13.10  Buttons

A push button is the simplest sensor there is: its contacts are either open or closed. Reading one with digitalRead() still raises three questions, and this chapter answers them at the bench. What does an input read while the button is open and nothing drives the pin? Why does one press sometimes count as several? And why does a program that waits with delay() miss presses? The answers give us the pull-up resistor, debouncing, and the timing with millis() that every later program in this part uses.

The Guide

Step 1: Wire the button

The button in the kit is a 6 mm tactile switch with four legs. Inside it the two legs on each side of the square are always connected, and pressing joins the two sides. Put it across the centre gap of the lower breadboard, beside the ESP32, with its legs in e18, f18, e20 and f20 (Figure 13.10.1). Columns 18 and 20 are then connected only while the button is pressed.

Figure 13.10.1: The push button across the gap at columns 18 and 20. The yellow jumper takes column 18 to D27 (GPIO 27), the black one takes column 20 to the − rail, and GND feeds that rail. Nothing goes to 3V3.

Before the jumpers go in, check the button with the continuity test: probes in columns 18 and 20, silent while the button is released, a beep while it is pressed. A button turned by 90° beeps all the time, since its connected legs then sit in different columns; turn it back. Then add the three jumpers of Figure 13.10.1.

Step 2: Count the presses

The project is code/button next to this chapter:

// main.cpp: a push button from GPIO 27 to GND. Every press switches the LED on GPIO 2.
// The program counts every change of the pin and every debounced press and prints both,
// so contact bounce shows up as more edges than presses.
#include <Arduino.h>

const int buttonPin  = 27;
const int ledPin     = 2;
const int debounceMs = 20;       // a new level must hold this long before it counts

int rawLevel = HIGH;             // the pin as read last
int stableLevel = HIGH;          // the debounced level: HIGH released, LOW pressed
unsigned long changedMs = 0;     // when rawLevel last changed
int edges = 0;                   // every change of the pin, bounces included
int presses = 0;                 // debounced presses
bool ledOn = false;

void setup() {
  Serial.begin(115200);
  pinMode(buttonPin, INPUT_PULLUP);  // the pin's own resistor pulls it up to 3.3 V
  pinMode(ledPin, OUTPUT);
  Serial.println("Press the button");
}

void loop() {
  int level = digitalRead(buttonPin);
  if (level != rawLevel) {           // a press, a release or a bounce
    rawLevel = level;
    changedMs = millis();
    edges++;
  }

  // Take the new level only once it has held for debounceMs
  if (rawLevel != stableLevel && millis() - changedMs >= debounceMs) {
    stableLevel = rawLevel;
    if (stableLevel == LOW) {        // pressed: the button pulls the pin to GND
      presses++;
      ledOn = !ledOn;
      digitalWrite(ledPin, ledOn ? HIGH : LOW);
      Serial.printf("presses=%d  edges=%d\n", presses, edges);
    }
  }
}

Upload it and open the Serial Monitor. Each press switches the blue D2 LED and prints a line. A clean press and release change the pin twice, so after ten presses we expect edges near 20. Most buttons give more, some presses a few extra edges, some none:

presses=1  edges=1
presses=2  edges=5
presses=3  edges=7
presses=4  edges=11

Every edge beyond two per press is a bounce of the contacts, and presses still counts each press once.

Step 3: Take the pull-up away

In setup(), change INPUT_PULLUP to INPUT and upload again. Do not press the button. Touch the yellow jumper, or move a hand close to it: lines appear, presses climbs and the LED switches by itself. Put INPUT_PULLUP back and upload. The pin is quiet again until the button is pressed.

Step 4: Block the loop with delay()

Add the line delay(500); as the last line of loop(), as a program that blinks with delay() would have, and upload. Press the button quickly three times in a row. Most of the quick presses are lost, and edges grows more slowly than before. Remove the line again.

NoteCheckpoint: the button

Every press switches the LED once and adds one to presses. edges grows by at least two per press. With INPUT the pin switches without a press, and with delay(500) quick presses are lost.

How It Works

Pull-up and pull-down

An input pin draws almost no current: it only senses the voltage on it. With the button open and nothing else connected, nothing sets that voltage. The pin and the yellow jumper hold a tiny charge that a hand nearby or a neighbouring wire can push either way, so the reading wanders between HIGH and LOW. Such an input is called floating, and it is what Step 3 showed.

A pull-up resistor from the pin to 3.3 V gives the open pin a defined level, HIGH. INPUT_PULLUP switches on a resistor of about 45 kΩ inside the ESP32. Pressing the button connects the pin to ground through the contact, which is far stronger than the resistor, so the pin reads LOW, and the resistor carries \(3.3/45\,000\) A = 73 µA while the button is held. A pressed button therefore reads LOW and a released one HIGH, which is why the program counts a press when the stable level becomes LOW.

