ESP32-P4: a button toggles an LED
Run a first sketch on the ESP32-P4: 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: Smart home display (Smart home): The ESP32-P4's power drives touch screens and camera panels.
The ESP32-P4 is a high-performance dual-core RISC-V chip with no built-in Wi-Fi or Bluetooth. It is made for human-machine interfaces: it has MIPI display and camera interfaces and plenty of memory, and it pairs with a separate radio chip when a project needs one.
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-P4:
pinMode(),digitalWrite()andSerialwork as on an Uno - Reading a button with
INPUT_PULLUPon 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. It is the most powerful chip here, and the only one without a radio.
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-P4 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 nodelay(). - Hold the button down: the count must go up once per press, not once per loop.
- Print
ESP.getChipModel()insetup()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");
}
}
}