Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The TF-Luna is a compact LiDAR range sensor that can measure distances from 0.2 to 8 meters. It uses UART communication to send distance and strength data. Here's an example of how to use the TF-Luna with an Arduino to read the distance and display it on the Serial Monitor:
- To wire the TF-Luna sensor, connect its 5V pin (or 3.3V pin, depending on the sensor model) to the corresponding power 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.
- This code will continuously read the distance and signal strength from the TF-Luna sensor and print them on the Serial Monitor. The configureTFLuna() function is optional and can be used to change the sensor's configuration according to the datasheet.
- */
- #include <SoftwareSerial.h>
- const int RX_PIN = 10; // TF-Luna RX connected to Arduino pin 10
- const int TX_PIN = 11; // TF-Luna TX connected to Arduino pin 11
- SoftwareSerial tfLunaSerial(RX_PIN, TX_PIN); // Declare a SoftwareSerial object
- void setup() {
- Serial.begin(9600);
- tfLunaSerial.begin(115200); // TF-Luna default baud rate is 115200
- delay(500); // Wait for the sensor to initialize
- configureTFLuna(); // Configure the TF-Luna sensor
- }
- void loop() {
- int distance = -1;
- int strength = -1;
- if (readTFLunaData(distance, strength)) {
- Serial.print("Distance: ");
- Serial.print(distance);
- Serial.print(" cm, Strength: ");
- Serial.println(strength);
- } else {
- Serial.println("Failed to read data from TF-Luna");
- }
- delay(500); // Wait 500ms between readings
- }
- void configureTFLuna() {
- // This function sends the command to configure the TF-Luna (optional)
- // Check the datasheet for other possible configurations
- byte configCommand[] = {0x5A, 0x05, 0x0A, 0x00, 0x00, 0x01, 0x60};
- tfLunaSerial.write(configCommand, sizeof(configCommand));
- delay(100);
- }
- bool readTFLunaData(int &distance, int &strength) {
- const int FRAME_SIZE = 9;
- byte frame[FRAME_SIZE];
- // Look for the start of a valid frame
- while (tfLunaSerial.available()) {
- if (tfLunaSerial.read() == 0x59) {
- if (tfLunaSerial.available() && tfLunaSerial.read() == 0x59) {
- // Read the rest of the frame
- tfLunaSerial.readBytes(frame, FRAME_SIZE);
- // Calculate checksum
- byte checksum = 0;
- for (int i = 0; i < 8; i++) {
- checksum += frame[i];
- }
- // Check if checksum matches
- if (checksum == frame[8]) {
- distance = frame[0] | (frame[1] << 8);
- strength = frame[2] | (frame[3] << 8);
- return true;
- }
- }
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement