I'm trying to send an integer between 0 and 400 each second via serial port, and display it in Qt. The problem is that I'm reading inconsistent numbers like so:
174, 229, 397, 51, 220, 18, 1, 42
Here is my Arduino Code:
int data = 0; // variable to send via serial
unsigned long deltaTime;
unsigned long oldTime = 0;
void setup() {
// initialize the serial communication:
Serial.begin(9600);
}
void loop() {
// decompose the integer into low and high bytes
byte b0 = lowByte(data);
byte b1 = highByte(data);
// Create a buffer and store the two bytes in it
byte buff[2];
buff [0] = b0;
buff [1] = b1;
deltaTime = millis() - oldTime;
// When one second is passed send Data
if (deltaTime > 1000) {
// Send the packet
Serial.write(buff,2) ;
oldTime = millis();
}
// incremment the integer:
data++;
if(data >= 400 ) data = 0;
}
And here is the Slot code in Qt:
void MainWindow::readData(){
// read two bytes at once
QByteArray data = serial->read(2);
// convert them back to int and display
unsigned char b0 = (unsigned char)data[0];
unsigned char b1 = (unsigned char)data[1];
int val = (int)b1 * 256 + (int)b0 ;
qDebug()<< val << endl;
}