The mirror image is a pull-down: the resistor to ground keeps the open pin LOW, and the button connects the pin to 3.3 V. INPUT_PULLDOWN switches on the internal one. Both work. The pull-up is the more common choice, because the button then needs only a ground wire, and ground is everywhere on a board, and a button wire that touches the chassis by accident does no harm. GPIO 34 to 39 have no internal resistors at all (Which pins can read), so a button on one of them needs an external resistor, typically 10 kΩ.

Contact bounce

The contacts of a button are two pieces of spring metal. When they meet, they hit, spring apart and hit again several times before they rest on each other, and the same happens on release. The pin follows every touch (Figure 13.10.2). The whole bounce lasts around a millisecond for a small tactile button and can last several milliseconds for a large switch or one that has worn.

Figure 13.10.2: The voltage on GPIO 27 when the button is pressed, in the shape an oscilloscope shows. The contacts touch, part and touch again for about a millisecond before they stay closed. The number and timing of the bounces change from press to press.

To us that is one press. To the program it is several, because loop() reads the pin far more often than the bounces last: one pass of the button program takes a few microseconds, so it reads the pin several hundred times during one bounce. Without debouncing, the LED would switch four times on the press of Figure 13.10.2 and end up where it started.

Debouncing in software

The program keeps two levels. rawLevel follows the pin exactly, and every change records the time in changedMs. stableLevel is the level we believe in, and it takes the raw level only once the raw level has held for debounceMs without changing. During a bounce the raw level changes again and again, changedMs keeps moving forward, and the 20 ms never pass. They pass 20 ms after the last bounce, and then the press counts once. The release bounces too, and it is filtered the same way, so the next press starts from a clean HIGH.

The 20 ms must be longer than the bounce and shorter than anything a person does on purpose. A deliberate press and release take more than 100 ms, so 20 ms leaves room on both sides. The price is that the press is recognised 20 ms after the contact settles, which nobody notices.

Debouncing in hardware

A capacitor of 100 nF across the button does the same job before the signal reaches the pin. Pressing the button empties the capacitor through the contact at once. While the contact bounces open, only the 45 kΩ pull-up can recharge it, with the time constant

\[ \tau = RC = 45~\text{k}\Omega \cdot 100~\text{nF} = 4.5~\text{ms}. \]

During an opening of 0.1 ms the capacitor recovers only the fraction \(1 - e^{-0.1/4.5} = 2.2\) %, or 0.07 V, and the pin stays far below the level where the ESP32 reads HIGH, about 2.5 V. On release the voltage rises along the same curve and crosses 2.5 V after \(\tau \ln 4 \approx 6\) ms. Hardware debouncing needs no code, but it needs a part per button and makes the edges slow. Software debouncing is free on a microcontroller, which is why we use it.

Never wait in loop()

delay(500) stops the program for half a second. Nothing else happens in that time: no reading of the button, no answer to the serial port, and on the car no steering. A press that begins and ends inside the delay is never seen, which is what Step 4 showed.

The way out is to let loop() run freely and decide in each pass whether something is due. millis() returns the number of milliseconds since the start. A program that should do something every 500 ms remembers when it last did it and compares:

unsigned long lastBlinkMs = 0;      // above setup()

// in loop(): blink without stopping anything else
  if (millis() - lastBlinkMs >= 500) {
    lastBlinkMs = millis();
    ledOn = !ledOn;
    digitalWrite(ledPin, ledOn ? HIGH : LOW);
  }

A pass in which nothing is due costs a few microseconds, so the loop still reads the button hundreds of thousands of times a second. The subtraction millis() - lastBlinkMs also stays correct when millis() runs past its largest value after 49.7 days and starts again from zero, since unsigned arithmetic wraps round in the same way. The debounce of the button program uses the same comparison, and so does every later program in this part: the sweep of the servo bench, the control step of the motor bench and the battery samples of Battery sensing.

Exercises

Exercise 1: The debounce time

Set debounceMs to 1 and press the button twenty times. How many presses are counted? Then set it to 300 and press as fast as you can. What is lost now, and why?

Exercise 2: Debouncing with a capacitor

Put a 100 nF capacitor across the button, from column 18 to column 20, and set debounceMs to 0. Compare edges and presses with Step 2. Predict, then measure with the oscilloscope on GPIO 27, how long the pin takes to rise after a release.

Exercise 3: A long press

Extend the program so that a press held for more than one second prints long instead of switching the LED. Use millis() and no delay().