Read a button, sample voltage, and drive PWM
Use an ESP32-C6 button and knob to control an LED with native ESP-IDF.
Opening the Python editor…
Requirements and learning goals
Before you start
- Complete Run your first ESP32 app on an ESP32-C6-DevKitC-1
- Button, 10k potentiometer, LED, 330-ohm resistor, and breadboard
You will be able to
- Read digital and analog inputs
- Control LED brightness with PWM
What the ESP32 measures
means general-purpose input/output: a pin your program can read or drive. A button supplies a digital on/off state. An analog-to-digital converter, or , turns a voltage into a number. Pulse-width modulation, or , switches a pin rapidly; its on-time fraction controls average LED brightness.
These are the building blocks of a sensor-controlled device. Here, a button enables a light and a knob sets its brightness.
Keep the button and LED in the same loop on the ESP32 so the button still works offline.
Wire it
Disconnect power. On the ESP32-C6-DevKitC-1, connect:
- A button between GPIO 10 and GND.
- The potentiometer's outer terminals to 3.3V and GND, and its middle terminal to GPIO 0.
- GPIO 11 through a 330-ohm resistor to the LED anode; connect its cathode to GND.
Use 3.3V signals, never 5V on these GPIOs. This external LED is separate from the board's RGB LED.
Run it
Reuse the first app's project. Save the complete C example as main/main.c and this component configuration as main/CMakeLists.txt. Keep the project's other files, including the wendy_core dependency.
wendy runThe example initializes the ADC and LEDC PWM peripheral, then repeats this decision every 20 ms:
bool pressed = gpio_get_level(GPIO_NUM_10) == 0;
unsigned duty = valid && pressed ? raw * 1023 / 4095 : 0;The pull-up holds an open button high; pressing it connects the input to ground. The expression maps a 12-bit ADC count to a 10-bit PWM duty value.
Expected result
Hold the button and turn the knob: brightness changes. Release it: the LED turns off. The ADC can saturate near the knob's endpoints; counts are not calibrated voltage.
Troubleshooting
No light? Check LED polarity and GPIO 11. Random readings? Check the knob's ground and middle terminal. To count individual presses later, add debouncing so mechanical contact chatter does not become extra presses.
Reference: ESP32-C6 PWM.
Before you move on
Can you do each of these?
- Read digital and analog inputs
- Control LED brightness with PWM
0 of 2 checkpoints solved. Try checkpoint 1
All lessons in this topic
- 1. Install Wendy Lite on your ESP32
- 2. Update an ESP32 app over Wi-Fi
- 3. Find your ESP32 on Wendy Net
- 4. Use ESP32 sensors from Linux and ROS 2
- 5. Run your first ESP32 app
- 6. Read a button, sample voltage, and drive PWM
- 7. Connect ESP32 sensors with I²C, SPI, and UART
- 8. Handle ESP32 interrupts and detect stalled work
- 9. Build an ESP32 alarm that tolerates noisy readings