As simple as it may seem, knowing when something is either on or off can be a great tool for designing something useful.
This lesson will answer the following questions:
Is a button being pressed?
Has a switch been turned on?
What is the on/off sensor status?
When you can answer questions like these, you can implement actions based on the current status – if the button is pressed do this – otherwise, do that. If the sensor is HIGH take this action, otherwise do nothing. You get the gist. But before we can implement the actions, we have to be able to track the status and the changes of the digital pins.
If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it.
You Will Need
A momentary push button – this is a button that is spring-loaded, i.e. it never stays in a down position unless it’s held down.
Jumper wires (3)
A 10,000 Ohm resistor more commonly referred to as a 10K resistor
A very ripe banana, (1) – not completely useful, but nutritious
Step-by-Step Instructions
Connect the pushbutton to the breadboard.
Connect one side of the pushbutton to the 5-volt pin on the Arduino board using a jumper wire.
Connect one side of the 10K resistor to the other side of the pushbutton.
Connect the other side of the resistor to the ground pin on the Arduino. You may have to use a jumper wire to make it reach.
On the same side, the resistor is connected to the pushbutton, connect a jumper wire and run it to pin 2 on the Arduino board.
Connect the Arduino to your computer with the USB cable.
Open the sketch for this section.
Click the Verify button in the top left corner of the IDE. The Verify button will turn orange and then back to blue when it has completed compiling.
Click the Upload Button (located to the immediate right of the Verify button). This button will also turn orange and then back to blue once the sketch is uploaded to the Arduino board.
Now go to the menu bar at the top and select Tools > Serial Monitor. Or you could use the shortcut key, Shift + Control + M.
The serial monitor window will open and will be spouting off numbers. It should be a bunch of zeros.
Press and hold the pushbutton – watch the serial monitor window, the numbers should now be ones.
If the numbers are not scrolling, make sure you click Autoscroll at the bottom left of the serial monitor window.
digitalRead Serial Port Circuit
This image built with Fritzing.
The Arduino Code
/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor
This example code is in the public domain.
*/
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton’s pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1); // delay in between reads for stability
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor
This example code is in the public domain.
*/
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton’s pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1); // delay in between reads for stability
}
Discuss the Sketch
This sketch opens with a multi-line comment containing a short description of the program and circuit. The first block of code following the comment is where we declare and initialize variables. From the last lesson, we are familiar with the integer data type.
int pushButton = 2; //This is the pin that our push button is connected to.
1
int pushButton = 2; //This is the pin that our push button is connected to.
Notice how the variable pushButton is declared and initialized all on the same line. Also, notice the descriptive name of the variable – pushButton – the variable name implies its use within the program – this is a good example to follow.
Let’s consider what we have done so far – we have made a variable that will store the pin number that our pushbutton is connected to.
The next block of code we come to is the setup(). Inside these wily curly brackets there are two functions – a familiar one, pinMode() and another which we will learn to love – Serial.begin().
Serial.begin() is part of a family of functions referred to as a library. The name of the library is the Serial library. A library is just a group of functions that work toward a similar purpose. If you had a Circus library, it might contain the functions juggle(), balance() and flamingCircleOfDeath(). To access the functions in a library, you write the name of the library followed by the name of the function in the library, with a period in between.
Circus.juggle();
1
Circus.juggle();
Arduino has many preinstalled libraries. There are also many community-contributed libraries that you can add. You can view all of the preinstalled libraries and some of the contributed libraries at http://arduino.cc/en/Reference/Libraries.
So what does the Serial library do?
The Serial library helps establish communication between your computer and the Arduino board. If you ever go to marriage counseling, you will learn that communication involves sending and receiving. Data can flow both ways. If we want to establish this communication, we use the begin() function from the Serial library.
Serial.begin(9600);
1
Serial.begin(9600);
The begin() function takes one argument – the baud rate. What is the baud rate you ask? It is the rate at which data will flow between your computer and the Arduino. For most Arduino sketches a baud rate of 9600 is used as the argument.
That’s all you really need to know about the baud rate to get started with serial monitoring. But I have a feeling you want to know more, so if you check out the further reading section at the end of this tutorial, there will be some links to tempt your insatiable desire for acquiring an understanding of all things in the universe.
The next function after Serial.begin() is the pinMode() function. We want to set the mode of a pin and what is cool about pinMode() this time around is that we are changing the arguments we pass to the function. Instead of being an OUTPUT (as in the Blink sketch), we want our pin to be an INPUT because we want to read voltage at this pin, not provide it.
pinMode(pushButton, INPUT) ;
1
pinMode(pushButton, INPUT) ;
Here we use the variable pushButton to let the function know we are setting the mode at pin 2. Then we use the keyword INPUT, to say which mode we want.
Those are the only two functions in the setup() curly braces – and just as a reminder – setup() only runs once.
The next block of code is the function loop(). What do we see inside the curly braces of the loop()?
int buttonState = digitalRead(pushButton);
1
int buttonState = digitalRead(pushButton);
Whoa! What the heck is this? It looks like the programmer is declaring a variable! I thought variables were declared at the top of the sketch. While variables are often declared before the setup() function, you can actually declare and initialize a variable just about anywhere in a sketch. Soon you will see why this placement is the way to go.
Let’s break down this statement. First, look at the data type and the name. We declare an integer and name it buttonState. Notice the variable name buttonState is indicative of its purpose, as we will see this variable is assigned the position of the button.
To initialize the variable, we see something altogether new – the variable is set equal to the output of a function called digitalRead(). This is going to take a little recall power on your part. Do you remember the reason for the word void in front of the loop() function? We had to write void because the function loop() does not return a value. But that is not the case for the function digitalRead().
The digitalRead() function returns an integer – either 1 or 0. This value is then assigned to the variable buttonState.
If it is 1, the voltage at the pin is HIGH, if the value is 0, the voltage at the pin is LOW. What pin you ask? Well the pin you pass as an argument in the digitalRead() function. In this case, we send the variable pushButton, because we want to read the state of pin 2 (if you recall pushButton was initialized to equal 2).
All of this is in the following line of code:
int buttonState = digitalRead(pushButton);
1
int buttonState = digitalRead(pushButton);
This is why Arduino rocks – one line of code and you are on your way to dominating the world.
Now the state of our pushbutton will be either HIGH (pressed) or LOW (not-pressed). HIGH will be reported as a 1, and LOW will be reported as 0. When we press the pushbutton, pin 2 is exposed to the 5-volts from the Arduino board, this is considered HIGH, and the digitalRead() function will return 1. If the button is not pressed, then all that pin 2 is exposed to is the ground voltage which is 0 and digitalRead() will return 0.
Explanation of Digital Read Code
In the next line of code we return to the Serial library for another function called println().
Serial.println(buttonState);
1
Serial.println(buttonState);
The Serial.println() function returns the value of whatever variable you stick in as an argument. It will report this value to the serial monitor window on your Arduino IDE. To open up the serial monitor window all you have to do is click Tools > Serial Monitor (or SHIFT + CONTROL + M). This is one way to retrieve the data on your Arduino board.
Keep in mind, that when you unplug your Arduino and use some batteries to charge it, the Serial.println() function won’t do you much good. But while you are creating the circuit and the sketch, there is no better way to troubleshoot than use the println() and print() functions from the Serial library.
So let’s cover what we have done so far in the loop. First we read the state of digital pin 2 and save the state in a variable. Then we display the state in the serial monitor window.
Finally, we use the delay() function and wait one millisecond – this allows the reading at the pin to stabilize.
Once this is done, the loop starts from the top. We read another value at pin 2 – we are checking every time whether the button is pressed or not pressed – this value gets assigned to our buttonState variable, then we display the newly recorded value to serial monitor window – again. And we do this over and over – hundreds of times per second.
So go ahead, press that button, watch the serial monitor window – I think you are already brewing applications for these functions…
Try On Your Own Challenge
Change the function Serial.println() to Serial.print(). What happens to the output in the serial monitor window? Can you tell the difference between the two functions?
Change the pin that you are reading to pin 3. Make the circuit change and the changes to the sketch.
Further Reading
Baud Rate
Serial Library
Serial.begin()
Serial.println()
Serial.print()
Create your
podcast in
minutes
It is Free