Small syntax question

Hey guys,

Hoping someone could help with this small bit of code. I mad a small sketch to light a LED connected the pin which the user selects over the serial connection, eg type 13 to turn on the LED on pin 13, 07 to turn on LED on pin 7 etc…
I heavily used the code from Gian Pablo Villamil (username gpvillamil) posted here:

Here’s my code

byte incomingByte ; 
int LEDpin;
void setup() { 
 void loop() { 

  if (Serial.available()) {         // if serial data waiting
    digitalWrite(LEDpin,LOW);       // if so, turn off previously lit LED

    LEDpin = 0;                     // reset pin variable
     for (int i = 0; i <=1; i++) {  // for the first two bytes (i.e. 0 and 1)
       incomingByte =;  // read byte
       Serial.println(incomingByte,DEC);   // print what was read
       LEDpin = LEDpin * 10 + (incomingByte - 48);  // assemble full 2-digit integer
     Serial.print("Lighting up LED #");   // Display which LED will be lit
     digitalWrite(LEDpin,HIGH);     // Light up LED
    while (Serial.available()) {  
     incomingByte =; // clear the buffer 

It all works really well, but here’s my question. If I comment out the line

Serial.println(incomingByte,DEC); // print what was read

it doesn’t work anymore…

What does this line do besides print the byte values out to screen? Does it somehow change the type of incomingByte?

Thanks for your help.

The issue is a bit subtle. Basically, the call to Serial.println() takes long enough for the second byte of serial data to arrive. The check if (Serial.available()) is true as soon as a single byte of data is available; if you then try to read two bytes in succession, the second one will be -1 because no real data is available. You could try changing the test to: if (Serial.available() >= 2) or replacing the Serial.println() with a delay.

if (Serial.available() >= 2)

That did it - awesome, thanks heaps.

If I could make a suggestion, it would be awesome if there was an example simmilar to this in function. As a newcomer to programming, especially serial communications, it took me ages to work out how to read more than the first byte, and I don't think I ever would have got the process of converting the bytes into a multi-digit integer without the code I linked to. Anyways just my thoughts, it may have been obvious to everyone else.