I’m using two TF-Luna LiDAR sensors to measure speed. To calculate it accurately, I need to calibrate the threshold that determines when the LiDAR starts timing. My setup currently uses UART communication, and while it gives distance readings, it reacts slowly when the distance changes and sometimes doesn’t output any data at all. It also doesn’t update consistently every 0.5 seconds as expected.
the code:
#include <HardwareSerial.h>
// Using serial ports 1 and 2 for two sensors
HardwareSerial lidarSerial1(1);
HardwareSerial lidarSerial2(2);
// Pin definitions for ESP32-S3
#define RXD1 6 // Sensor 1 RX
#define TXD1 7 // Sensor 1 TX
#define RXD2 17 // Sensor 2 RX
#define TXD2 16 // Sensor 2 TX
void setup() {
Serial.begin(115200);
// Initialize both serial ports
lidarSerial1.begin(115200, SERIAL_8N1, RXD1, TXD1);
lidarSerial2.begin(115200, SERIAL_8N1, RXD2, TXD2);
Serial.println("Dual TF-Luna Distance Detection - UART Mode");
Serial.println("Sensor 1 | Sensor 2");
Serial.println("---------|----------");
}
void loop() {
int dist1 = readTFLuna(lidarSerial1);
int dist2 = readTFLuna(lidarSerial2);
// Display distances
if (dist1 > 0) {
Serial.print("S1: " + String(dist1) + " cm");
} else {
Serial.print("S1: --- ");
}
Serial.print(" | ");
if (dist2 > 0) {
Serial.println("S2: " + String(dist2) + " cm");
} else {
Serial.println("S2: ---");
}
delay(100);
}
int readTFLuna(HardwareSerial &serial) {
uint8_t buf[9] = {0};
if (serial.available() >= 9) {
serial.readBytes(buf, 9);
if (buf\[0\] == 0x59 && buf\[1\] == 0x59) {
uint16_t distance = buf\[2\] + buf\[3\] \* 256;
return distance;
}
}
return -1; // Return -1 if no valid reading
}
Please edit your post to add code tags (editor <code> button).
When using each of the two sensors one at a time (with appropriately modified code) do they always behave as expected?