You are on page 1of 8

Commands in Arduino

This section covers the small set of commands you need to make the Arduino do something
useful.

You could make a great machine using only digital read, digital write and delay commands,
but learning all the commands here will take you to the next level.

Serial.print

The Serial.print command lets you see what's going on inside the Arduino from your
computer.

For example, you can see the result of a math operation to determine if you are
getting the right number. Or, you can see the state of a digital input pin to see if the
Arduino is a sensor or switch properly. When your interface circuits or program does
not seem to be working, use the Serial.print command to check the situation. For this
command to show anything, you need to have the Arduino connected to the host
computer with the USB cable.

For the command to work, the command Serial.begin(9600); must be placed in the
setup() function. After the program is uploaded, you must open the Serial Monitor
window (in tools) to see the response.

There are two forms of the print command. Serial.print() prints on the same line
while Serial.println() starts the print on a new line.

Here is a brief program to check if your board is alive and connected to the PC

void setup()
{
Serial.begin(9600);
Serial.println("Hello World");
}
void loop() {}

Here is a program that loops in place, displaying the value of an I/O pin. This is
useful for checking the state of sensors or switches and to see if the Arduino is
reading the sensor properly.

Try it out on your Arduino. After uploading the program, use a jumper wire to
alternately connect pin 4 to +5V and to GND.

void setup()

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 1
{
Serial.begin( 9600 );
Serial.println("Hello World");
}

void loop()
{
Serial.println( digitalRead(4) );
delay( 100 );
}

If you wanted to see the states of pins 4 and 5 at the same time, you can chain a few
print commands; noting that the last command is a println to start a new line.

void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print( "pin 4 = " );
Serial.print( digitalRead(4) );
Serial.print(" pin 5 = ");
Serial.println( digitalRead(5) );
}

“IF” Command

We have already used it in the “Interactive Traffic light” project, but it is interesting
to review and explain it, because it is probably one of the most useful commands.

This is the basic conditional branch instruction that allows your program to do two
different things depending on whether a specified condition is true or false.

Here is one way to have your program wait in place until a


switch is closed. Connect a switch to pin 3 as shown in the
image. Upload this program then try closing the switch.

void setup()
{
Serial.begin(9600);
}
void loop()
{
if (digitalRead(3) == HIGH) {
Serial.println( "Somebody closed the switch!" );
}

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 2
}

The if line reads the state of pin 3. If it is LOW, which it will be for this circuit when
the switch is open, the code jumps over the Serial.println command and will repeat
the loop. When you close the switch, 5V is applied to pin 3 and its state is now
HIGH. This means the if condition is true so this time around the code between the
braces is executed and the message is printed

The syntax for the if statement is

if (condition) {
//commands
}

If the condition is TRUE, the program will execute the commands between the
braces. If the condition is FALSE (not true), the program will skip to the statement
following the braces.

The condition compares one thing to another. In the example above, the state of pin 1
was compared to LOW with ==, the equality condition.

Some conditional operators are:

== (equal to
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)

You can have the program branch depending on the value of a variable. For example,
this program will print the value of i only when it is less than 30.

int i;
void setup()
{
Serial.begin(9600);
i=0;
}
void loop()
{
i=i+1;
if (i<30) {
Serial.println(i);
}
}

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 3
Exercise:

1. Take the Morse Code Sketch and modify it to use a push button. When you push
the button, it will blink the SOS message. Save it as “if exercise”

if…else

if/else allows greater control over the flow of code than the basic if statement, by
allowing multiple tests to be grouped together. For example, an analog input could be
tested and one action taken if the input was less than 500, and another action taken if
the input was 500 or greater. The code would look like this:

if (pinFiveInput < 500)


{
// action A
}
else
{
// action B
}
else can proceed another if test, so that multiple, mutually exclusive tests can be run
at the same time.

Exercise:

2. Using the “if…else“ command, write the code to make a sound when you push
the button, and when you are not pushing it, an LED is ON.

Save it as “if_else exercise”

for

The for statement is used to create program loops. Loops are useful when you want
an action to be repeated a specified number of times. A variable is used to count the
number of times the code is repeated. Here is an example that flashes an LED
attached to pin 2 five times.

