Logo ilsitodelfaidate.it

5.1 What Are Digital Inputs on Arduino?

In the previous chapter we learned how to use Arduino to control an LED through a digital output. Now we’re going to take a step forward: we’ll learn how to read a signal coming from the outside world and use that information to change the way our program behaves.

In fact, Arduino can do two things: it can send commands to the components connected to it using outputs, and it can receive information through inputs.

Digital inputs and outputs

A digital input lets Arduino recognise two possible logic states, called HIGH and LOW.

On the Arduino UNO R3, these states normally correspond to:

  • HIGH: a high voltage level, close to 5 V relative to GND (ground).
  • LOW: a low voltage level, close to 0 V relative to GND (ground).

These two values let Arduino tell two conditions apart, such as a push button being pressed or released, as long as the circuit is wired up correctly.

For example, we can use a push button as a digital input and an LED as an output. When we press the button, Arduino reads the signal it receives and can turn the LED on; when we release it, Arduino can turn it off again.

How do you read a digital input?

The Arduino programming language has a function made for reading the state of a digital input: digitalRead().

To use it, you put the number of the pin you want to read between the brackets (parentheses). For example:

digitalRead(2);

This instruction reads the logic state of digital pin 2 and returns the value HIGH or LOW, depending on the signal at the input.

For now, you don’t need to use this instruction in a complete program straight away. In the next sections we’ll see how to connect a push button to Arduino and how to use digitalRead() to detect its state.

That way, we’ll build an interactive circuit in which Arduino doesn’t just run a fixed sequence of instructions, but reacts to a command coming from the outside.

Diagram of an Arduino UNO using digitalRead(2) to read a push button (released = LOW, 0 V; pressed = HIGH, 5 V) and control an LED (off = LOW, on = HIGH).

5.2 How a Push Button Works

A push button is an electrical component that opens or closes a connection when you press it. In our Arduino projects, we’ll use it to send a command to the microcontroller.

A normally open push button keeps the circuit broken while it isn’t being pressed. When we press it, the contact closes and lets current flow through the circuit.

When we let go of the button, the contact springs back to its starting position and the connection is broken again.

How does a push button work with Arduino?

If we connect a push button to a digital input correctly, Arduino can detect changes in the electrical signal and use them in the program.

Drawing the flowchart of the program

For example, we can design a circuit in which:

  • when the button is pressed, Arduino turns an LED on;
  • when the button is released, Arduino turns the LED off.

Here’s an example of how the flowchart (or block diagram) could be laid out:

Flowchart of the Arduino program: pin 2 is set as input (button) and pin 13 as output (LED), then pin 2 is read repeatedly. If the button is pressed, HIGH is written to pin 13 and the LED turns on; otherwise LOW is written and the LED turns off.

It’s important to know that a push button, on its own, doesn’t generate a voltage: it simply changes the electrical connection. To let Arduino read a HIGH or LOW state reliably, the circuit has to be set up correctly. We’ll see how to do that in the next section.

The push button on the breadboard

In our experiments we’ll use a small tactile push button, often called a tact switch. This component usually has four legs (terminals), but they’re connected internally in pairs.

When you place the button on the breadboard, it’s important to position it correctly, usually straddling the centre channel (the gap running down the middle of the board), so that you avoid unwanted connections between its terminals.

In the next section we’ll prepare the circuit, connecting the button to Arduino and setting up the input so that it can be read correctly.

5.3 Wiring Up the Circuit

Now we’ll connect a push button to Arduino and build the circuit that lets us detect a button press through a digital input.

What you’ll need

To build the circuit, you’ll need:

  • an Arduino UNO R3 board with a USB cable to connect it to your computer;
  • a breadboard;
  • a tactile push button;
  • a 10 kΩ resistor for the push button;
  • an LED;
  • a 220 Ω or 330 Ω resistor for the LED;
  • a few jumper wires (connecting wires).

Why does the push button need a resistor?

When the button isn’t pressed, the input pin must not be left electrically disconnected (“floating”). In that state it could pick up unstable readings and interpret the state of the button in an unpredictable way.

To avoid this problem we use a pull-down resistor, connected between the input pin and GND (ground). This resistor keeps the pin at a logic LOW level while the button is released.

