Example Code for Arduino-Distance Measurement

Use Arduino Uno with software serial to read distance and signal strength from TF03, and display the results on a PC serial port tool.

Hardware Preparation

Software Preparation

Wiring Diagram

SEN0328 TF03 Laser Range Sensor(100m) Arduino Connection

Other Preparation Work

Since the TF mini is a serial device and the ordinary Arduino has only one hardware serial, we recommand using the sensor together with a software serial. Of course, users can also use device with multi-serial port, such as Arduino Leonardo, Arduino Mega2560 and so on. Here we use the common Arduino Uno as the controller, and define D12 and D13 as software serial port.

Sample Code

/*
  * @File  : DFRobot_TFmini_test.ino
  * @Brief : This example use TFmini to measure distance
  *         With initialization completed, we can get distance value and signal strength
  * @Copyright   [DFRobot](https://www.dfrobot.com), 2016
  *             GNU Lesser General Public License
  *
  * @version  V1.0
  * @date  2018-1-10
*/
  
#include <DFRobot_TFmini.h>

SoftwareSerial mySerial(12, 13); // RX, TX

DFRobot_TFmini  TFmini;
uint16_t distance,strength;

void setup(){
    Serial.begin(115200);
    TFmini.begin(mySerial);
}

void loop(){
    if(TFmini.measure()){                      //Measure Distance and get signal strength
        distance = TFmini.getDistance();       //Get distance data
        strength = TFmini.getStrength();       //Get signal strength data
        Serial.print("Distance = ");
        Serial.print(distance);
        Serial.println("cm");
        Serial.print("Strength = ");
        Serial.println(strength);
        delay(500);
    }
    delay(500);
}

Result

The following shows the data format displayed in the serial monitor:

Dis: 05.000 m
Str: 00600

Was this article helpful?

TOP