Example Code for Raspberry Pi-Distance Measurement

This project shows how to connect the TF03 laser range sensor to a Raspberry Pi via UART and read real-time distance and signal-strength data using Python.

Hardware Preparation

  • Raspberry Pi 4B x 1
  • Raspberry IO Expansion Board x 1
  • TF03(TOF) Laser Range Sensor(180m) x 1
  • Connector x 1

Wiring Diagram

SEN0328 TF03 Laser Range Sensor(100m) Connection with Raspberry Pi

Other Preparation Work

Enable UART on the Raspberry Pi and ensure the sensor is connected to the correct UART pins.

Sample Code

# -*- coding:utf-8 -*-

'''
  # DFRobot_TFmini.py
  #
  # Connect board with raspberryPi.
  # Run this demo.
  #
  # Connect TFmini to UART
  # get the distance value
  #
  # Copyright   [DFRobot](https://www.dfrobot.com), 2016
  # Copyright   GNU Lesser General Public License
  #
  # version  V1.0
  # date  2019-8-31
'''

import time

from DFRobot_TFmini import TFMINI

mini = TFMINI()

def main():
    while True:
        if mini.measure():
            distance = mini.getDistance()
            strength = mini.getStrength()
            print("Distance = %.d" % distance)
            print("Strength = %.d" % strength)
            time.sleep(0.5)
        time.sleep(0.5)

if __name__ == "__main__":
    main()

Result

The Raspberry Pi will print the distance and signal strength in the terminal:

Distance = 100
Strength = 688

Was this article helpful?

TOP