GPIO, Timers, and PWM
Every pin has a history: a default state, a strapping role at boot, and a drive strength. Ignore the history and the pin ignores you.
🎯 By the end you'll understand
What a GPIO configuration actually sets (direction, pull, drive strength, open-drain, and which peripheral owns the pad), why pins glitch at reset and how to hold them through deep sleep. Why GPIO9 is sampled by the ROM at every reset and exactly what happens when Beacon's user button is held at the wrong instant. The difference between a delay and a timer, and which one Beacon's 45 ms active window can afford. And the LEDC arithmetic — frequency times resolution is bounded by the clock — that decides whether a dimmed LED flickers, bands, or cannot be configured at all.
KEY INSIGHTA pin is a contract with three parties
Beacon Rev A's button works perfectly. Press it, the LED acknowledges, the firmware does the right thing — thousands of times, in every test. Then a technician holds it while sliding the battery connector on, and the tag is dead until someone pulls the battery again. Nothing is broken. The pin simply had a job before your code existed.
A GPIO pin is shared by three parties who never meet. The ROM looks at a few pins in the first microseconds after reset to decide how to boot. The hardware — pad, pull resistors, driver transistors, the IO multiplexer — has a default state that exists whether or not any code has run. And your firmware arrives last and configures the pin for the job you want. Most GPIO bugs are one party assuming it is the only one: firmware that never sets the drive strength and wonders why an LED is dim; a schematic that puts a pull-down on a strapping pin; a wake-up design that assumes any pin can wake the chip. Reading a pin's history — default, strapping role, RTC capability, peripheral function — before assigning it is the discipline this lesson installs.
The ESP32-C3 samples GPIO2, GPIO8, and GPIO9 at every reset — power-on, brown-out, watchdog, and the reset that ends a deep sleep — and it does so before any code you wrote can run. Whatever is electrically on those pins at that instant is a boot-mode command. Beacon's user button is on GPIO9, so Beacon's user is, at that instant, in charge of the boot mode. That is the whole Rev A trap, and every other fact in this lesson is a smaller version of the same idea: the pin has a state before you do.
CORE CONCEPTConfiguring a pin: what the five fields actually do
ESP-IDF's gpio_config_t has five fields. Each maps to a physical structure in the pad, and each has a wrong value that fails silently.
| Field | Physical meaning | Values that matter | Silent failure if wrong |
|---|---|---|---|
mode | Which driver transistors are enabled: input buffer, push-pull output (both a high-side and low-side transistor), or open-drain (low-side only) | GPIO_MODE_INPUT, _OUTPUT, _OUTPUT_OD, _INPUT_OUTPUT, _INPUT_OUTPUT_OD | Push-pull on an I2C line fights the pull-up and any other driver; a "high" from an open-drain pin with no pull-up is a float |
pull_up_en / pull_down_en | Weak internal resistors, roughly 45 kΩ on the ESP32-C3 (datasheet typical; treat as ±30 %) | Enable exactly one, or neither | An input with neither pull and nothing driving it floats and reads noise; a 45 kΩ pull-up is far too weak for I2C at 400 kHz (Lesson 2.1 sized 4.7 kΩ) |
intr_type | Edge or level detector feeding the interrupt controller | GPIO_INTR_POSEDGE, _NEGEDGE, _ANYEDGE, _LOW_LEVEL, _HIGH_LEVEL, _DISABLE | A level interrupt on a line that stays asserted re-fires forever (3.4); an edge interrupt on a bouncing button fires ten times per press |
pin_bit_mask | Which pads this configuration applies to | 1ULL << n — 64-bit, always | 1 << 21 is fine; the habit of using a 32-bit shift breaks on chips with pins above 31 |
| (separate call) drive strength | How many parallel driver transistors are enabled: sets output current capability and edge speed | gpio_set_drive_capability(pin, GPIO_DRIVE_CAP_0…3) — Espressif documents approximately 5, 10, 20 (default), 40 mA | Weakest setting on a pin driving an LED without a transistor: dim. Strongest on a long trace: overshoot, ringing, EMI (6.4) |
#include "driver/gpio.h" #define PIN_BUTTON 9 // strapping pin — see #strapping before you trust this #define PIN_LED_PWR 10 // gate of the high-side PMOS feeding the WS2812B (active-low) #define PIN_ACC_INT 3 // LIS2DH12 INT1 — must be GPIO0–5 to wake from deep sleep void pins_init(void) { // Button: input, internal pull-up (the external 10 kΩ from 2.7 is the real one; // the internal ~45 kΩ is a backstop). Interrupt on falling edge, debounced in 3.4. gpio_config_t btn = { .pin_bit_mask = 1ULL << PIN_BUTTON, .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_ENABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE, .intr_type = GPIO_INTR_NEGEDGE, }; ESP_ERROR_CHECK(gpio_config(&btn)); // LED power switch: push-pull output. Drive HIGH first (PMOS off), then enable // the output, so the LED never sees a glitch of power during init. gpio_set_level(PIN_LED_PWR, 1); // latch value before direction gpio_config_t led = { .pin_bit_mask = 1ULL << PIN_LED_PWR, .mode = GPIO_MODE_OUTPUT, .pull_up_en = GPIO_PULLUP_DISABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE, .intr_type = GPIO_INTR_DISABLE, }; ESP_ERROR_CHECK(gpio_config(&led)); gpio_set_drive_capability(PIN_LED_PWR, GPIO_DRIVE_CAP_1); // a gate needs no current; keep edges gentle // Accelerometer interrupt: input, no pulls (LIS2DH12 drives INT1 push-pull, active-high). gpio_config_t acc = { .pin_bit_mask = 1ULL << PIN_ACC_INT, .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_DISABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE, .intr_type = GPIO_INTR_POSEDGE, }; ESP_ERROR_CHECK(gpio_config(&acc)); }
The highlighted line is a habit worth acquiring: set the output latch before enabling the output driver. The GPIO output register has a value even while the pin is an input; when you switch the pin to output, the pin immediately drives that value. If the latch holds 0 (the reset default) and your PMOS is active-low, the LED gets a pulse of power for the microseconds between gpio_config() and your first gpio_set_level(). Harmless for an LED, not harmless for a motor driver or a relay.
A push-pull output has two transistors: one pulls the pin to 3.3 V, the other to ground, and exactly one is on. It can source and sink current and it cannot share the wire with any other driver — two push-pull outputs driving opposite levels short the supply through both transistors. An open-drain output has only the low-side transistor; "high" means "let go" and a pull-up resistor does the rest. That is what makes I2C possible: any device can pull the line low, none can fight, and the slowest device can stretch the clock by holding it (3.5). It is also why I2C rise time is set by the pull-up and the bus capacitance, not by the chip.
HOW IT WORKSMultiplexing, reset glitches, and holding a pin through sleep
The ESP32-C3 has 22 GPIO pads and dozens of peripheral signals — UART TX/RX, I2C SDA/SCL, SPI, LEDC channels, RMT, the USB pair. Two structures route signals to pads. The IO_MUX connects each pad to a short list of "native" functions with minimal delay; the GPIO matrix is a crossbar that can route almost any peripheral signal to almost any pad, at the cost of a small extra delay. For Beacon's speeds — I2C at 400 kHz, an RMT bit stream for the LED — the matrix is fine and the freedom is worth it. For an 80 MHz SPI flash or a high-speed signal, the datasheet insists on IO_MUX pins. The USB Serial/JTAG pair (GPIO18/19) is fixed; it is a dedicated analogue function, not a matrix signal.
Not every pad is equal, and the differences are the "history" in this lesson's title:
| ESP32-C3 pins (MINI-1 module exposes 0–10, 18–21) | Special history | Beacon consequence |
|---|---|---|
| GPIO0 – GPIO5 | RTC-domain pads: the only pins that can wake the chip from deep sleep. ADC1 is GPIO0–GPIO4 only (GPIO5 is ADC2_CH0) | LIS2DH12 INT1 and the battery divider's ADC input must be here |
| GPIO2, GPIO8, GPIO9 | Strapping pins, sampled by the ROM at reset | The user button is on GPIO9 — the trap below |
| GPIO18, GPIO19 | USB D−/D+ for the native USB Serial/JTAG | Reserved; console and debug in 3.9 |
| GPIO20, GPIO21 | UART0 RX/TX by default; the ROM logs here at boot | Free to reuse, but the ROM's boot banner will pulse GPIO21 at every reset |
| GPIO11 – GPIO17 | Connected to the in-package flash on the MINI-1 | Not available. A schematic that uses them will not fit an assembled module. |
Glitches at reset. Between power-on and your gpio_config() — a few tens of milliseconds through the ROM and bootloader (3.1) — every pad sits in its reset state: input, with whatever default pull the datasheet lists. Pins with a default pull-up (GPIO9 among them) go high the instant the supply is up. Pins with none float, and a floating gate on an external MOSFET is a random switch. The fix is on the schematic, not in code: every MOSFET gate and every enable pin gets a resistor that defines its state with the MCU unpowered (2.7 put the 100 kΩ on the LED PMOS gate for exactly this reason). Firmware then merely agrees with the resistor.
Holding through deep sleep. Deep sleep powers down the digital core and, with it, the pin configuration. By default a pad reverts to its reset state during sleep — so the LED PMOS gate, driven high (off) by the app, would float during the 60 s and the 100 kΩ pull-up is what keeps the LED off. If a pin must hold a level that differs from its passive default, ESP-IDF provides gpio_hold_en(pin) plus gpio_deep_sleep_hold_en(), which latches the pad's driver state in the RTC domain across sleep. Beacon uses this for nothing in Rev A precisely because every switched pin has a resistor that agrees with sleep; the hold feature is the backup, not the design.
DEFINITIONStrapping pins, and why GPIO9 is Beacon's button anyway
The ROM cannot read a config file — there is no filesystem yet, no flash mapping, nothing but the ROM and a few pins. So the chip designers gave the ROM a way to take instructions from the board: at the moment reset is released, it latches the levels of a handful of pins and uses them as a boot-mode word. On the ESP32-C3:
| Pin | Default | Role at reset | Normal boot (SPI flash) | Download boot (ROM waits for esptool) |
|---|---|---|---|---|
| GPIO9 | Pull-up on | Boot mode select | High (1) | Low (0) |
| GPIO8 | No default pull | Must be high for download boot to be valid | Don't care | High (1) |
| GPIO2 | No default pull | Must be high in both modes | High | High |
Read the first row again. GPIO9 defaults to a pull-up, so with nothing attached the chip boots from flash — the designers chose the pull so the "do nothing" case is the normal case. To enter download mode a board needs to pull GPIO9 low at reset, which is exactly what a button to ground does. Every ESP32-C3 dev kit has a "BOOT" button on GPIO9 for this reason, and idf.py flash uses the USB Serial/JTAG controller to do the same thing electrically without the button (3.2).
Beacon puts its user button on GPIO9 — and the honest reason is that it looked free, it already has the pull-up the button needs, and the dev-kit firmware in Stage 3 works unchanged. The canon records the consequence as a Rev A defect and this lesson explains its full mechanism:
(1) Battery insertion while the button is held. Power rises, the brown-out detector releases reset, the ROM samples GPIO9 low with GPIO8 high, and enters download mode. It then waits, forever, for a flashing tool on USB. The app never runs, the LED never blinks, and there is no watchdog in the ROM to time out. The tag is dead until power is removed and reapplied with the button released. (2) Deep-sleep wake while the button is held. A wake from deep sleep is a reset (3.1), and the ROM samples strapping pins on every reset. Hold the button across the 60 s timer wake and the same thing happens in the field, on a tag that was working. (3) The button cannot wake the chip. GPIO9 is not an RTC-domain pad; only GPIO0–5 can end a deep sleep. So a press while asleep does nothing until the next timer or motion wake — and if the press is still held at that instant, see (2). Rev B moves the button to an RTC-capable pad. Rev A firmware lives with the constraints below.
How Rev A firmware copes, and it is a genuine compromise rather than a fix. The app never relies on the button to wake the device. The OTA opt-in is served at cold boot only: after battery insertion or USB connection, the FSM's SELF_TEST state stays awake for about two seconds with the LED lit, and a button press during that window — after the ROM has already sampled the pin released — selects OTA mode (4.9). The user instruction becomes "connect power, wait for the light, then hold the button", and the manual has to say in bold not to hold it while connecting. It is a usability defect with a firmware bandage, which is exactly what the Stage 6 post-mortem will call it.
You can see the ROM's decision on the monitor. Every reset prints a banner whose second line encodes the strapping state; on a normal boot the ESP32-C3 prints rst:0x1 (POWERON),boot:0xc (SPI_FAST_FLASH_BOOT), and in download mode boot:0x4 (DOWNLOAD(USB/UART0)) followed by waiting for download. Learn to read that line; it is the first piece of evidence in every "the board is dead" report.
SEE ITPWM and pin lab: two ways a pin can ignore you
Left pane: configure an LEDC timer for a dimmable LED and watch the achievable duty steps collapse as frequency rises — until the driver refuses the configuration outright. Right pane: choose what the user is doing with Beacon's GPIO9 button at the moment of a reset, and see which boot mode the ROM enters and what the device does afterwards. Both panes are deterministic; both have a choice that looks reasonable and produces a dead board or a visibly bad LED.
Notice what the left pane says about "more is better". Pushing frequency up to escape camera banding is right; pushing it to 200 kHz at 14 bits is impossible, and the driver tells you so with ESP_ERR_INVALID_ARG — the good outcome. The bad outcome is 100 kHz at 8 bits: it configures, it runs, and the lowest non-zero brightness is 1/256 of full, so a "breathing" animation visibly steps at the dim end. The right pane's bad outcome is quieter still: Rev A, timer wake, button held. The build was fine, the firmware was fine, and the tag is dead in a customer's hand.
CORE CONCEPTTimers versus delays: four ways to wait, one of which is a lie
Beacon's active window is ≈ 45 ms and the whole battery budget depends on it (R1). Inside that window the firmware must wait for the SHT40's measurement (about 8 ms at high precision), space out three BLE packets, and time a button. How it waits determines whether the wait costs 40 mA of awake current, whether other tasks can run meanwhile, and whether the timing is even accurate.
| Mechanism | What actually happens | Resolution / accuracy | CPU during the wait | Use it for |
|---|---|---|---|---|
esp_rom_delay_us(n) (busy-wait) | The core spins counting cycles | Sub-microsecond; drifts with clock changes | 100 % busy, nothing else runs, interrupts still fire | Sub-100 µs gaps in a bit-banged protocol; nothing longer, ever |
vTaskDelay(pdMS_TO_TICKS(n)) | Task blocks; scheduler runs others or idles | One tick — 10 ms by default (CONFIG_FREERTOS_HZ=100); a request of 8 ms waits 10–20 ms | Free; idle task can enter light sleep | Waits of tens of ms and up where ±1 tick is fine |
esp_timer (high-resolution) | 64-bit µs timer; callback runs from a dedicated task (or ISR, if requested) | Microseconds; one-shot or periodic | Free; callbacks are asynchronous | Precise one-shots: "read the SHT40 8.5 ms from now", the OTA window timeout, debounce |
gptimer (hardware general-purpose timer) | A counting peripheral with alarm compare; alarm callback runs in ISR context | Clock-cycle exact (APB/prescaler) | Free; ISR rules apply (3.4) | Hard real-time edges, input capture, anything where jitter must be near zero |
| RTC timer (deep-sleep wake) | Counter in the always-on domain, runs from the ~136 kHz RC oscillator | Milliseconds; the RC oscillator drifts a few percent with temperature | Core is off | The 60 s report period. Accept that "60 s" is 58–62 s across 0–45 °C |
The lie is the busy-wait. It feels precise and it is — but during an esp_rom_delay_us(8000) the BLE host's tasks cannot run, the idle task cannot sleep, and the watchdog on a long enough spin will fire. A 10 ms busy-wait in a loop is 10 ms at 40 mA that could have been 10 ms of light sleep at a fraction of that. In Beacon's firmware the only busy-waits are inside drivers for gaps shorter than 100 µs; every longer wait is either a blocking call that yields or an esp_timer callback that advances the state machine (3.7).
// 1. Wrong: precise, and it freezes the scheduler for 8.5 ms at 40 mA. esp_rom_delay_us(8500); // 2. Acceptable: yields, but the 10 ms tick rounds this to 10–20 ms of awake time. vTaskDelay(pdMS_TO_TICKS(9)); // pdMS_TO_TICKS(9) == 0 ticks at 100 Hz! use ≥ 10, or raise CONFIG_FREERTOS_HZ // 3. Beacon's way: a one-shot timer posts an event; the FSM handles it (3.7). static void on_sht40_ready(void *arg) { fsm_post(EV_SAMPLE_READY); } // runs in esp_timer's task static const esp_timer_create_args_t targs = { .callback = on_sht40_ready, .name = "sht40", .dispatch_method = ESP_TIMER_TASK, }; esp_timer_handle_t t; ESP_ERROR_CHECK(esp_timer_create(&targs, &t)); ESP_ERROR_CHECK(esp_timer_start_once(t, 8500)); // µs; core is free to run the BLE host meanwhile
The comment on line 2 is not a joke: pdMS_TO_TICKS(9) at a 100 Hz tick is zero ticks, and vTaskDelay(0) is a yield, not a wait. The SHT40 read that follows returns a NACK because the sensor is still measuring, and the driver in 3.6 has to handle that as an error. Tick resolution is a system property; know yours before you write a number.
HOW IT WORKSLEDC PWM: frequency, resolution, and the clock that bounds both
Pulse-width modulation is a counter and a comparator. The LEDC timer counts from 0 to 2res − 1 at some clock rate and wraps; the output is high while the count is below the duty value. So the PWM frequency is the clock divided by the period count, and the number of distinct brightness levels is the period count. Those two are the same number seen from two sides, which is the entire trade-off:
fPWM = fclk ÷ (divider × 2res). On the ESP32-C3 with the 80 MHz APB clock, the divider is at least 1, and the resolution is at most 14 bits. So fPWM × 2res ≤ 80 MHz. At 14 bits the fastest possible PWM is 80 MHz ÷ 16384 ≈ 4.88 kHz. At 1 kHz you can have the full 14 bits (16,384 levels). At 100 kHz you can have at most 9 bits (512 levels), and at 1 MHz only 6 bits (64 levels). Ask for more and ledc_timer_config() returns ESP_ERR_INVALID_ARG. The divider has a fractional part on the C3, so intermediate frequencies are reachable, but the ceiling is the ceiling.
What frequency and resolution does an LED actually need? The eye stops seeing flicker somewhere above 100 Hz for a steady source, so 200 Hz is a safe floor for an indicator. Phone cameras with rolling shutters band at anything up to about a kilohertz, so a product that will be filmed wants 1 kHz or more. Perceived brightness is roughly logarithmic, so the dim end of a fade needs fine steps: with 8 bits the first non-zero level is 0.4 % of full and clearly visible as a jump; with 12 bits it is 0.02 % and smooth. A comfortable LED configuration on the C3 is therefore 1–5 kHz at 12–13 bits, and it costs nothing. The trouble starts when someone copies a 25 kHz motor-drive frequency for an LED and keeps 14 bits — impossible — or drops to 8 bits — banded.
#include "driver/ledc.h" #define LED_GPIO 8 #define LED_RES LEDC_TIMER_12_BIT // 4096 levels #define LED_HZ 2000 // 2000 × 4096 = 8.2 MHz ≤ 80 MHz ✓ void led_pwm_init(void) { ledc_timer_config_t tcfg = { .speed_mode = LEDC_LOW_SPEED_MODE, // the C3 has only the low-speed group .timer_num = LEDC_TIMER_0, .duty_resolution = LED_RES, .freq_hz = LED_HZ, .clk_cfg = LEDC_AUTO_CLK, }; ESP_ERROR_CHECK(ledc_timer_config(&tcfg)); // enables the LEDC clock (3.1) and checks the math ledc_channel_config_t ccfg = { .gpio_num = LED_GPIO, // routed through the GPIO matrix .speed_mode = LEDC_LOW_SPEED_MODE, .channel = LEDC_CHANNEL_0, .timer_sel = LEDC_TIMER_0, .duty = 0, .hpoint = 0, }; ESP_ERROR_CHECK(ledc_channel_config(&ccfg)); } void led_set(float frac) // 0.0 – 1.0 perceived; gamma ≈ 2.2 { uint32_t duty = (uint32_t)(frac * frac * frac * 4095.0f); // cheap gamma: cube ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, duty); ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0); // nothing changes until this }
Two details that catch people. ledc_set_duty() writes a shadow register and ledc_update_duty() commits it at the next period boundary — forget the second call and the LED never changes, which is the 3.1 "peripheral does nothing" family again. And the order matters: timer first, channel second. Configure the channel before its timer exists and the channel binds to a stopped timer; some versions of the driver accept this silently.
Beacon's LED is not a PWM LED. The canon's WS2812B-2020 is a serially addressed RGB LED: it takes a single-wire bit stream at 800 kbit/s with specific high/low pulse widths, which ESP-IDF generates with the RMT peripheral (via the led_strip component), not LEDC. LEDC on Beacon is therefore the dev-kit lesson and the fallback for a Rev B with a plain LED. What LEDC teaches survives the change of peripheral: a clock, a period, a duty, and a bound between them.
BEACONBeacon's pins, fixed for firmware v0
The dev-kit firmware and the Rev A board share a pin map from here on so that Stage 5's schematic and Stage 3's code agree. Every assignment has its history noted — that is the point of the lesson.
| Signal | Pin | Config | History that justified it |
|---|---|---|---|
| I2C SDA / SCL (SHT40 0x44, LIS2DH12 0x19) | GPIO6 / GPIO7 | Open-drain via I2C driver; external 4.7 kΩ pull-ups (2.1) | Non-strapping, non-RTC, free on the MINI-1; matrix-routed, fine at 400 kHz |
| LIS2DH12 INT1 (motion wake) | GPIO3 | Input, no pull, rising edge; deep-sleep wake via esp_deep_sleep_enable_gpio_wakeup(BIT(3), ESP_GPIO_WAKEUP_GPIO_HIGH) | Must be GPIO0–5 to wake from deep sleep (R4) |
| Battery divider sense | GPIO4 (ADC1_CH4) | ADC input; the divider is switched by a PMOS on GPIO1. Settle ≥ 250 ms (5τ, τ = 500 kΩ × 100 nF = 50 ms) before sampling | ADC1 is GPIO0–GPIO4 (GPIO5 is ADC2_CH0), and GPIO4 is RTC-domain. Deliberately not GPIO2: GPIO2 is a strapping pin that must read high at reset, but with the PMOS off the lower 1 MΩ pulls this node to ground — the board would latch the wrong boot mode every time |
| User button | GPIO9 | Input, pull-up, falling-edge interrupt; sampled during the 2 s cold-boot SELF_TEST for OTA opt-in | Strapping pin: the Rev A trap. Cannot wake from deep sleep. Rev B → GPIO0. |
| LED power (high-side PMOS gate) | GPIO10 | Push-pull output, latched high (off) before direction set; 100 kΩ pull-up on the schematic | Passive default agrees with sleep — no hold needed |
| WS2812B data | GPIO5 | RMT TX channel via led_strip | Any matrix pin works; kept away from the strapping pins |
| USB D− / D+ | GPIO18 / GPIO19 | Native USB Serial/JTAG — console and debug | Dedicated function; 22 Ω series resistors per canon |
(1) The pin map above. (2) The output-latch-before-direction rule for every switched rail. (3) No busy-wait longer than 100 µs anywhere in the application; the SHT40 wait is an esp_timer one-shot. (4) The button is never a wake source in Rev A; OTA opt-in is a press during the two-second cold-boot self-test window, and the user documentation says so. (5) The LED indicator on the dev kit runs LEDC at 2 kHz / 12 bits; on Rev A the WS2812B runs from RMT behind the PMOS, and both are off for the entire deep sleep.
WEAKNESSWhere this bites
On the ESP32-C3, deep-sleep wake works only from RTC-domain pads GPIO0–5 (plus the RTC timer). esp_deep_sleep_enable_gpio_wakeup() on any other pin returns an error that a careless ESP_ERROR_CHECK-free call ignores, and the device simply never wakes on that source. Light sleep is more permissive — gpio_wakeup_enable() works on any pin — which is exactly how the confusion starts: a prototype that used light sleep worked, the production firmware switched to deep sleep for the µA budget, and the motion wake silently died. Check the pad's RTC capability before assigning any wake signal, and check the return value.
Motor drives use 20–30 kHz to stay above audible frequencies; that need does not exist for an LED, but the number gets copied anyway. At 25 kHz the C3's LEDC can give at most 11 bits — fine — but a project that also copied "14 bits" from an example gets ESP_ERR_INVALID_ARG and the usual response is to drop resolution until it configures, ending at 8 bits and a fade that visibly steps. The right response is to drop frequency: nothing about an LED needs 25 kHz, and 2 kHz at 12 bits is both flicker-free on camera and smooth at the dim end. Know what each number is for before choosing it.
The C3's internal pulls are roughly 45 kΩ and exist only once the digital core is powered and configured. They cannot define a MOSFET gate during the reset glitch window, cannot pull an I2C line up fast enough at 400 kHz with real bus capacitance, and cannot be relied on for a strapping pin when a connected device might pull the other way. Every one of Beacon's switched signals has an external resistor on the schematic for the unpowered case; the internal pull is a convenience for inputs after boot, never the design.
KEY INSIGHTHow this connects
- Inside a Microcontroller (3.1) — the ROM's boot sequence that samples GPIO9 and the clock-gate inside
ledc_timer_config()were both introduced there; this lesson is what they do to real pins. - Switching Things: Driving LEDs, Motors, and Relays (2.7) — the high-side PMOS, its 100 kΩ gate pull-up, and the button's external pull-up were chosen there. Firmware's job is to agree with those resistors, especially during reset and sleep.
- Interrupts, Polling, and the Latency Budget (3.4) — next: the falling-edge interrupt configured on the button and the rising-edge interrupt on INT1 become ISRs with rules, and the button's bounce becomes a debouncing problem.
- State Machines and Event-Driven Firmware (3.7) — the two-second cold-boot SELF_TEST window that makes the Rev A button usable is a state with a timer, defined there.
The pattern to carry forward: before you write to a pin, read its history — what the ROM does with it, what its passive default is, whether it is RTC-capable, what peripheral function it has. Five minutes with the datasheet's pin table prevents the kind of defect that survives every bench test and fails in a customer's hand.
GLOSSARYKey terms introduced
- Push-pull / open-drain
- Output types: push-pull drives both high and low with two transistors and cannot share a wire; open-drain only pulls low and relies on a pull-up, which is what lets I2C devices share a line.
- Drive strength
- The selectable output-current capability of a pad (four levels on the ESP32-C3, roughly 5–40 mA). Higher means faster edges and more current, also more ringing and EMI.
- IO_MUX and GPIO matrix
- The two routing structures between peripheral signals and pads: IO_MUX for a pad's few native functions with minimal delay, the matrix for routing almost any signal to almost any pad.
- Strapping pin
- A pad whose level at reset release is latched by the ROM to select boot mode. GPIO2, GPIO8, GPIO9 on the ESP32-C3; GPIO9 low with GPIO8 high enters download mode.
- RTC-domain pad
- A pin powered from the always-on RTC domain (GPIO0–5 on the C3) and therefore able to wake the chip from deep sleep and to hold state during it.
- Tick
- The FreeRTOS scheduler's time quantum (10 ms at the default 100 Hz).
vTaskDelayresolution is one tick; a delay shorter than a tick rounds to zero. - LEDC
- The ESP32-C3's PWM peripheral: timers that count at a divided clock, channels that compare a duty value against the count. Frequency × 2resolution is bounded by the 80 MHz source.
- Duty resolution
- The bit width of the PWM counter, hence the number of distinct duty levels (2res). Determines the smallest non-zero brightness and the smoothness of a fade.
ACTIVE RECALLCheck your understanding
Answer in your own words first, then reveal.
1A Beacon Rev A comes back from the field "dead": no LED, no advertising, battery measures 3.9 V. Pulling and reinserting the battery fixes it. What most likely happened, and what would the USB console have shown?›
The button on GPIO9 was held at the instant of a reset — either while the battery was connected or across a 60 s deep-sleep wake, which is also a reset. The ROM sampled GPIO9 low (GPIO8 high), entered download mode, and waited for a flashing tool that never came; there is no watchdog in the ROM, so it waits until power is removed. The console would show the ROM banner with boot:0x4 (DOWNLOAD(USB/UART0)) and waiting for download instead of boot:0xc (SPI_FAST_FLASH_BOOT). The fix in Rev B is to move the button to an RTC-capable non-strapping pad; the Rev A bandage is documentation and the cold-boot-only OTA window.
2You want a smooth LED fade that does not band on a phone camera. Pick a frequency and resolution for the ESP32-C3's LEDC and show that the configuration is valid.›
Camera banding needs roughly ≥ 1 kHz; a smooth dim end needs ≥ 12 bits so the first step is well under 0.1 % of full. Choose 2 kHz at 12 bits. Validity: f × 2res = 2000 × 4096 = 8.19 MHz, which is below the 80 MHz APB clock, so a divider of about 9.77 exists (the C3's divider has a fractional part) and ledc_timer_config() succeeds. For contrast, 25 kHz at 14 bits would need 409.6 MHz and fails with ESP_ERR_INVALID_ARG; 100 kHz at 8 bits (25.6 MHz) configures but its first non-zero level is 0.4 % — a visible jump.
3Why does vTaskDelay(pdMS_TO_TICKS(9)) not wait 9 ms on a default ESP-IDF build, and what should Beacon use to wait for the SHT40 instead?›
The default FreeRTOS tick is 100 Hz, so one tick is 10 ms and pdMS_TO_TICKS(9) evaluates to 0 ticks; vTaskDelay(0) merely yields. The SHT40 read then arrives before the measurement is complete and the sensor NACKs. A vTaskDelay of ≥ 1 tick works but rounds up to 10–20 ms of awake time at ~40 mA — a real cost against R1 when it happens every minute. Beacon uses an esp_timer one-shot of 8,500 µs whose callback posts an event to the state machine; the core is free (or the BLE host runs) meanwhile, and the wait is accurate to microseconds. A busy-wait would be accurate too, but freezes the scheduler and burns the full active current for the duration.
4Beacon's LED PMOS gate is on GPIO10 and the LED must be off during deep sleep. Which two mechanisms keep it off, and which one is the design and which the backup?›
The design is the schematic: a 100 kΩ pull-up from the gate to the battery rail (2.7) holds the PMOS off whenever nothing drives the gate — during the reset glitch window, during deep sleep when the pad reverts to input, and with the MCU entirely unpowered. The backup is gpio_hold_en(10) plus gpio_deep_sleep_hold_en(), which latches the pad's driven high level in the RTC domain across sleep. Beacon does not need the hold because the passive default already agrees with the sleep state; the hold is for pins whose required sleep level differs from what a resistor can cheaply provide. Relying on the hold alone would leave the LED powered for the milliseconds between power-on and pins_init(), which is why the resistor is the primary mechanism.