When we press the button, the pin is connected to 5 V and Arduino can read a logic HIGH level.

Connecting the components

We’ll use digital pin 2 as the input. Make the connections following this layout:

  • one terminal of the push button to the 5 V pin on Arduino;
  • the other terminal of the push button to digital pin 2;
  • a 10 kΩ resistor between digital pin 2 and GND.

The resistor must not be connected in series with the button: in this configuration it sits between the input point and GND, acting as a pull-down.

To see the result of reading the button, we’ll also use the LED from the previous chapter.

If the LED isn’t connected yet, mount it on the breadboard and connect it to digital pin 13 on Arduino, adding a 220 Ω or 330 Ω resistor in series. The cathode of the LED must be connected to GND.

This way we’ll have two circuits connected to the same board: the push button circuit, which sends a signal in, and the LED circuit, which receives the command out.

Before powering up the circuit, check that all the connections are correct and that the button is placed on the breadboard so that it uses the right pairs of terminals.

Breadboard circuit diagram with an Arduino UNO. The push button receives 5 V through a red wire and is connected to digital pin 2 with a blue wire; a 10 kΩ resistor connects the same point to GND (pull-down). The red LED is connected to pin 13 through a series resistor, and its cathode goes to GND with a green wire.

What happens when we press the button?

The circuit has two conditions:

  • Button released: the resistor holds pin 2 at a low level, so Arduino reads LOW.
  • Button pressed: pin 2 is connected to 5 V, so Arduino reads HIGH.

This way, the digital input has a stable state both when the button is pressed and when it’s released.

In the next section we’ll write our first program to read the state of the button using the digitalRead() function and show the result through the behaviour (behavior) of the LED.

5.4 Reading the Button State and Controlling the LED

Now that we’ve connected the button to digital pin 2, we can write a program that lets Arduino recognise when it’s being pressed.

For the moment, we’ll use this information to control an LED, applying what we learned in the previous chapter.

The first program

Type this code into the Arduino IDE:

/*  Esercizio N.05.4
    premendo il pulsante sul pin 2 accendi il led sul pin 13 */
int statoPulsante;
void setup() {
  // put your setup code here, to run once:
  pinMode(2, INPUT); // Inizializza il pin 2 come pin di Iutput
  pinMode(13, OUTPUT); // Inizializza il pin 13 come pin di Output
}

void loop() {
  // put your main code here, to run repeatedly:
  statoPulsante = digitalRead(2); // Leggi il pin 2 in digitale e metti il valore nella variabile

  if (statoPulsante == HIGH) {  // Se il pulsante è premuto
    digitalWrite(13, HIGH);     // Accendi il led
  } else {                      // Altrimenti
    digitalWrite(13, LOW);      // Spegni il led
  }
}

How does it work?

At the start of the program we find this instruction:

int statoPulsante;

This instruction declares a variable called buttonState. A variable is a space in memory where the program can store a value to use while it runs. The word int means that the variable is meant to hold a whole number (an integer).

The variable is declared outside setup() and loop(), so it can be used in both functions. This is known as a global variable.

Inside setup() we find two instructions we already know:

  • pinMode(2, INPUT); sets digital pin 2 as an input.
  • pinMode(13, OUTPUT); sets pin 13 as an output, to control the LED.

Reading and storing the button state

Inside loop() we find this instruction:

buttonState = digitalRead(2);

The function digitalRead(2) reads the logic level at digital pin 2 and returns HIGH or LOW.

The = symbol assigns the returned value to the variable buttonState. This way, every time loop() runs, the variable is updated with the current state of the button.

So we’ve separated two operations: the variable declaration, which happens only once in the structure of the program, and the assignment of the value, which is repeated while loop() runs.

Making a decision: if and else

After reading the button, Arduino has to decide how to control the LED:

if (statoPulsante == HIGH) {
  digitalWrite(13, HIGH);
} else {
  digitalWrite(13, LOW);
}

The if statement checks a condition. Here, buttonState == HIGH checks whether the value of the variable is equal to HIGH.

Be careful not to mix up the two symbols:

  • = is used to assign a value.
  • == is used to compare two values.

