I have an Arduino Mega and I am using a LD06. Specs are here;
I keep getting garbled data from the device. It has a constant flow of data and I am using Serial2 to read it. The Mega has a 64 byte buffer
My latest attempt has been to clear the buffer and read straight into a temporary buffer and then process that.
This is what I have so far in my main sketch
#include <ArduinoSTL.h>
#include "LD06forArduino.h"
#include <algorithm>
LD06forArduino ld06;
void setup() {
Serial.begin(9600);
ld06.Init();
#if (RAMEND < 1000)
Serial.println("SERIAL_BUFFER_SIZE 16");
#else
Serial.println("SERIAL_BUFFER_SIZE 64");
#endif
}
void loop() {
ld06.getBuffer();
ld06.readBuffer();
}
LD06forArduino.cpp has this
(TOTAL_DATA_BYTE is defined as 47. The Mega has an incoming buffer of 64 so this should be ok)
#include "LD06forArduino.h"
std::vector<char> tmpChars;
std::vector<char> tmpBuffer;
void LD06forArduino::Init() {
Serial2.begin(230400);
}
void LD06forArduino::calc_lidar_data(std::vector<char> &values) {
for(int i=0; i<values.size(); i++){
Serial.print((uint8_t)values[i],HEX);
}
Serial.println();
}
void LD06forArduino::getBuffer(){
tmpBuffer.clear();
char tmpInt;
// Clear the buffer
while(Serial2.available()){Serial2.read();}
delay(1);
if (!Serial2.available()) {
Serial.println("No data");
//delay(10);
return;
}
for (int count = 0; count < TOTAL_DATA_BYTE*2; count++){
if (!Serial2.available()) {
delay(1);
}
tmpInt = Serial2.read();
tmpBuffer.push_back(tmpInt);
}
}
void LD06forArduino::readBuffer() {
tmpChars.clear();
if (tmpBuffer.size()==0) return;
for (int count = 0; count < tmpBuffer.size(); count++){
tmpInt = tmpBuffer[count];
int bSize = tmpChars.size();
if (tmpInt == 0x54 && (bSize == 0 || (bSize > 1 && tmpChars[1] != 0x2C)) ) {
// Start byte
tmpChars.clear();
tmpChars.push_back(tmpInt);
} else if (bSize == 0) {
// wait for a start byte
} else if (bSize == TOTAL_DATA_BYTE - 1 ) {
// - 1 this byte must be the CRC
tmpChars.push_back(tmpInt);
calc_lidar_data(tmpChars);
tmpChars.clear();
return;
}else if (bSize > 1 && tmpChars[1] != 0x2C) {
// Invalid sequence, 0x2C is fixed
tmpChars.clear();
} else{
tmpChars.push_back(tmpInt);
}
}
}
Once in a blue moon it will print a line
542C22B7101D87D96BB47F847F34C5DE3E73E937E7D3A4F9354E9DB01103B0DD801D03B1CDD1CE23E53E7
which means the starting sequence was hit but the values are not valid