Advertisement
microrobotics

Benewake TF03 LiDAR sensor

Mar 31st, 2023
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. The Benewake TF03 LiDAR sensor is a range sensor that can measure distances up to 100 meters. It uses UART communication to send distance and strength data. Here's an example of how to use the TF03 with an Arduino to read the distance and display it on the Serial Monitor:
  3.  
  4. To wire the TF03 LiDAR sensor, connect its 5V pin (or VIN pin) to the 5V pin on the Arduino and the GND pin to the ground. Connect the sensor's TX pin to the RX_PIN (pin 10) on the Arduino and the RX pin to the TX_PIN (pin 11) on the Arduino.
  5.  
  6. This code will continuously read the distance and signal strength from the TF03 sensor and print them on the Serial Monitor. Note that the TF03 sensor might require a logic level converter if used with a 3.3V Arduino board, as it operates at 5V logic levels.
  7. */
  8.  
  9. #include <SoftwareSerial.h>
  10.  
  11. const int RX_PIN = 10; // TF03 RX connected to Arduino pin 10
  12. const int TX_PIN = 11; // TF03 TX connected to Arduino pin 11
  13.  
  14. SoftwareSerial tf03Serial(RX_PIN, TX_PIN); // Declare a SoftwareSerial object
  15.  
  16. void setup() {
  17.   Serial.begin(9600);
  18.   tf03Serial.begin(115200); // TF03 default baud rate is 115200
  19.  
  20.   delay(500); // Wait for the sensor to initialize
  21. }
  22.  
  23. void loop() {
  24.   int distance = -1;
  25.   int strength = -1;
  26.  
  27.   if (readTF03Data(distance, strength)) {
  28.     Serial.print("Distance: ");
  29.     Serial.print(distance);
  30.     Serial.print(" cm, Strength: ");
  31.     Serial.println(strength);
  32.   } else {
  33.     Serial.println("Failed to read data from TF03");
  34.   }
  35.  
  36.   delay(500); // Wait 500ms between readings
  37. }
  38.  
  39. bool readTF03Data(int &distance, int &strength) {
  40.   const int FRAME_SIZE = 9;
  41.   byte frame[FRAME_SIZE];
  42.  
  43.   // Look for the start of a valid frame
  44.   while (tf03Serial.available()) {
  45.     if (tf03Serial.read() == 0x59) {
  46.       if (tf03Serial.available() && tf03Serial.read() == 0x59) {
  47.         // Read the rest of the frame
  48.         tf03Serial.readBytes(frame, FRAME_SIZE);
  49.  
  50.         // Calculate checksum
  51.         byte checksum = 0x59 + 0x59;
  52.         for (int i = 0; i < 8; i++) {
  53.           checksum += frame[i];
  54.         }
  55.  
  56.         // Check if checksum matches
  57.         if (checksum == frame[8]) {
  58.           distance = frame[0] | (frame[1] << 8);
  59.           strength = frame[2] | (frame[3] << 8);
  60.           return true;
  61.         }
  62.       }
  63.     }
  64.   }
  65.  
  66.   return false;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement