Electronic – Arduino Serial communication troubles

arduinocommunicationprocessingserial

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)
   {
     readData();
   }

}

void badPacket()
{
    //flush the buffer and send a request to resend the data
    Serial.flush();
        Serial.println("Bad Packet");
    Serial.print(kNACKBit);

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


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

    //check that the address is valid
    uint8_t address = Serial.read();
    if(address >= 6)
    {
        badPacket();
                Serial.println("address");
        return;
    }

    //read in the RGB values
    uint8_t r = Serial.read();
    uint8_t g = Serial.read();
    uint8_t b = Serial.read();

    //read in the duration
    uint8_t high_byte = Serial.read();
    uint8_t low_byte = Serial.read();

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

    //check that it ends in a null teminator
    if(Serial.read() != 0)
    {       
        badPacket();
                Serial.println("nullterm");
        return;
    }

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

Best Answer

It looks like you're confusing the ASCII values of the numbers with the numbers themselves.

If you send a '1' character over the serial port, you're actually sending the byte 49 (0x31). This is why you're seeing the invalid 49.

Either change your code to understand ASCII, or send the raw bytes instead of ASCII digits.