If the condition is true, Arduino runs the if block and turns the LED on. Otherwise, it runs the else block and turns the LED off.

Because these instructions sit inside loop(), Arduino reads the button continuously and updates the LED according to the result.

Trying out the program

Arduino IDE screenshot showing the sketch EsercizioN05.4 for Arduino UNO. The program declares the variable statoPulsante, sets pin 2 as input and pin 13 as output, reads the button with digitalRead(2) and, using if...else, writes HIGH to pin 13 if the button is pressed, otherwise LOW. The Output panel shows the successful compilation message.

Verify (compile) the code and upload it to the board. If the circuit is wired correctly, the LED connected to pin 13 will light up while we hold the button down and go off when we release it. The built-in LED on the board will light up too.

We’ve now covered reading an input with digitalRead(), declaring and assigning a variable, and a first decision-making structure with if and else.

In the next section we’ll take a closer look at how conditions work and see how to use them to change the behaviour (behavior) of our circuit.

5.5 Testing and Troubleshooting the Program

Once you’ve built the circuit and uploaded the program to Arduino, it’s time to check that everything works properly. When you press the button, the LED connected to digital pin 13 should light up; when you release it, it should go off. The built-in LED on the board should behave in exactly the same way.

If the circuit doesn’t work as expected, there are a few checks we can make.

The LED doesn’t turn on

  • Check the program: make sure the code compiled without errors and was uploaded to the board correctly.
  • Check the LED: make sure it’s connected the right way round (polarity), with the Anode towards pin 13 through the resistor and the Cathode towards GND.
  • Check the connections: make sure the wires are plugged into the right holes on the breadboard and that the LED’s resistor is connected in series.
  • Test the button: press it and see whether the LED turns on only while you’re pressing it.

The LED stays always on or always off

In this case, the problem is probably in the push button circuit. Check that one terminal of the button is connected to 5V, the other to digital pin 2, and that the 10 kΩ resistor connects pin 2 to GND.

Also make sure the button is placed correctly on the breadboard. On common four-legged push buttons, two legs on the same side are often already connected internally, so placing the button the wrong way round can stop it from working as intended.

The program won’t upload

If the Arduino IDE reports an error during the upload, check that the correct board is selected and that you’ve chosen the port that matches your Arduino (Tools > Board and Tools > Port). Also make sure the USB cable is plugged in properly and that it’s a data cable, not just a charge-only cable.

A handy method for finding errors

When a circuit doesn’t work, it’s better to check one thing at a time rather than changing all the connections at once. You can start with the program, move on to the LED connections, and finally check the push button circuit.

This is an important habit in robotics: learning to find and fix errors (troubleshooting, or debugging) helps us understand how both circuits and programs work.

In the next section we’ll put what we’ve learned to the test with some exercises and program variations, changing the behaviour (behavior) of the LED and experimenting with new solutions.

Photo of the circuit built on a breadboard and connected to an Arduino UNO through a USB cable. A finger presses the push button and the LED on the breadboard is lit; the built-in LED on the board is lit as well.

5.6 Exercises and Variations

Now that we know how to read the state of a push button and use that information to control an LED, we can try a few changes to the program. The aim is to understand digital inputs better and to learn how to change the way Arduino behaves (behaves) to suit our needs.

Exercise 1 – Reverse the behaviour of the LED

Change the program so that the LED stays on when the button is released and turns off when it’s pressed.

To do this, we need to swap the instructions that are run in the two cases of the if...else condition.

Exercise 2 – Use a different digital pin

Move the button connection from pin 2 to pin 4, then change the program so that Arduino reads the new input.

Remember to update the pin number in both the pinMode() instruction and the digitalRead() call. The physical connection of the button also has to be moved to the correct pin.

Exercise 3 – Add a second LED

Connect a second LED to another digital pin, for example pin 12, using a 220 Ω or 330 Ω resistor in series.

Change the program so that when we press the button, the first LED turns on and the second one turns off. When we release the button, the behaviour has to be reversed.

To do this, we’ll need to set pin 12 as an output with pinMode() and control the second LED with digitalWrite().

Exercise 4 – Understand the program

