User Manual
173
/
223
Serial.println("Cleared");
}
}
}
Everything that happens inside the loop is contained within an 'if' statement. So
unless the call to the built-in Arduino function 'Serial.available()' is 'true' then
nothing else will happen.
Serial.available() will return 'true' if data has been send to the MEGA2560 and is
there ready to be processed. Incoming messages are held in what is called a buffer
and Serial.available() returns true if that buffer is Not empty.
If a message has been received, then its on to the next line of code:
char ch = Serial.read();
This reads the next character from the buffer, and removes it from the buffer. It also
assigns it to the variable 'ch'. The variable 'ch' is of type 'char' which stands for
'character' and as the name suggests, holds a single character.
If you have followed the instructions in the prompt at the top of the Serial Monitor,
then this character will either be a single digit number between 0 and 7 or the letter
'x'.
The 'if' statement on the next line checks to see if it is a single digit by seeing if 'ch'
is greater than or equal to the character '0' and less than or equal to the character
'7'. It looks a little strange comparing characters in this way, but is perfectly
acceptable.
Each character is represented by a unique number, called its ASCII value. This means
that when we compare characters using <= and >= it is actually the ASCII values that
were being compared.
If the test passes, then we come to the next line:
int led = ch – '0';
Now we are performing arithmetic on characters! We are subtracting the digit '0'
from whatever digit was entered. So, if you typed '0' then '0' – '0' will equal 0. If you
typed '7' then '7' – '0' will equal the number 7 because it is actually the ASCII values
that are being used in the subtraction.
Since that we know the number of the LED that we want to turn on, we just need to
set that bit in the variable 'leds' and update the shift register.
bitSet(leds, led);
updateShiftRegister();