int a;
void setup()
{
pinMode( 2,OUTPUT );
for ( a=0; a<5; a++ ) {

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 4
digitalWrite( 2,HIGH );
delay( 250 );
digitalWrite( 2,LOW );
delay( 250 );
}
}
void loop() {}

The variable a is the loop counter. The for() statement has three parts: the
initialization, the check and the increment. Variable a is initialized to zero. The check
is to see if a is less than 5. If so, the commands between the braces are executed. If
not, those commands are skipped. After the check, a is incremented by 1 (the a++
command). While the for statement could read for (a=1 ;a<5; a++), it is convention to
start the counter variable at zero and use “ less than” for the condition check.

You can have the loop counter increment by two or by three or by any increment you
want. For example, look at the following sketch. Now the variable is “i” instead of
“a”. Of course, the name of the variable does not affect at all.

Can you imagine what will happen? How many times will it be repeated? Try it and
check if your answers were right.

int i;
void setup()
{
Serial.begin( 9600 );
for (i=0; i<15; i=i+3) {
Serial.println(i);
}
}
void loop() {}

Loops can be nested (one inside another) within loops. This example will flash the
LED 10 times because for each of the five outer loops counted by i, the program goes
twice through the inner loop counted by j.

Do you understand it? Try and check.

int i,j; // two variables


void setup()
{
pinMode(2,OUTPUT);
for (i=0;i<5;i++) {
for(j=0;j<2;j++) {
digitalWrite( 2,HIGH );
delay( 250 );
digitalWrite( 2,LOW );
delay( 250 );
}

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 5
}
}
void loop() {}

Exercise:

3. Take the Morse Code Sketch again and now modify it using “for” so that it sends
the SOS message three times when you push the button.

Save it as “for exercise”

while

The while statement is another branch command that does continuous looping. If the
condition following the while is true, the commands within the braces are executed
continuously, so the program can’t go on until the condition becomes false.

Here is an example that continuously reads a switch on pin 3, and does nothing
(because in this case there is nothing between the braces) until the switch is pressed.
Then, the condition is no longer true so the code escapes the while command and
prints.

void setup()
{
Serial.begin(9600);
while( digitalRead( 3 ) == LOW ) {
}
Serial.println( "Switch was pressed" );
}
void loop() {}

Exercise:

4. Take the Morse Code again and modify it using “while”.

It must send the message continuously until you press the button. Then, it stops
and does not start again when you release the button. Save it as “While exercise
1”

5. Modify it. It must start again when you release the button. Save it as “while
exercise 2”

6. Modify exercise 2 so that it writes “Message stopped” in the Serial Monitor


when you push the button. Save it as “while exercise 3”

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 6
PUSH Button. Exercise with Serial Monitor. Counting clicks

Now we will learn to count how many times you press a button in order to do
different things depending on the number of times.

This is the Circuit: we are


using LED 13. If you want to
use another one, connect it
and change the necessary
commands in the code

We need to store the number


of clicks in a variable.

Look at the code and be sure


you understand every
command.

// this constant won't


change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
// initialize the button pin as an input:
pinMode( buttonPin, INPUT );
// initialize the LED as an output:
pinMode( ledPin, OUTPUT );
// initialize serial communication:
Serial.begin( 9600 );
}
void loop() {
//read the pushbutton input pin:
buttonState = digitalRead( buttonPin );
// compare the buttonState to its previous state
if( buttonState != lastButtonState) {
// if the state has changed, increment the counter
if ( buttonState == HIGH ) {
// if the current state is HIGH then the button
// changes from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 7
// wend from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// The modulo function gives you the remainder of
// the division of two numbers:
if ( buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}

Try it and open the Serial Monitor to see the number of clicks and the result in the
LED.

Save it as “Push Button and multiple clicks” in your USB key.

PUSH Button . 3 and 4 clicks

Could you change the code in order to make it turn on a LED when you click the
button three times and when you click four times turn it off and turn on another one?

Save it as “Push Button with 3 and 4 clicks” in your USB key

Doctor Areilza, 32. 48010 Bilbao Tel. 944 271 818 Fax 944 396 098 E-mail: colegio@indautxujesuitak.org 8

You might also like