Professional Documents
Culture Documents
Serial Comunication
Serial Comunication
In the following sketch, we are using the serial communication to turn ON and OFF an LED. We will
use LED 13 (it is integrated in the motherboard) so, we do not need to use the protoboard. When we
send the character “a” throw the Serial Monitor to ARDUINO, the LED will turn OFF, and when we
send “b” the LED will turn ON.
int option;
void setup(){
Serial.begin(9600);
pinMode(led, OUTPUT);
void loop(){
}
}
Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 1
In this example, we are sending a number between 1 and 9 and we will make an LED blink that number
of times. The code is similar to the previous one, but in this case, we need a number (not a character) so
we have to subtract “0” to the character and Arduino converts it to a number.
int option;
void setup(){
Serial.begin(9600);
pinMode(led, OUTPUT);
void loop(){
char option = Serial.read(); // we read the character written in the keyboard
if (option >= '1' && option <= '9') //if the character is between '1' and '9’.
{
for( int i=0 ; i<option; i++){ // LED will blink that number of times
delay(100);
delay(200);
}
}
}
There is another way to get a numerical value written with the keyboard. It is using the function
“parseInt”.
Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 2
int option;
void setup(){
Serial.begin(9600);
pinMode(led, OUTPUT);
void loop(){
if (option >= 1 && option <= 9) // if the character is between 1 and 9
// when using numbers, do not put ‘1’ because Arduino would think it is a character
{
delay(100);
delay(200);
}
}
}
Be careful: in this practice ‘option’ works like an integer, in the previous it works like a character. That
is the reason we modify the if (option >= 1 && option <= 9) with or without the ‘’ in the
numbers.
Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 3