Français

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].

Pull-up: the door-spring idea Two states of the same circuit. A 3.3 V supply feeds a pull-up resistor down to a node joined to the GPIO 27 pin; a push button goes from that node to ground. Left, button not pressed: no current flows, the pull-up holds the pin at 3.3 V and digitalRead returns 1, HIGH. Right, button pressed: the pin is connected to ground, it reads 0, LOW, and a small current flows through the resistor to ground. Below, the analogy: a spring keeps a door shut when nobody pushes; your push beats the spring. The picture stops there: a resistor is not a force, and a bigger resistor means a smaller current. FIG. 1 — PULL-UP = DOOR SPRINGaButton not pressed3V3pull-up≈ 45 kΩGPIO 27buttonpin reads1HIGHThe pull-up holds the pin at 3.3 V.No current flows.springdoorNobody pushes: the door stays shut.bButton pressed3V3pull-up≈ 45 kΩGPIO 27buttonpin reads0LOWIPin joined to GND: 0 V.A small current I flows to ground.springyour pushYou push: you beat the spring.
Tap the diagram to open it full screen.

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.

Virtual button on GPIO 27 with pull-up
Virtual button on GPIO 27 with pull-up Interactive. Press and hold the big button. Released, the pull-up holds GPIO 27 at 3.3 V: the pin reads 1, digitalRead(27) returns HIGH, and the spring keeps the door shut. Pressed, the pin is joined to GND: it reads 0, LOW, and your push beats the spring. A line at the bottom draws the pin level over the last seconds. FIG. W2 — VIRTUAL BUTTONpress and holdspringdoorpull-up = springGPIO 271pin at 3.3 VdigitalRead(27)→ HIGH10time →

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 HIGH and LOW on 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.

K2 wiring: buzzer on 25, LED on 26, button on 27 Breadboard seen from above, DevKitC across the centre gap, USB on the left, pins 25, 26, 27 and GND in the top row, column j free. Eight numbered wires. 1 black: GND pin to the top minus rail. 2 orange: GPIO 25 to row 22, the active buzzer's plus leg; its other leg is in row 25; 3 black: row 25 to the top minus rail. 4 green: GPIO 26 to row 28; the 220 ohm resistor bridges rows 28 and 32; the LED's long leg is in row 32, its short leg in row 33; 5 black: row 33 to the top minus rail. 6 blue: GPIO 27 to row 37, one leg of the button, which straddles the gap across rows 37 and 39; 7 black: the opposite leg, row 39 bottom half, to the bottom minus rail; 8 black: bottom minus rail to top minus rail, so both rails are GND. FIG. 2 — WIRING, BREADBOARD VIEW+−−+jihgfedcba15101522252832373944ENBOOT5VCMDD3D213GND121427262533323534VNVPEN3V3++24613578active buzzer220 ΩLEDbutton1black: GND pin → top − rail2orange: GPIO 25 → buzzer + (row 22)3black: buzzer − (row 25) → − rail4green: GPIO 26 → 220 Ω (row 28)5black: LED − (row 33) → − rail6blue: GPIO 27 → button (row 37)7black: button, opposite leg → bottom − rail8black: bottom − rail → top − railThe LED part is the same as in K1, with its parts moved along. The button needs no resistor: INPUT_PULLUP.
Tap the diagram to open it full screen.
K2 circuit as a schematic IEC schematic. Inside the ESP32, shown dashed, an internal pull-up of about 45 kilohms joins GPIO 27 to 3.3 V when the code says INPUT_PULLUP. GPIO 27 goes through a push button to ground: pressed reads LOW. GPIO 26 drives a 220 ohm resistor and an LED to ground: HIGH lights it. GPIO 25 drives the plus pin of an active buzzer whose other pin goes to ground: HIGH makes it sound. FIG. 3 — SCHEMATIC (IEC)ESP32GPIO 27GPIO 26GPIO 253V3pull-up ≈ 45 kΩinside the chip:INPUT_PULLUPbuttonpressed → reads LOW220 ΩLEDHIGH → lit+−active buzzerHIGH → sound
Tap the diagram to open it full screen.

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 == LOW checks whether two things are equal, and that is what the test in our sketch uses [4]. A single = stores a value, as in int ledPin = 13; [11]. Inside an if, 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.

if / else, step by step
if / else, step by step Interactive. Press the virtual button on the left. The flowchart of loop() reads the button into reading, then asks whether reading equals LOW. Pressed, reading is 0: the yes branch lights up, the LED and the buzzer switch on. Released, reading is 1: the no branch lights up, both switch off. Only one branch is active at a time. FIG. W3 — IF / ELSE, STEP BY STEPpress and holdGPIO 27reading = 1LED offbuzzer offloop() startsreading = digitalRead(27);1 = released0 = pressedreading == LOW ?yes: pressed (0)digitalWrite(…, HIGH);LED onbuzzer onno: released (1)digitalWrite(…, LOW);LED offbuzzer offSerial.println(reading);delay(50);↻ loop() again, many times a second

Swipe the drawing sideways to see all of it.

Flowchart of loop() with if / else Flowchart. loop() starts, then reads the button: reading equals digitalRead of pin 27, 1 when released, 0 when pressed. A diamond asks: is reading equal to LOW? Yes, pressed: digitalWrite HIGH, LED on and buzzer on. No, released: digitalWrite LOW, LED off and buzzer off. Only one branch runs each time. Both paths join, the value is printed, a 50 millisecond pause follows, and an arrow goes back to the start: loop() runs again, many times a second. FIG. 4 — LOOP() FLOWCHARTloop() startsreading = digitalRead(27);1 = released0 = pressedreading == LOW ?yes: pressed (0)digitalWrite(…, HIGH);LED onbuzzer onno: released (1)digitalWrite(…, LOW);LED offbuzzer offSerial.println(reading);delay(50);↻ loop() again, many times a second
Tap the diagram to open it full screen.

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() says INPUT_PULLUP, not INPUT [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 HIGH and LOW on the two buzzer lines.

Try your own changes

Change one thing, upload, observe.

  1. Flip it. Make the LED light up while the button is not pressed. Which if test do you change?
  2. Silent mode. Remove the two buzzer lines in the “pressed” branch. What is left?
  3. Words, not numbers. Replace Serial.println(reading); with a print of “pressed” or “released”, chosen with the same if.

Check yourself

Three short questions. Nothing is saved, take your time.

  1. 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
    Show the answer

    HIGH (1). The pull-up holds the pin at the high level while the button is open. Pressing the button connects the pin to ground, and the reading drops to LOW [2][4].

  2. 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
    Show the answer

    reading == LOW. With a pull-up, pressed means LOW [4]. The test in the sketch uses a double equals sign to compare two values [4].

  3. 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
  1. 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
  2. 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/
  3. 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
  4. 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/
  5. 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
  6. 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/
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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/
  12. Arduino, “Digital Pins” (an input pin with nothing connected reports seemingly random changes) — https://docs.arduino.cc/learn/microcontrollers/digital-pins/
  13. 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

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.