Try Embedded

ESP32-S3: a button toggles an LED

Run a first sketch on the ESP32-S3: toggle an LED with a button on GPIO 5, debounce it, and report the count over the serial port.

Basic · Beginner

In a real product: Voice assistant (Consumer electronics): The ESP32-S3's AI instructions run wake-word detection on the device.

The ESP32-S3 has two Xtensa LX7 cores, Wi-Fi 4 and Bluetooth 5 (LE), and native USB. It is the ESP32 to reach for when a project needs a screen, a camera or a little machine learning, thanks to its vector instructions.

This is the same small circuit as on every other board in the simulator, so you can compare them: one LED, one button and a serial line. What changes from chip to chip is the pin map and the radios, not the Arduino code.

What you'll learn

  • Running Arduino code on the ESP32-S3: pinMode(), digitalWrite() and Serial work as on an Uno
  • Reading a button with INPUT_PULLUP on a 3.3 V board
  • Finding the rising or falling edge of a button in software, and a simple debounce
  • Printing with Serial.printf(), which the ESP32 core has and AVR boards do not

How it works

The LED's anode goes through a 220 ohm resistor to GPIO 4 and its cathode to GND. The button joins GPIO 5 to GND, and INPUT_PULLUP holds the pin HIGH until it is pressed. Unlike the C3, it is a dual-core Xtensa chip, so FreeRTOS tasks can really run at the same time on its two cores.

The sketch waits for the button to go from released to pressed, ignores bounces for 30 ms, flips the LED, and prints how many presses it has seen. The simulator's ESP32-S3 runs this on its emulated core, so the timing is the chip's, not the browser's.

Try this

  • Blink the LED on its own with millis() while still reading the button, with no delay().
  • Hold the button down: the count must go up once per press, not once per loop.
  • Print ESP.getChipModel() in setup() and check it names the chip.

sketch.ino

// A button on GPIO 5 (to GND, internal pull-up) toggles an LED on GPIO 4 and counts the presses.
const int LED = 4;
const int BUTTON = 5;

bool ledOn = false;
bool wasPressed = false;
int presses = 0;
unsigned long lastChange = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
  Serial.println("Press the button to toggle the LED");
}

void loop() {
  bool pressed = digitalRead(BUTTON) == LOW;
  if (pressed != wasPressed && millis() - lastChange > 30) {  // a real change, not a bounce
    lastChange = millis();
    wasPressed = pressed;
    if (pressed) {
      ledOn = !ledOn;
      digitalWrite(LED, ledOn);
      presses++;
      Serial.printf("Press %d: LED %s\n", presses, ledOn ? "on" : "off");
    }
  }
}

Lessons behind it