Example Code for Arduino-Distance Measurement

Last revision 2025/12/31

Use Arduino UNO R3 (or similar) with TOF Sense Laser Ranging Sensor (5m) to measure distance. With initialization completed, you can get distance value, distance status, and signal strength, which will be displayed in the PC serial tool interface.

Hardware Preparation

  • DFRduino UNO R3 (or similar) x 1
  • TOF Sense Laser Ranging Sensor (5m) x 1
  • M-M/F-M/F-F Jumper wires

Software Preparation

Wiring Diagram

Use the PC-side serial port software to display the distance detected and to power the entire system.

SEN0337 TOF Sense Laser Range Sensor (5m) Connection Diagram

Other Preparation Work

Since TOF Sense is a serial port device, while the average Arduino has only one hardware serial port. So, it is recommended to use a soft serial port to work with sensors, and users can also use multiple serial devices, such as Arduino Leonardo, Arduino Mega2560, etc. The most common one--Arduino UNO is used here as a controller, defining D10 and D11 as soft string ports.

Sample Code

PC serial tool is required, and the data read will be displayed in the serial tool interface

/*!
 * @file  DFRobot_TFmini_test.ino
 * @brief This example use TFmini to measure distance
 * @n With initialization completed, we can get distance value and signal strength
 * @copyright  Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
 * @license  The MIT License (MIT)
 * @author  DFRobot
 * @version  V1.0
 * @date  2018-01-10
 */
#include <SoftwareSerial.h>

int i;
int dat[32] = { 0 };
unsigned long a, p, q, z;
SoftwareSerial mySerial(11, 10); // RX, TX

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

void loop()
{
  if (mySerial.available() >= 32) {
    if (millis() - a > 500) {
      a = millis();
      for (i = 0;i < 32;i++) {
        dat[i] = mySerial.read();
      }
      for (i = 0;i < 16;i++) {
        if (dat[i] == 0x57 && dat[i + 1] == 0 && dat[i + 2] == 0xff && dat[i + 3] == 0) {
          if (dat[i + 12] + dat[i + 13] * 255 == 0) {
            Serial.println("Out of range!");
          } else {
            z = dat[i + 11];
            Serial.print("Status = ");
            Serial.print(z);
            p = dat[i + 12] + dat[i + 13] * 255;
            Serial.print("  Strength = ");
            Serial.print(p);
            q = dat[i + 8] + dat[i + 9] * 255;
            Serial.print("  Distance = ");
            Serial.print(q);
            Serial.println("mm");
          }
          break;
        }
      }
    }
  }
}

Result

SEN0337 TOF Sense Laser Range Sensor (5m) Expected Results

Was this article helpful?

TOP