# Arduino Serial communication troubles

I'm having problems getting my communication code to work. I enter the data 1, 0, 255, 50 and then it errors (shouldn't it wait until 8 bits have been sent?) it exits with my debug message of BadPacket and StartPacket, and then prints the number 49, indicating that it thought the first packet was 49. What's going on here?

This is what I am using:

const uint8_t kACKBit = 6;
const uint8_t kNACKBit = 25;
const uint8_t kStartBit = 1;

void setup()
{
Serial.begin(115200);

}

void loop()
{
if(Serial.available() >= 8)
{
}

}

{
//flush the buffer and send a request to resend the data
Serial.flush();
Serial.print(kNACKBit);

}
void goodPacket()
{
//Packet good - send an acknowledgement
Serial.println("Good Packet");
Serial.print(kACKBit);
}

{
uint8_t startPacket = 10;
if (startPacket != kStartBit)
{
Serial.println("StartPacket");
Serial.println(startPacket, DEC);
return;
}

//check that the address is valid
{
return;
}

//combine the two values into a single int
uint16_t duration = (high_byte << 8) + low_byte;

//check that it ends in a null teminator
{
Serial.println("nullterm");
return;
}

//confirmed packet - send ack signal
goodPacket();
return;
}

• are you trying to read individual bits there? it's not unheard of, but it would seem like with the arduino, there'd already be a library that would let you work in bytes. Jun 14, 2011 at 11:13
• Yeah, that is where your confusion is coming from. Serial.available() and Serial.read() are done in whole bytes, not individual bits. That said, I would try Serial.flush() 'ing in your setup fxn because as you stated, if you are in fact only sending 4 bytes {1,0,255,50}, then you should still be in the loop waiting for Serial.available() to reach 8. So it is my belief that you are not sending your data correctly... or at least not the way you think you are. Jun 14, 2011 at 12:28
• Sorry I meant bytes. A was a bit tired, it was midnight I was trying to get it working before I went to bed. Anyways, when I says Badpacket it also does a Serial.flush and then it will error again after another 4 bytes, not 8. Jun 14, 2011 at 14:14
• Just figured it out - although I'm still not sure how the serial protocol works. I was sending the ASCII character that corresponds to the number 1 instead of the plain number 1. I don't know why but I guess when you send ASCII text it takes 2 bytes instead of one? Jun 14, 2011 at 14:47
• Ah - when I sent the multi-digit numbers I was sending multiple bytes that explains it. Jun 14, 2011 at 15:01