Without running the program straight away, try answering these questions:

  1. What value does digitalRead(2) return when the button is pressed?
  2. What is the variable buttonState for?
  3. What’s the difference between = and ==?
  4. What would happen if we removed the else part from the program?
  5. Why do we need a pull-down resistor in the push button circuit we’ve built?

Once you’ve worked out your answers, try the program and check whether your predictions were right.

A first programming challenge

Try changing the program so that the LED changes state every time the button is pressed: if it’s off, it turns on, and if it’s on, it turns off. The new state must be kept even after the button is released.

This challenge needs a different kind of behaviour from the one we’ve used so far: it isn’t enough to read whether the button is pressed. We also need to detect each new press and remember the previous state of the LED. To do it properly, we’ll need to introduce a new concept, which we’ll cover later on.

With these exercises we’ve consolidated the basics of digital inputs, outputs and conditions. They’re essential tools for building robotic systems that can react to what the user does and, in the coming chapters, to the information gathered by sensors.

Coming Up in the Next Chapter...

So far, we’ve been giving Arduino its orders by pressing a button. But a real robot can’t wait around for someone to tell it what to do every time: it has to notice for itself what’s happening around it. In the next chapter, Chapter 6 - Arduino Analog Sensors: Control an LED with a Photoresistor (LDR), we’ll find out how to do exactly that by getting to know sensors and putting them to work.

We’ll see that there are many kinds of sensors, able to measure light, temperature, distance or movement, and we’ll understand the difference between digital sensors, which only know two states, and analog sensors, which can pick up every shade in between.

We’ll start with a small, simple component, the photoresistor (also called an LDR, or light-dependent resistor), which changes the way it behaves depending on the light falling on it. We’ll connect it to Arduino, watch how it reacts when we shine a light on it or cover it with a hand, and use it to make an LED switch on by itself when the room gets dark.

This will be our first little automatic system: Arduino senses, decides and acts. Along the way, we’ll also learn to think like real experimenters, hunting for the cause when something doesn’t work, and we’ll be able to test ourselves with exercises and variations of our own to invent.

If you’re curious to see where this journey will take us, have a look at the page Beginner's Guide to Robotics with Arduino: there you’ll find the full contents list, from the first chapter to the final project, and you can choose whether to carry on in order or go back and review a topic.

If you’ve found this course useful and would like to explore other robotics or hobby electronics projects, you can keep reading by visiting the other content in the Electronics and Robotics section of the site, where you’ll find plenty more practical guides and step-by-step explanations.

I’d like to point out that some of the images in the course were generated by artificial intelligence (AI), and I apologise for any inaccuracies they may contain. The course itself was also written with the help of AI, but the structure is the result of my own experience: I’m a retired programmer and, over the course of my career, I’ve taught several courses. So I chose the topics, organised the whole structure of the course and reviewed the text myself.

I care a great deal about the quality and originality of the content I publish. That’s why I’d prefer it not to be copied or republished elsewhere. If you think this guide could be useful to other people, though, I’ll be really happy if you share the link to the page: it’s the right way to spread the information and to support the work behind every article.

Thank you

Luciano (Capitan Farloc)

Warning!

The advice and instructions provided on this site come from hobbyists rather than professional technicians, meaning there is no guarantee that they are accurate or represent the best solution.
Additionally, using the tools and techniques described here should be done with careful consideration of one’s own abilities.
These articles assume that the tasks will be performed by individuals with the necessary skills and knowledge to use the required tools safely, without risking harm to themselves, others, or property.
Therefore, the owners of this site cannot be held responsible for any direct or indirect damages resulting from the application of the content found here.
Before undertaking any DIY activity, it is strongly recommended to read the Safety Notice, which provide a basic (though non-exhaustive) list of precautions to follow.

Copyright

The republication of full articles is strictly prohibited. However, it is permitted to publish brief excerpts of the articles or images, provided that the source is clearly credited at the end. This must include a hyperlink directing readers to the original page from which the content was taken.

The site icon ilsitodelfaidate.it was downloaded from 123rf.com. © captainvector, 123RF Free Images

Disclaimer

Privacy Policy

Cookie Policy

Terms and Conditions

Consent Preferences