I'm trying to read from source that is constantly outputting 3 bytes at time. It should be a number between 0 and 60 and another number.
Here is code;
#include <SoftwareSerial.h>
SoftwareSerial MyBlue(0, 1);
unsigned long number2 = 0;
uint8_t *p = (uint8_t *)&number2;
uint16_t *pNumber2 = (uint16_t *)&number2;
void setup() {
Serial.begin(9600);
MyBlue.begin(9600);
}
void loop() {
if (Serial.available()) {
uint8_t number1;
Serial.readBytes(p, 3);
// store number, 8bits
number1 = p[2];
// clear high order 16 bits -- now number2 is just the low order 16bits
p[2] = p[3] = 0;
char buffer[512];
sprintf(buffer, "number1: %hu, number2: %lu, *pu: %u", (uint16_t)number1, number2, *pNumber2);
Serial.println(buffer);
}
}
The problem is that number2 is sometimes very large and number1 is sometimes zero. I don't understand why this is happening. I know the data is coming in very fast. Anything I am doing wrong? number2 should be between 0 & 60, and number1 should be 15. I have validated that client side is correct.
How it should work. Reads 2 numbers into 4byte buffer, unsigned long. One number is 8bits and the other is 16bits. I send them from Bluetooth client as 3 bytes. On the Arduino side, I read them into unsigned long, 3 bytes at a time; 4th byte is unused. Then assign (&buffer)[2] to 8 bit unsigned number, and &buffer to 16bit unsigned number (after clearing the most significant 16bits to 0).
Can anyone see what is wrong? Is it systematic of data coming in too fast?
Thanks!