Home

Guide no. 35

Arduino listens to a button, switches on the LED and writes to you on the computer. With the basic commands explained one by one, plus a bonus: turning the button into a switch.

By Ada Intelisano · informaticait.it technical team

Download the PDF (A4, 6 pages) Free to print and share, without changes — CC BY-ND 4.0
In short
  • We add a button to the circuit from guide no. 34.
  • The sketch reads the button with digitalRead and decides with if … else.
  • The Serial Monitor shows on the computer what is happening.
  • At the end: the notebook with all the basic commands.
Time: 30 minutesLevel: day twoBefore: guide no. 34 (your first LED)

In guide no. 34 Arduino switched the LED on all by itself. Now it is the one listening: when you press a button it notices, switches on the LED and writes it on the computer. It is the first step for any project that reacts to something.

1Get the parts ready

  • the circuit from guide no. 34 (Arduino, breadboard, LED with the 220 Ω resistor)
  • a 4-pin pushbutton, the small square kind
  • three more jumper wires

2Fit the button and the wires

Then the wiresSCLSDAAREFGND131211109876543210IOREFRESET3.3V5VGNDGNDVINDIGITAL (PWM ~)POWERANALOG INUNO−++−220 Ωbutton213GNDinformaticait.it

The button sits across the center channel, like a bridge. Compared with guide no. 34 the ground connection changes: GND goes to the long row at the top marked − (the − rail), and from there two short jumpers bring the minus to the LED and to the button.

Orange wire: pin 13 → resistor (as before). Blue wire: pin 2 → column of the button's left pin. Black wires: GND → − rail; − rail → short leg of the LED; − rail → right pin of the button.

✓ Check before moving onFollowing it with your finger: pin 2 → button → − rail → GND. When you press, pin 2 is connected to GND.

3Write the sketch

// The button: as long as you hold it down the LED stays on and the computer says so.
#include <Arduino.h>

const int LED = 13;          // with the ESP32 write 23
const int BUTTON = 2;        // with the ESP32 write 27

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);     // input: at rest it reads HIGH
  Serial.begin(115200);              // opens communication with the computer
  Serial.println("Ready! Press the button");
}

void loop() {
  if (digitalRead(BUTTON) == LOW) {     // LOW = pressed
    digitalWrite(LED, HIGH);
    Serial.println("Pressed");
  } else {                              // otherwise: released
    digitalWrite(LED, LOW);
  }
  delay(200);                           // a short pause
}
New word: INPUT_PULLUPIt tells Arduino that the pin is an input and turns on an internal resistor that holds it HIGH. When you press, the button connects it to GND and the pin reads LOW. So: pressed = LOW.
New word: if … elseIt is a question: if the button is pressed switch on the LED, otherwise switch it off. The double equals sign == is used to compare.
New word: SerialIt is the communication line with the computer, through the USB cable. With Serial.println the board writes messages to you.

4Upload and open the Serial Monitor

Upload as in guide no. 34 (right-pointing arrow). Then open the Serial Monitor: it is the magnifying glass icon at the top right. At the bottom of the monitor, choose the speed 115200, the same as in the sketch.

✓ What you should seeThe monitor shows “Ready! Press the button”. Hold the button down: the LED comes on and lots of “Pressed” lines appear. Let go: the LED goes off.
If it doesn't work
  • The LED is always on: the button is turned the wrong way and always connects. Rotate it a quarter turn.
  • Nothing happens when you press: check the blue wire on pin 2 and that the button sits across the channel.
  • The monitor shows strange symbols: the speed at the bottom is not 115200.
  • The monitor is empty: press the RESET button on Arduino to start over.

5Bonus: one press on, one press off

Now the button becomes a switch, like a light switch. You need a variable that remembers whether the LED is on.

// One press switches on, one press switches off: the button becomes a switch.
#include <Arduino.h>

const int LED = 13;          // with the ESP32 write 23
const int BUTTON = 2;        // with the ESP32 write 27
bool ledOn = false;          // remembers whether the LED is on

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(BUTTON) == LOW) {            // you pressed it
    ledOn = !ledOn;                            // the exclamation mark flips it: on becomes off and vice versa
    digitalWrite(LED, ledOn ? HIGH : LOW);
    delay(300);                                // pause: one press counts only once
    while (digitalRead(BUTTON) == LOW) {}      // wait until you let go of the button
  }
}
New word: variableA box with a name that holds a value. bool ledOn = false; creates a box that is either true or false, and at the start it is false (off).
✓ What you should seeEvery press changes the LED: on, off, on…

6Challenge yourself

Try it yourself: three challenges
  • Do the opposite: LED on when the button is released and off when you press it.
  • While you hold the button down, make the LED blink instead of staying on (you need delay from guide no. 34).
  • Count the presses and write them in the monitor: “Press number 1”, “2”… (you need an int variable).

7And with the ESP32?

Same circuit, but: LED on pin 23, button on pin 27, ESP32 GND to the − rail. In the sketch change the two lines: const int LED = 23; and const int BUTTON = 27;. Board to choose: ESP32 Dev Module.

The command notebook

All the commands from guides no. 34 and 35, to keep at hand:

CommandWhat it does
pinMode(pin, OUTPUT)the pin gives out current: for LEDs, buzzers, relay modules
pinMode(pin, INPUT_PULLUP)the pin listens: for buttons and switches connected to GND
digitalWrite(pin, HIGH) / LOWswitches on / off
digitalRead(pin)reads the pin: HIGH or LOW
delay(ms)waits, in thousandths of a second (1000 = 1 second)
if (…) { … } else { … }if it is true it does the first part, otherwise the second
Serial.begin(115200)opens communication with the computer
Serial.println("text")writes a line in the Serial Monitor
✓ What you learned
  • a button is connected between a pin and GND, with INPUT_PULLUP: pressed = LOW;
  • digitalRead reads, if … else decides;
  • the Serial Monitor lets you see what the board is thinking;
  • a variable remembers things from one round of loop to the next.
Sources: Arduino, “Digital Pins” documentation (INPUT_PULLUP) and language reference · informaticait guides no. 20 (pull-ups and bounce), no. 26 (ESP32 pins), no. 34 (your first LED)

Useful products

Other guides

All our guides →
Loading...
Back to top