Go Down

Topic: Small syntax question (Read 1 time) previous topic - next topic


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: http:// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1160543432

Here's my code
Code: [Select]
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 = Serial.read();  // 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 = Serial.read(); // 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
Code: [Select]
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:
Code: [Select]
if (Serial.available() >= 2) or replacing the Serial.println() with a delay.


Code: [Select]
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.

Go Up