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
- We add a button to the circuit from guide no. 34.
- The sketch reads the button with
digitalReadand decides withif … else. - The Serial Monitor shows on the computer what is happening.
- At the end: the notebook with all the basic commands.
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
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.
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 }
== is used to compare.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.
- 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 } }
bool ledOn = false; creates a box that is either true or false, and at the start it is false (off).6Challenge yourself
- 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
delayfrom guide no. 34). - Count the presses and write them in the monitor: “Press number 1”, “2”… (you need an
intvariable).
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:
| Command | What 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) / LOW | switches 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 |
- a button is connected between a pin and GND, with
INPUT_PULLUP: pressed = LOW; digitalReadreads,if … elsedecides;- the Serial Monitor lets you see what the board is thinking;
- a variable remembers things from one round of
loopto the next.
Useful products
Other guides
- Resistor colour code and tolerances
- N-channel and P-channel MOSFETs
- Bipolar transistor (BJT) or MOSFET?
- Relays: how to drive them and how much current they draw
- THT and SMD/SMT components
- XIAO board pinouts
- LEDs: forward voltage and series resistor
- The multimeter: measuring voltage and current
- Wemos D1 mini: first steps
- MOSFET module with Arduino and ESP32
- Relay module with Arduino and ESP32
- 3D printing filaments: PLA, PETG and fibre-filled versions
- Analog and digital: the differences
- ADS1115: 16-bit converter with Arduino and ESP32
- From bits to real values: converting sensor readings
- DS3231 RTC clock with Arduino and ESP32
- Linear or switching regulator: which one to choose
- Step-down, step-up and buck-boost: choosing the right module
- Voltage divider: reading voltages higher than 5 V or 3.3 V
- Pull-up, pull-down and bounce: wiring a button properly
- 3.3 V and 5 V logic levels: getting an ESP32 and an Arduino to talk
- The I²C bus: addresses, pull-ups and the scanner
- Lithium batteries: voltages, charging and protection
- ESP32 power consumption and deep sleep: how long the battery lasts
- Temperature sensors compared
- ESP32: which pins to use and which to avoid
- Getting started with the ESP32 in Arduino IDE 2 and PlatformIO
- SSD1306 OLED display and 16×2 I²C LCD with Arduino and ESP32
- PIR motion sensor and HC-SR04 ultrasonic sensor
- Date and time from the Internet with the ESP32: NTP, Italian time zone and daylight saving time
- MicroSD data logger: saving measurements to CSV
- Solar-powered ESP32: panel, charger and the numbers for Italy
- Web server on the ESP32: control a relay from your phone
- Your first LED: wire it up and make it blink
- The potentiometer: turn a knob and read its value
- Soft light: adjusting the brightness of an LED
- The buzzer: playing notes and melodies
- The traffic light: three LEDs in sequence
- The thermometer: reading the temperature with the TMP36
- The servo motor: moving an arm with Arduino
- The night light: the photoresistor and your first decision
- The relay: switching on a light bulb with Arduino
- The LCD display: making Arduino write
- The electronic dice: your first complete project
- The RGB LED: every color from three lights
- The joystick: two-axis control with a shield
- The LED ring: twelve colors from a single pin
- The DC motor: driving it with a MOSFET
- Soil moisture: the plant that asks for water
- The stepper motor: turn exactly as far as you want
- The parking sensor: faster and faster beeps
- The 7-segment display: big, bright numbers
- Automatic watering: the plant that waters itself
- The keypad: a lock with a secret code
- Networked weather station: values and chart on your phone
- A Telegram bot on the ESP32: your home from your phone
- MQTT with the ESP32: the language of connected devices
- Updating the ESP32 over Wi-Fi (OTA)
- ESP-NOW: two ESP32 boards talking without a router
- WebSocket with the ESP32: the LED that follows the slider
- Readings on a Google sheet, with deep sleep
- WiFiManager: choose the Wi-Fi from your phone
- Bluetooth LE with the ESP32: the phone without a network
- The camera in your browser with the ESP32-S3
- A portable Bluetooth speaker you build yourself
- Bluetooth desktop speakers, 2 × 20 W
- Stereo MP3 player with two buttons
- The shelf that plays music: a Visaton exciter
- How to solder well
- How much does it draw? Current and power with the INA219
- Load-cell scale with the HX711
- CO2 traffic light: when to open the windows
- RFID card door opener
- GPS: track logger on microSD
- LoRa: how far does it go? A range test with two boards
- Battery weather sign with an e-paper display
- Web radio with an ESP32 and an I2S amplifier
- Getting started with the Raspberry Pi Pico 2 in MicroPython
- Your first amplifier: the LM386 and a speaker
- Talking Arduino: the DFR0760 speech synthesis module
- The spectrum of your music on an LED matrix
- Drawing with 64 LEDs: the 8×8 matrix with the MAX7219
- A real voltage: the 12-bit MCP4725 DAC
- The heartbeat on Arduino: an ECG with the AD8232