Advertisement
microrobotics

TF02 LiDAR Sensor Range 22m

Mar 31st, 2023
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. The TF02 LiDAR sensor is a range sensor that can measure distances up to 22 meters. It uses UART communication to send distance and strength data. Here's an example of how to use the TF02 with an Arduino to read the distance and display it on the Serial Monitor:
  3.  
  4. To wire the TF02 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 TF02 sensor and print them on the Serial Monitor. Note that the TF02 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; // TF02 RX connected to Arduino pin 10
  12. const int TX_PIN = 11; // TF02 TX connected to Arduino pin 11
  13.  
  14. SoftwareSerial tf02Serial(RX_PIN, TX_PIN); // Declare a SoftwareSerial object
  15.  
  16. void setup() {
  17.   Serial.begin(9600);
  18.   tf02Serial.begin(115200); // TF02 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 (readTF02Data(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 TF02");
  34.   }
  35.  
  36.   delay(500); // Wait 500ms between readings
  37. }
  38.  
  39. bool readTF02Data(int &distance, int &strength) {
  40.   const int FRAME_SIZE = 7;
  41.   byte frame[FRAME_SIZE];
  42.  
  43.   // Look for the start of a valid frame
  44.   while (tf02Serial.available()) {
  45.     if (tf02Serial.read() == 0x59) {
  46.       if (tf02Serial.available() && tf02Serial.read() == 0x59) {
  47.         // Read the rest of the frame
  48.         tf02Serial.readBytes(frame, FRAME_SIZE);
  49.  
  50.         // Calculate checksum
  51.         byte checksum = 0x59 + 0x59;
  52.         for (int i = 0; i < 6; i++) {
  53.           checksum += frame[i];
  54.         }
  55.  
  56.         // Check if checksum matches
  57.         if (checksum == frame[6]) {
  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