I thought I’d drop this here for someone who needed a copy-paste solution.

I am parsing a serial string output from a YDLIDAR X4 rotating lidar. I have to do this because the library sucks. a lot. I mean I’m not over my heels with the unit anyhow, first off who the hell outputs at 128,000 baud? I’ll post the code when it’s done enough for someone to build off of it.

I was getting an error in number of bytes in the packet as parsed from the serial string so I had to break out the function into really busy but obvious code to see where I was going wrong. The code has me concatenating two bytes and an upper nibble. Ignore the discrepancy in how I added my bytes backwards in my code vs. how the device actually stacks it’s data… because you know: WHO IN THEIR RIGHT MIND SHIFTS LSB ON THE LEFT?! (note the “length bytes as shown in 12 bits and the “response length” example below.)

Anyhow… feel free to show me how to do it better in the comments. Obviously this is built for you to look at it do it’s magic in a serial monitor.

//Arduino Friendly.
unsigned long rx_make_length(byte b1, byte b2, byte b3) {
  unsigned int msb_bits = 0; 
  unsigned long length_value = 0;
  
  //drop the lower nibble and prep for OR-ing.
  b3 = b3 >> 4;

  Serial.print("c w/ nibble removed and right shift: "); Serial.println(b3, HEX);

  msb_bits = b1;   
  msb_bits = msb_bits << 8;
  Serial.print("b1 shifted up 8 : "); Serial.println(msb_bits, HEX);
  msb_bits = msb_bits | b2;
  Serial.print("b1 concatenated w/ b2: "); Serial.println(msb_bits, HEX);
  length_value = msb_bits;
  length_value = length_value << 4; 
  Serial.print("b1 concatenated w/ b2 w/ shift: "); Serial.println(length_value, HEX);
  length_value = length_value | b3;
  Serial.print("b1 concatenated b2 and b3: "); Serial.println(length_value, HEX);

  return length_value;
}

//unsigned long my_value = rx_make_lenth(a, b, c);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: