ESP32-C6: a button toggles an LED
Run a first sketch on the ESP32-C6: 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: Matter smart light (Smart home): The ESP32-C6 runs Wi-Fi 6 and Thread for Matter lights and plugs.
The ESP32-C6 is a RISC-V chip with Wi-Fi 6, Bluetooth 5 (LE) and an 802.15.4 radio for Thread and Zigbee. That mix makes it a popular choice for Matter smart-home devices.
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-C6:
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. Its 802.15.4 radio is what a C3 lacks: the C6 can join a Thread or Zigbee mesh.
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-C6 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");
}
}
}