Hi folks,
I'm sending ints of serial one byte at a time, and putting the received data into an array declared as an int. The bytes are correctly assigned, but the program is treating the elements of the int array as unsigned ints, and I'm getting numbers over 60,000 whenever a negative is sent. The code is super long, and I know the correct bytes are being assigned so I'll only post the relevant portions of code. Note that I'm sending the data as total number of bytes first, then array location, MSB, LSB. Any thoughts on why I'm getting unsigned values would be appreciated.
Receive the data:
And the parse code:
I'm sending ints of serial one byte at a time, and putting the received data into an array declared as an int. The bytes are correctly assigned, but the program is treating the elements of the int array as unsigned ints, and I'm getting numbers over 60,000 whenever a negative is sent. The code is super long, and I know the correct bytes are being assigned so I'll only post the relevant portions of code. Note that I'm sending the data as total number of bytes first, then array location, MSB, LSB. Any thoughts on why I'm getting unsigned values would be appreciated.
Receive the data:
Code:
while (Serial1.available()) {
if (debugOn) Serial.println("incoming");
msb = Serial1.read();
if (temp == 0xFFFF) {
activedata = 1;
i = 0;
//temp = 0;
}
if (debugOn) Serial.println(msb);
temp = (temp >> 8) + (msb << 8);
if (activedata) {
if (debugOn) Serial.print("i=");
if (debugOn) Serial.println(i);
if (i == 0) {
if (msb <= maxRec) {
inputs[i] = msb;
i++;
}
else {
activedata = 0;
i = 0;
}
}
else if (i < (inputs[0])) { //inputs[0] counts from 0. Use < to ensure we only catch up to inputs[0] - 1
inputs[i] = msb;
i++;
}
else if (i == (inputs[0])) {
inputs[i] = msb;
i = 0;
activedata = 0;
if (debugOn) Serial.println("parse called");
parse();
}
}
}
And the parse code:
Code:
void parse() {
int x = 1;
int readMSB = 0;
int recCheckSum = 0;
int checkSum = 0;
for (int j = 0; j <= (inputs[0] - 2); j++) {
recCheckSum = recCheckSum + inputs[j];
}
if (debugOn) Serial.print("recCheckSum=");
if (debugOn) Serial.println(recCheckSum);
checkSum = inputs[inputs[0]];
checkSum = inputs[inputs[0] - 1] + (checkSum << 8);
if (debugOn) Serial.print("checkSum=");
if (debugOn) Serial.println(checkSum);
while ((x <= (inputs[0] - 2)) && (inputs[0] <= maxRec) && (checkSum == recCheckSum)) { //Use inputs[0] - 2 to avoid re-reading checksum. maxRec to avoid overrun allocated memory.
//inputsInts[(x>>1)] = inputs[x] + (inputs[x+1] << 8);
readMSB = (int)inputs[x + 2];
if (inputs[x] < 12) {
inputsInts[inputs[x]] = inputs[x + 1] + ((int)readMSB << 8);
//if (inputsInts[inputs[x]] >> 15) {
//inputsInts[inputs[x]] = -1 * (~inputsInts[inputs[x]]);
//}
}
x = x + 3;
}
}