0

My code:

char data;
int numOfBytes;
void setup() {
    Serial.begin(9600);
}
void loop()
{
    if (Serial.available() > 0)
    {
        int numOfBytes = Serial.available();
        Serial.print("numOfBytes: ");
        Serial.println(numOfBytes);

        data=Serial.read();
        Serial.print("data: ");
        Serial.print(data);
        Serial.print("\n-----------\n"); 

        delay(500);
    }
}

I expected that this code returns 5 and then 4,3,2,1.
But it returned: 1,4,3,2,1

Why?

3

This is because at the first execution only one byte was received. The Serial interface does not send the data in one big packet of 5 bytes, only because you typed five bytes and started the transmission of all with one press in enter. It is sending the bytes one by one, in other words serial (hence the name). The exact transmission time is dependend on many factors (especially, when other technologies are involved, like the USB interface, when you are transmitting over the Arduinos USB to serial converter).

In this case the first byte is sent, followed by a short break, then the other bytes. The Arduino is fast enough in checking the Serial interface to sense this at 9600 baud.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.