Lessons · Lesson K2 · Code basics · 20 min
Inputs, outputs and if
Read a button, switch on an LED and a buzzer, and let your code decide what to do. About 20 minutes, with a virtual button to press.
Two directions
In lesson K1 your code sent a signal out: digitalWrite() switched an LED on and off. This lesson adds the other direction. A pin can work in two ways [1][3]:
- Output: the board decides the pin’s level, high or low, to drive something such as an LED or a buzzer.
- Input: the board listens to the pin’s level, to find out what the outside world is doing, for example whether a button is pressed.
You choose which one with pinMode(), and you do it once, in setup(): OUTPUT for sending, INPUT (or one of its cousins below) for listening [1][3]. Then digitalWrite(pin, HIGH or LOW) sets an output, and digitalRead(pin) gives you the level of an input as HIGH or LOW [1].
Today’s circuit uses three pins. We keep GPIO 26 for the LED from K1, add a button on GPIO 27 and a buzzer on GPIO 25.
The floating pin problem
Picture an input pin with nothing attached. If your code reads it, what does it see? Nobody can say. The pin is floating: it can drift towards high or low, and it can change on its own [5].
The cure is to give the pin a default level. A pull-up resistor connects the pin to the supply voltage through a resistor, so the pin reads high when nothing else is happening. A pull-down does the same towards ground [5].
The door spring. Think of a door with a spring that keeps it closed. Nothing touches the door, and it sits closed: that is the pull-up holding the pin high. Push the door and you overpower the spring: that is the button connecting the pin to ground. Let go and the spring brings the door back.
Where the picture stops. A spring pushes with a force. A pull-up is a resistor: when you press the button, a small current flows through it to ground, and a larger resistor value means less current [5].
No extra parts: the built-in pull-up
The ESP32 has pull-up resistors inside the chip, about 45 kΩ each [3]. You switch one on from code with a special mode:
pinMode(27, INPUT_PULLUP);
INPUT_PULLUP means “input, with the internal pull-up resistor switched on” [3][6].
Wire the button: one leg to GPIO 27, the leg diagonally opposite to GND. On a 4-leg button, two legs are always joined inside, so diagonal corners are the two sides of the switch. Nothing else, no resistor [4][6].
What your code reads, then [4][6]:
| Button | Pin connected to | digitalRead(27) |
|---|---|---|
| Not pressed | the pull-up (high) | HIGH (1) |
| Pressed | GND | LOW (0) |
Yes, it feels backwards: pressed is LOW. This is called inverted logic, and you get used to it quickly [4].
Choosing the pin. Not every ESP32 pin suits this job. GPIO 34 to 39 are input-only and have no internal pull-up or pull-down, so they cannot do what we need [8]. GPIO 0, 2, 5, 12 and 15 help decide how the chip starts up (they are called “strapping pins”), so keep buttons and wires off them for now [8][9]. GPIO 12, for example, sets the flash voltage at start-up, so a button there can stop the board booting [9]. GPIO 27 is a safe pick on the DevKitC.
A reminder on voltage. The ESP32 uses 3.3 V logic, and its pins are generally not safe with 5 V [10]. Everything in this lesson stays at 3.3 V.
Swipe the drawing sideways to see all of it.
The active buzzer
A buzzer turns an electrical signal into sound. There are two kinds. A plain piezo element needs a rapidly changing signal from you to make noise. An active buzzer has a small driver circuit built in. Give it power and it sounds at a fixed pitch (about 2 kHz in the example Adafruit describes), and you cannot change the pitch [7].
That makes it easy to use: for your code it behaves exactly like the LED. HIGH means sound, LOW means silence. The model Adafruit describes works from 3 V to 5 V [7], so a 3.3 V pin is within its range.
Pick the right buzzer. An ESP32 pin is designed to give about 20 mA on its own [13]. So choose an active buzzer rated for 3.3 V (or “3-5 V”) whose product page states a current of 20 mA or less. Two kinds are sold:
- 2-pin active buzzer (a small black cylinder, often with a sticker on top): the leg marked + (usually the longer one) to GPIO 25, the other leg to GND.
- 3-pin buzzer module (a small board marked VCC, GND and I/O or S): VCC to 3V3, GND to GND, I/O to GPIO 25. The module carries its own transistor, so the pin only has to send a small signal. Some modules beep when the pin is LOW instead of HIGH (“low-level trigger”). If yours beeps while the button is released, swap
HIGHandLOWon the two buzzer lines of the sketch.
If you are not sure what you have, use a 3-pin module rated for 3.3 V.
Later, lesson A1 covers passive buzzers and playing notes.
Deciding with if / else
Now the board knows what the button says. To act on it, your code needs to make a choice. That is what if is for:
if (reading == LOW) {
// the button is pressed: do this
} else {
// anything else: do that
}
Read it as a sentence: “If the reading equals LOW, run the first block. Otherwise, run the second one.” Only one block runs each time [4].
Two details that trip up many beginners:
==asks a question,=gives an order.reading == LOWchecks whether two things are equal, and that is what the test in our sketch uses [4]. A single=stores a value, as inint ledPin = 13;[11]. Inside anif, write two equals signs.if (reading = LOW)is accepted by the compiler, but it stores LOW instead of comparing, so the LED never lights.- Curly braces
{ }wrap the lines that belong to each branch.
Because loop() runs over and over, the decision is made again and again, many times a second. That is how the LED seems to follow your finger.
Swipe the drawing sideways to see all of it.
The whole sketch
Upload this, with the circuit built and the board plugged in as in lesson K1:
// Tinker Mission, lesson K2: button -> LED + active buzzer, decided with if/else
// Wiring:
// Button: one leg to GPIO 27, the diagonally opposite leg to GND (no resistor needed)
// LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
// Active buzzer: + leg to GPIO 25, other leg to GND (3-pin module: VCC to 3V3, GND to GND, I/O to GPIO 25)
const int BUTTON_PIN = 27;
const int LED_PIN = 26;
const int BUZZER_PIN = 25;
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP); // input, with the board's own pull-up switched on
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
int reading = digitalRead(BUTTON_PIN); // 1 (HIGH) = not pressed, 0 (LOW) = pressed
if (reading == LOW) {
// pressed
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
} else {
// not pressed
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
}
Serial.println(reading);
delay(50); // short pause so the Serial Monitor stays readable
}
Download the sketch folder (.zip)
int reading = ... creates a variable, a named place to keep a number. It is named reading, it holds a whole number (int), and it receives whatever digitalRead() returned [11].
Open the Serial Monitor at 115200 baud. You should see a stream of 1, and 0 for as long as you hold the button [4].
Troubleshooting.
- LED and buzzer are on all the time and the monitor says 0: the pin is being held at ground. Check the button wiring against the diagram: one leg on GPIO 27, the leg diagonally opposite on GND. With two legs on the same side, the button may be always closed.
- The monitor shows only 1, even when you press: the button is not really connected. Check the wire on GPIO 27 and the one on GND, and that the button legs sit in the breadboard [3][4].
- The monitor jumps between 0 and 1 on its own: the pin is floating. Check that
setup()saysINPUT_PULLUP, notINPUT[5][12]. - No sound but the LED works: check the buzzer’s + leg, and read its datasheet for the voltage it needs. A 3-pin module needs its VCC on 3V3.
- The buzzer sounds when the button is released, and stops when you press: your module triggers on LOW. Swap
HIGHandLOWon the two buzzer lines.
Try your own changes
Change one thing, upload, observe.
- Flip it. Make the LED light up while the button is not pressed. Which
iftest do you change? - Silent mode. Remove the two buzzer lines in the “pressed” branch. What is left?
- Words, not numbers. Replace
Serial.println(reading);with a print of “pressed” or “released”, chosen with the sameif.
Check yourself
Three short questions. Nothing is saved, take your time.
A button is wired between a pin and GND, and the pin uses INPUT_PULLUP. What does digitalRead() return while the button is NOT pressed?
- LOW (0)
- HIGH (1)
- Nothing, it is undefined
In the sketch, you want the LED to light up while the button is pressed. Which test goes inside the if?
- reading == HIGH
- reading == LOW
- reading = LOW
What does an active buzzer need from your code to make its sound?
- A rapidly changing signal that you generate yourself
- Just power: digitalWrite HIGH switches it on
- A resistor to GND on each leg
Show the answer
Just power: digitalWrite HIGH switches it on. An active buzzer has its own driver circuit inside, so it does not need an alternating signal from you, and its pitch is fixed [7].
Sources
Show the 13 sources
- Espressif, Arduino-ESP32 documentation, “GPIO” (input and output modes; pinMode, digitalWrite, digitalRead; INPUT_PULLUP) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/gpio.html
- Arduino, “Input Pullup Serial” example (when the pushbutton is open the pin reads HIGH; when closed, connected to ground, it reads LOW) — https://docs.arduino.cc/built-in-examples/digital/InputPullupSerial/
- Espressif, Arduino-ESP32 documentation, “GPIO” (internal pull-up and pull-down are about 45 kΩ; without a pull mode the pin stays high-impedance) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/gpio.html
- Arduino, “Input Pullup Serial” and “Digital Input Pull-Up Resistor” examples (button wired between a pin and ground without a resistor; HIGH when open, LOW when closed; the logic is inverted; if/else on the reading;
==comparison in the sketch) — https://docs.arduino.cc/built-in-examples/digital/InputPullupSerial/ and https://docs.arduino.cc/tutorials/generic/digital-input-pullup/ - SparkFun, “Pull-up Resistors” (a floating pin has an unknown state; pull-up and pull-down; pull-up reads high when the button is not pressed and low when it is; typical 10 kΩ external value; internal pull-ups) — https://learn.sparkfun.com/tutorials/pull-up-resistors
- Arduino, “Digital Pins” (INPUT_PULLUP inverts the behaviour of INPUT; with a simple switch to ground the pin reads HIGH when open and LOW when pressed) — https://docs.arduino.cc/learn/microcontrollers/digital-pins/
- Adafruit, “Buzzer 5V - Breadboard friendly”, product 1536 (3 V to 5 V; does not need an AC signal; piezo plus driver circuit; fixed 2 kHz; frequency cannot be changed) — https://www.adafruit.com/product/1536
- Espressif, ESP-IDF Programming Guide, “GPIO & RTC GPIO” (GPIO 34 to 39 can only be inputs and have no software-enabled pull-up or pull-down; GPIO 0, 2, 5, 12 and 15 are strapping pins) — https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html
- Espressif, esptool documentation, “Boot Mode Selection” (GPIO 0 held low at reset enters the serial bootloader; GPIO 2 must be floating or low to do so) — https://docs.espressif.com/projects/esptool/en/latest/esp32/advanced-topics/boot-mode-selection.html
- Adafruit, “Adafruit HUZZAH32 ESP32 Feather: Pinouts” (3.3 V power and logic; GPIO pins are not 5 V safe unless stated otherwise) — https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/pinouts
- Arduino, “Arduino Sketches” (a variable is a named place to store data, with a type and a value;
int) — https://docs.arduino.cc/learn/programming/sketches/ - Arduino, “Digital Pins” (an input pin with nothing connected reports seemingly random changes) — https://docs.arduino.cc/learn/microcontrollers/digital-pins/
- Espressif, ESP32 Series Datasheet, DC characteristics and IO MUX drive strength (default drive strength is about 20 mA per pin; the highest setting is about 40 mA) — https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf