Capstone: A Nonblocking Polled Key and Modular BSP

Complete the GL-E01 bare-metal BSP capstone from first principles: sample active-low tactile switches via GPIO1_PSR, filter millisecond mechanical contact chatter with a nonblocking three-variable FSM, prove modulo-2^32 tick wraparound safety, and coordinate LED + buzzer outputs cleanly.

20 minfree previewLinux 6.12C11U-Boot 2025.x→ module 6 lab
What you'll learn
  • Normalize the sampled active-low PSR input into a logical pressed state.
  • Accept a candidate only after a continuous sampled stable interval.
  • Integrate one press event with LED and buzzer policy without blocking polling.

Mechanical Contact Bounce Physics & Why Blocking Delays Fail

Press a spring-loaded metal dome inside a tactile PCB push-button and zoom in on an oscilloscope at 500 us/div: the voltage on the pin does not step cleanly from 3.3 V to 0 V once! Because elastic metal contacts collide with kinetic energy, rebound microscopically, and re-strike 3..15 times over 1..5 ms on both press and release, the pad sees a rapid burst of 3.3 V <-> 0 V square edges (contact bounce). Look at Figure 6.3a (Panel 1): enabling Schmitt-trigger hysteresis (HYS = 1) in IOMUXC cleans up slow analog RC transitions so mid-rail noise cannot oscillate, but hysteresis cannot suppress full-swing 0 V <-> 3.3 V mechanical bounces separated by milliseconds! If your loop toggles the PNP buzzer on every raw 0 V edge, a single finger press toggles the alarm four or five times at random!

Why not "fix" bounce with if (pressed) { delay_ms(10); ... } inside key_read()? At 528 MHz, spinning inside delay_ms(10) burns 5,280,000 Cortex-A7 clock cycles doing nothing—freezing UART reception, LED telemetry, and other keys on every electrical glitch, while still double-triggering if the user holds their finger down or releases with chatter! Instead, trace the synchronized waveform in Figure 6.3a (Panel 2), driven by a nonblocking three-variable Finite State Machine (candidate, stable, since_ms):

  1. Read GPIO1_PSR (+0x08), never GPIO1_DR (+0x00): On input UART1_CTS_B (ALT5 -> GPIO1_IO18, pulled to 3.3 V idle and switched to GND when pressed), PSR samples the live external pad (pressed = (*psr & (1U << 18)) == 0U), whereas DR holds the unused output latch!
  2. Qualify continuous stability (t = 1..48 ms in Figure 6.3a): Raw chatter at t = 1, 3, 4 keeps resetting since_ms = 4; at t = 13 (13 - 4 = 9 < 10), no event fires; at t = 14 (14 - 4 == 10), stable commits true and one EV_PRESS fires (turning alarm_on = true)! Holding at t = 19 sees candidate == stable (EV_NONE); release chatter at t = 20, 25, 26 settles at t = 36 (EV_RELEASE, re-arming the button without toggling the alarm); and a second press at t = 37 fires EV_PRESS at t = 47 (toggling alarm_on = false)!
fig_m06_l03_a.svg — Active-low tactile switch input path into GPIO1_PSR[18]…

Figure 6.3a. tactile switch input path into GPIO1_PSR[18] (top) and the exact capstone waveform turning press/release chatter into single-shot transitions (bottom).

mental model: A nonblocking debounce FSM is an air-traffic clearance desk that logs a status transition only after radar sweeps confirm the new state holds continuously for 10 ticks—restarting since_ms on any bounce blip while keeping every other BSP subsystem runnable in < 30 CPU cycles per poll.

Where it stops working: Unlike continuous analog radar, discrete polling observes pad voltage only at sample instants and relies on a monotonic unsigned tick source whose poll interval stays well below the 2^32 wraparound horizon.

definition (Nonblocking FSM & Modulo-2^32 Elapsed-Time Subtraction): A nonblocking contact-debounce FSM stores (candidate, stable, since_ms): any sample pressed != candidate updates candidate = pressed and since_ms = now_ms (KEY_NONE), while an unchanged candidate != stable commits stable = candidate and emits exactly one transition event (KEY_PRESS or KEY_RELEASE) once (uint32_t)(now_ms - since_ms) >= threshold_ms. Computing elapsed duration via unsigned modulo-2^32 subtraction (uint32_t)(now - since) remains exact across UINT32_MAX -> 0 wraparound (~49.71 days at 1 kHz), whereas deadline addition now >= since + 10U wraps and misfires early!

Step through the four-stage capstone super-loop connecting GPIO1_PSR, debounce qualification, and bsp/led + bsp/buzzer below:

ast_m06_l03.svg — Sample PSR (never DR), separate candidate from stable…step 1/4
  1. Step 1. Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.
  2. Step 2. Step 2: On any pressed != candidate edge or bounce, update candidate and reset since_ms = now_ms.
  3. Step 3. Step 3: Once candidate != stable and (uint32_t)(now_ms - since_ms) >= 10U, commit stable and emit 1 event.
  4. Step 4. Step 4: Toggle LED0 (GPIO1_DR[3]) and PNP buzzer (GPIO5_DR[1]) on EV_PRESS while preserving sibling bits.

Figure 6.3b. Sample PSR (never DR), separate candidate from stable state, and always subtract (uint32_t)(now - since) >= threshold.

Modulo-2^32 Tick Wraparound Proof & O(1) Poll Architecture

Study Figure 6.3b (Panel 2) carefully—it explains a classic 49.7-day uptime field bug that crashes industrial controllers. A 32-bit 1 ms tick counter (uint32_t now_ms) counts from 0x00000000 up to 0xFFFFFFFF (4,294,967,295 ms ~= 49.71 days) and then wraps cleanly back to 0x00000000 under ISO C11 unsigned modulo-2^32 arithmetic. Suppose a button bounce starts 6 milliseconds before wraparound: since = UINT32_MAX - 5 = 0xFFFFFFFA.

  • Why if (now >= since + 10U) is broken: 0xFFFFFFFA + 10U overflows 32 bits and wraps to 0x00000004! Just 1 ms later (now = 0xFFFFFFFB), 0xFFFFFFFB >= 0x00000004 evaluates true immediately—passing raw contact bounce straight into your application!
  • Why if ((uint32_t)(now - since) >= 10U) is exact: At now = 0xFFFFFFFE, 0xFFFFFFFE - 0xFFFFFFFA == 4U (< 10U); after wrap at now = 0x00000003, (3U - 0xFFFFFFFAU) == 9U (< 10U); and at now = 0x00000004, (4U - 0xFFFFFFFAU) == 10U (>= 10U, firing after the exact 10-tick physical interval)!
fig_m06_l03_b.svg — Nonblocking O(1) debounce branches (left) and why…

Figure 6.3b. Nonblocking O(1) debounce branches (left) and why unsigned subtraction (uint32_t)(now - since) survives 49.7-day UINT32_MAX wraparound (right).

Switch-Handling ImplementationSuper-Loop CPU CostBounce & UINT32_MAX BehaviorEngineering Verdict
Blocking if (!psr) { delay_ms(10); ... }Burns 5.28M cycles @ 528 MHzStarves UART/sensors; re-fires while held!Broken beyond toy demos
Deadline now >= since + 10UO(1) nonblocking (< 30 cycles)Fails near UINT32_MAX: wrapped since + 10 fires in 1 tick!Latent 49.7-day uptime bug
Subtraction (uint32_t)(now - since) >= 10UO(1) nonblocking (< 30 cycles)Exact across UINT32_MAX; debounces press & releaseProduction bare-metal standard
Reading GPIO1_DR (+0x00) instead of PSRO(1)Reads output latch instead of external switch pin!Dead input bug

In bsp_key.c below, key_poll() reads GPIO1_PSR (0x0209C008, base 0x0209C000 + 0x08) through a volatile const uint32_t * pointer, normalizes active-low bit 18, and executes the exact O(1) three-branch FSM.

learner@ksa: ~/gl-e01/m06-l03
learner@ksa:~/gl-e01/m06-l03$ bat -H 8 -H 9 -H 10 -H 16 -H 17 -H 18 bsp_key.c File: bsp_key.c    #include <stdbool.h>    #include <stdint.h>    enum key_event { KEY_NONE, KEY_PRESS, KEY_RELEASE };    struct key_filter { bool candidate, stable; uint32_t since; };    enum key_event key_poll(struct key_filter *f, uint32_t now_ms)    {        volatile const uint32_t *psr =            (volatile const uint32_t *)(uintptr_t)0x0209c008U;      bool pressed = (*psr & (UINT32_C(1) << 18)) == 0U;        if (pressed != f->candidate) {            f->candidate = pressed;            f->since = now_ms;            return KEY_NONE;        }        if (f->candidate != f->stable &&            (uint32_t)(now_ms - f->since) >= 10U) {          f->stable = f->candidate;            return f->stable ? KEY_PRESS : KEY_RELEASE;        }        return KEY_NONE;    }    /* Initialize candidate and stable from a known startup policy before polling. */
  1. Sample GPIO1_PSR at 0x0209C008 (+0x08, never DR at +0x00!) and normalize active-low bit 18 (0V -> pressed = true).
  2. Subtract (uint32_t)(now_ms - f->since) >= 10U and update f->stable once so held keys emit zero duplicate events.

Proving End-to-End Capstone Integration & Wraparound Safety in C11

debounce_fsm_capstone.c wires together every concept from GL-E01 into one deterministic host testbench: psr_key_pressed() normalizes GPIO1_PSR[18], debounce_step() filters press chatter (t = 1, 3, 4 -> EV_PRESS @ 14), suppresses steady holds (t = 19 -> EV_NONE), filters release chatter (t = 20, 25, 26 -> EV_RELEASE @ 36), accepts a second press (t = 37 -> EV_PRESS @ 47), and proves UINT32_MAX - 5U -> 4U wraparound, while bsp_poll_cycle() toggles active-low LED0 (GPIO1_DR bit 3) and PNP buzzer (GPIO5_DR bit 1) without disturbing any of the 31 sibling bits in 0xA5A5A5AD or 0x5A5A5A57!

learner@ksa: ~/gl-e01/m06-l03
learner@ksa:~/gl-e01/m06-l03$ bat -H 10 -H 11 -H 12 -H 13 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 -H 36 -H 37 debounce_fsm_capstone.c File: debounce_fsm_capstone.c    #include <assert.h>    #include <stdbool.h>    #include <stdint.h>    #include <stdio.h>        enum key_ev { EV_NONE = 0, EV_PRESS = 1, EV_RELEASE = 2 };    struct deb_fsm { bool candidate, stable; uint32_t since_ms; };        static bool psr_key_pressed(uint32_t gpio1_psr)    {        return (gpio1_psr & (UINT32_C(1) << 18)) == 0U;  }        static enum key_ev debounce_step(struct deb_fsm *f, bool pressed, uint32_t now)    {        if (pressed != f->candidate) {            f->candidate = pressed;            f->since_ms = now;            return EV_NONE;        }      if (f->candidate != f->stable && (uint32_t)(now - f->since_ms) >= 10U) {            f->stable = f->candidate;            return f->stable ? EV_PRESS : EV_RELEASE;        }        return EV_NONE;    }        static enum key_ev bsp_poll_cycle(struct deb_fsm *f, uint32_t psr, uint32_t now,                                      bool *alarm_on, uint32_t *gpio1_dr, uint32_t *gpio5_dr)    {        enum key_ev ev = debounce_step(f, psr_key_pressed(psr), now);      if (ev == EV_PRESS) *alarm_on = !*alarm_on;        *gpio1_dr = *alarm_on ? (*gpio1_dr & ~8U) : (*gpio1_dr | 8U);        *gpio5_dr = *alarm_on ? (*gpio5_dr & ~2U) : (*gpio5_dr | 2U);        return ev;    }        int main(void)    {        const uint32_t HI = UINT32_C(1) << 18, LO = 0U;        struct deb_fsm f = {false, false, 0U};        bool alarm = false;        uint32_t dr1 = 0xa5a5a5adU, dr5 = 0x5a5a5a57U;            assert(bsp_poll_cycle(&f, LO, 1U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, HI, 3U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, LO, 4U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, LO, 13U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, LO, 14U, &alarm, &dr1, &dr5) == EV_PRESS && alarm);        assert((dr1 & 8U) == 0U && (dr5 & 2U) == 0U && (dr1 & ~8U) == 0xa5a5a5a5U);        assert(bsp_poll_cycle(&f, LO, 19U, &alarm, &dr1, &dr5) == EV_NONE && alarm);        assert(bsp_poll_cycle(&f, HI, 20U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, LO, 25U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, HI, 26U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, HI, 36U, &alarm, &dr1, &dr5) == EV_RELEASE && alarm);        assert(bsp_poll_cycle(&f, LO, 37U, &alarm, &dr1, &dr5) == EV_NONE);        assert(bsp_poll_cycle(&f, LO, 47U, &alarm, &dr1, &dr5) == EV_PRESS && !alarm);            struct deb_fsm w = {false, false, 0U};        assert(debounce_step(&w, true, UINT32_MAX - 5U) == EV_NONE);        assert(debounce_step(&w, true, UINT32_MAX - 1U) == EV_NONE);        assert(debounce_step(&w, true, 3U) == EV_NONE);        assert(debounce_step(&w, true, 4U) == EV_PRESS);        printf("press@14 release@36 press@47 wrap@4 dr1_off=0x%08X dr5_off=0x%08X\n",               dr1, dr5);        return 0;    }
  1. Normalize active-low GPIO1_PSR bit 18 ((psr & (1U << 18)) == 0U) into logical pressed.
  2. Use unsigned subtraction (uint32_t)(now - f->since) >= 10U so 32-bit tick wrap across UINT32_MAX never triggers early.
  3. Toggle logical alarm state once per EV_PRESS and update active-low GPIO1_DR/GPIO5_DR while preserving sibling bits.

Running the Capstone Verifier & Freestanding Cortex-A7 Object Check

Compile and execute debounce_fsm_capstone.c on the workstation, then cross-compile bsp_key.c for freestanding ARMv7-A (target.o) under -Werror.

learner@ksa: ~/gl-e01/m06-l03
learner@ksa:~/gl-e01/m06-l03gcc -std=c11 -Wall -Wextra -Werror -pedantic debounce_fsm_capstone.c -o debounce_fsm_capstonelearner@ksa:~/gl-e01/m06-l03./debounce_fsm_capstonepress@14 release@36 press@47 wrap@4 dr1_off=0xA5A5A5AD dr5_off=0x5A5A5A57learner@ksa:~/gl-e01/m06-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c bsp_key.c -o target.olearner@ksa:~/gl-e01/m06-l03
strace — learner@ksa: ~/gl-e01/m06-l03
learner@ksa:~/gl-e01/m06-l03strace -e trace=write,exit_group \./debounce_fsm_capstonewrite(1, "press@14 release@36 press@47 wra"..., 74) = 74exit_group(0)                           = ?+++ exited with 0 +++

Where You Stand Now & Bridging Forward to GL-E02

Step back and appreciate the full bare-metal stack you now own from first principles: ARMv7-A AAPCS / CPSR modes (m01–m02), CCM gates, IOMUXC pad cells, and GPIO DR/GDIR/PSR/W1C ISR silicon (m03), POR_B boot straps, OCRAM, IVT/Boot Data coordinates, and big-endian DCD .imx packing (m04), start.S, bsp.lds VMA/LMA relocation, and _Static_assert MMIO structs (m05), and now a modular -MMD -MP BSP coordinating transistor actuators and wraparound-safe debounced inputs (m06)! Later: Course GL-E02 (imx6ull-baremetal-peripherals) supplies hardware now_ms ticks from EPIT/GPT timers, retunes ARM PLL1 to 528 MHz, routes GICv2 interrupts, trains external DDR3 (MMDC), and drives UART1, LCD, I2C, and SPI peripherals on bare silicon.

Common Production Pitfalls

warning: Symptom: After ~49.7 days of continuous 1 ms uptime (or whenever unit tests seed now_ms near 0xFFFFFFFA), tactile button bounces trigger immediate false KEY_PRESS events on the very first microsecond of contact chatter! Root Cause: Elapsed time was written if (now_ms >= f->since + 10U), allowing f->since + 10U to wrap modulo 2^32 to a small integer (4U) that 0xFFFFFFFB immediately exceeds! Fix: Always compute elapsed ticks via unsigned subtraction (uint32_t)(now_ms - f->since) >= 10U.

warning: Symptom: Configuring GPIO1_IO18 as an input (GDIR[18] = 0) and polling *gpio1_dr & (1U << 18) never detects a button press even when a multimeter measures 0 V right on the SoC ball. Root Cause: GPIOx_DR (+0x00) reads back the internal output data latch, whereas external pin voltage on an input pad is sampled through GPIOx_PSR (+0x08) (and requires IOMUXC pull-up biasing so the open switch cannot float). Fix: Read inputs strictly from GPIOx_PSR (+0x08) after configuring the ALT5 mux, pull-up network, and GDIR bit 0.

Practice & Retrieval

Guided Practice: Hand-Tracing Release Chatter & Modulo Subtraction

Trace debounce_step() starting from accepted pressed state {candidate = true, stable = true, since_ms = 14}. Step 1 (Chatter Reset): Poll (false, 50) -> candidate = false, since_ms = 50; bounce (true, 56) -> candidate = true, since_ms = 56; settle (false, 58) -> candidate = false, since_ms = 58; at t = 67 (67 - 58 = 9 < 10) -> EV_NONE; at t = 68 (68 - 58 == 10) -> EV_RELEASE. Step 2 (Wrap Check): Evaluate (uint32_t)(2U - 0xFFFFFFF9U) -> 2 + 7 = 9U (< 10U).

Independent Practice: Short-Tap vs 500 ms Long-Hold BSP Controller

Extend debounce_fsm_capstone.c into key_short_long_bsp.c adding EV_LONG_HOLD (emitted once per press when stable == true persists for (uint32_t)(now - accepted_at) >= 500U) and EV_TAP_RELEASE (emitted on EV_RELEASE only if EV_LONG_HOLD did not fire during that press), wiring taps to toggle LED0 (GPIO1_IO03) and long holds to assert the PNP buzzer (GPIO5_IO01).

quiz · 1 of 3

In debounce_step(), a bouncing switch finally stays low starting at now = 4 (f->candidate = true, f->since_ms = 4) with threshold 10U. What does debounce_step() return when polled with pressed = true at now = 13?

quiz · 2 of 3

After EV_PRESS fires at now = 14, the user keeps holding the tactile switch down at now = 19, 20, 25.... Why does key_poll() emit zero additional KEY_PRESS events while held?

quiz · 3 of 3

Retrieval: which GPIO1 register (base 0x0209C000) must bsp_key.c read to observe the external tactile switch on GPIO1_IO18?

Lab 6: Wraparound-Safe 10 ms Key Debounce FSM & Active-Low BSP Output Integration

env: host

1. Motivation

A bare-metal tactile-button and buzzer BSP appears to work during a two-minute bench demo yet misfires in continuous operation for two classic reasons: mechanical switch contacts chatter between 0 V and 3.3 V for 1 - 5 ms on every press and release (toggling an un-debounced alarm multiple times per finger tap), and deadline comparisons written as now >= f->since + 10U overflow 32-bit millisecond ticks whenever f->since lands within 9 ticks of UINT32_MAX (49.71 days at 1 kHz or 71.58 minutes at 1 MHz), firing PRESS prematurely! In this capstone laboratory, you will repair sample_key() in starter/core.c and verify end-to-end bounce rejection, hold suppression, 32-bit counter wraparound, and sibling-safe active-low GPIO output control under TAP version 13.

2. Learning Objectives

  1. Reject sub-10-tick mechanical contact bounce on both press and release transitions by resetting f->candidate and f->since whenever pressed != f->candidate.
  2. Suppress repeated PRESS events while a button remains held (f->candidate == f->stable) and require a full 10-tick RELEASE qualification before accepting the next press.
  3. Repair 32-bit monotonic tick elapsed-time comparison using unsigned modular subtraction ((uint32_t)(now - f->since) >= 10U) across UINT32_MAX -> 0.
  4. Integrate sample_key() and output_write() inside bsp_step() so accepted PRESS events toggle active-low bit 1 (mask = 2U) without disturbing bits [31:2] or bit 0.

3. Environment Requirements

  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) inside labs/lab_m06_modular_bsp_io/.
  • Target Hardware Alignment: Models active-low KEY0 input normalized from GPIO1_PSR[18] (0x0209C008), monotonic 32-bit timer ticks (EPIT/GPT), and active-low PNP buzzer output on GPIO5_DR[1] (0x020AC000).

4. Required Software & Hardware

  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, objdump).
  • Hardware: Standard Linux workstation (0 physical switches, buzzers, or Cortex-A7 boards required for the 5-check TAP grader).

5. Complete Executable Commands

Execute the commands below from labs/lab_m06_modular_bsp_io/ to reproduce starter/ failing check 4 (tick wrap), inspect the exact premature PRESS at UINT32_MAX - 1U, build files/libbsp.a, and pass all 5 TAP checks:

learner@ksa: ~/gl-e01/m06-l03
learner@ksa:~/gl-e01/m06-l03$ bat script.sh File: script.sh    # 1. Stage starter/ in a temporary directory and run check.sh to observe check 4 fail (# pass 4/5)    TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP"        # 2. Trace starter/'s sample_key() across UINT32_MAX - 5 -> UINT32_MAX - 1 -> 3 -> 4    TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter -x c - starter/core.c -o "$TMP/wrap" <<'EOF' && "$TMP/wrap" ; rm -rf "$TMP"    #include "core.h"    #include <stdio.h>    int main(void) {        struct filter f = {false, false, 0U};        uint32_t t0 = UINT32_MAX - 5U, t1 = UINT32_MAX - 1U;        printf("t0=0x%08X -> ev=%d (since+10 wraps to 0x%08X)\n", t0, sample_key(&f, true, t0), f.since + 10U);        printf("t1=0x%08X (only 4 ticks later!) -> starter ev=%d (expected 0=NONE)\n", t1, sample_key(&f, true, t1));        return 0;    }    EOF        # 3. Compile the repaired archive files/libbsp.a and list exported symbols    make -B -C files    nm -g --defined-only files/libbsp.a        # 4. Run the authoritative 5-check TAP version 13 harness    sh check.sh

*Why each step runs:* Step 1 runs check.sh against starter/ safely inside $TMP; Step 2 prints the exact wrapped deadline 0x00000004 (0xFFFFFFFA + 10) that causes starter to emit ev = 1 (PRESS) at 0xFFFFFFFE after just 4 ticks; Step 3 builds files/libbsp.a; and Step 4 confirms # pass 5/5.

6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)

  • Candidate Reset & Edge Gate (core.c:3-12): Whenever pressed != f->candidate, sample_key() sets f->candidate = pressed; f->since = now; and returns NONE immediately. In tests.c case 1, chatter at now = 1 (true) -> 3 (false) -> 4 (true) resets f->since to 4U, so now = 13U (elapsed = 9U) still returns NONE and now = 14U (elapsed = 10U) emits PRESS.
  • Seeded Flaw in starter/core.c:8 (sample_key): starter tests f->candidate != f->stable && now >= f->since + 10U. When f->since = UINT32_MAX - 5U (0xFFFFFFFAU) in tests.c case 3, f->since + 10U wraps modulo 2^32 to 4U, making now >= 4U immediately true at now = UINT32_MAX - 1U (0xFFFFFFFEU, only 4 ticks elapsed!).
  • Verified Repair in files/core.c:8: Evaluates (uint32_t)(now - f->since) >= 10U. Across the wrap boundary (since = 0xFFFFFFFAU), now = 0xFFFFFFFEU gives elapsed = 4U < 10U (NONE), now = 3U gives (uint32_t)(3U - 0xFFFFFFFAU) == 9U < 10U (NONE), and now = 4U gives 10U >= 10U (PRESS), after which f->stable = true suppresses now = 5U (NONE).
  • output_write & bsp_step (core.c:13-25): bsp_step() toggles *enabled = !*enabled strictly when event == PRESS (RELEASE leaves *enabled unchanged in tests.c:36), then calls output_write(dr, 1U, *enabled, true) to clear bit 1 (0U) when enabled and set bit 1 (2U) when disabled while preserving siblings = dr & ~2U.

7. Expected TAP-13 Output

learner@ksa: ~/gl-e01/m06-l03
learner@ksa:~/gl-e01/m06-l03$ bat listing.txt File: listing.txt    # Unmodified starter/ baseline (exits non-zero: # pass 4/5)    TAP version 13    1..5    ok 1 - strict C11 build and trusted grader link    ok 2 - rejects a bouncing press until the full stable interval    ok 3 - suppresses held repeats and accepts release before the next press    not ok 4 - handles tick wrap and threshold boundaries without deadline overflow      ---      message: 'Behavior differs from the independently specified test vectors'      hint: 'Repair case 3; inspect tests.c for the exact input and expected result'      ...    ok 5 - integrates two accepted presses with sibling-safe active-low output updates    # pass 4/5        # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5)    TAP version 13    1..5    ok 1 - strict C11 build and trusted grader link    ok 2 - rejects a bouncing press until the full stable interval    ok 3 - suppresses held repeats and accepts release before the next press    ok 4 - handles tick wrap and threshold boundaries without deadline overflow    ok 5 - integrates two accepted presses with sibling-safe active-low output updates    # pass 5/5

8. Explanation of Observed Behavior

Notice how insidious starter/core.c is during ordinary testing: checks 2, 3, and 5 (tests.c cases 1, 2, and 4) all use small startup timestamps (1..122), where f->since + 10U never wraps, so starter/ passes 4/5 checks without warning! Only check 4 (tests.c case 3), which seeds now = UINT32_MAX - 5U, exposes the modular deadline overflow at tests.c:25 (assert(sample_key(&f, true, UINT32_MAX - 1U) == NONE)). Switching to subtraction (uint32_t)(now - f->since) >= 10U makes the FSM invariant under arbitrary 32-bit starting phases (# pass 5/5).

9. Experiment Variations

  1. Toggle on Both Edges Bug (bsp_step): Change if (event == PRESS) to if (event != NONE) in a scratch copy and run verify 4: *enabled turns on at t = 11 (PRESS) and immediately turns off upon finger lift at t = 31 (RELEASE), converting a latching toggle button into a momentary dead-man switch (tests.c:36 aborts).
  2. Off-By-One Threshold (> 10U vs >= 10U): Change >= 10U to > 10U in sample_key(): tests.c case 1 (since = 4U, now = 14U), case 2 (1 -> 11), case 3 (UINT32_MAX - 5U -> 4U), and case 4 (1 -> 11) all fail because 10 elapsed ticks require an 11th tick to fire.
  3. Held-At-Boot Policy Check: Initialize struct filter f = {true, true, 0U}; when GPIO1_PSR[18] reads 0 at reset and verify a button already held across power-on emits zero spurious PRESS events until released and pressed anew.

10. Performance Measurements

Benchmarked on Linux 7.0.0-42-generic (x86_64) via CLOCK_MONOTONIC (5 warmup runs, 35 timed samples):

Workload Measured (N = 35, warmup = 5)Host p50Host p95Host p99Cortex-A7 @ 528 MHz Superloop Impact
Full sh check.sh (make -B + gcc link + 4 cases)143.97 ms169.45 ms170.52 msHost compile + link + process launch
verify 4-case capstone FSM suite (verify 1..4)3668.5 us4674.6 us4923.4 us< 2 us for all 26 sample_key/bsp_step transitions
Nonblocking bsp_step() vs 10 ms busy-wait delay~3 ns / poll~4 ns / poll~5 ns / pollSaves 5,280,000 stalled CPU cycles (10 ms) per bounce!

11. Troubleshooting

SymptomRoot CauseFix
not ok 4 (sample_key fires PRESS at UINT32_MAX - 1U)Deadline addition f->since + 10U wraps modulo 2^32 to 4UCompare elapsed ticks via (uint32_t)(now - f->since) >= 10U
not ok 2 (bounce glitch at t = 3 still fires PRESS at t = 11)Updated f->since only when pressed == true instead of every pressed != f->candidateReset f->candidate = pressed; f->since = now; on any mismatch
not ok 3 (holding button at t = 100 emits second PRESS)Checked (now - f->since) >= 10U without f->candidate != f->stableGate qualification on f->candidate != f->stable and set f->stable = f->candidate
not ok 5 (GPIO sibling bits [31:2] or bit 0 overwritten)bsp_step wrote *dr = *enabled ? 0U : 2U instead of calling output_writeMask single bit 1U via output_write(dr, 1U, *enabled, true)

12. Guided Questions

  1. Under what maximum polling-gap constraint is (uint32_t)(now - f->since) >= 10U guaranteed free of wraparound ambiguity on a 1 kHz (1 ms) uint32_t tick counter?
  • *Hint 1:* Compute the full period 2^32 ms in days (4,294,967,296 ms / 86,400,000 ms/day ~= 49.71 days).
  • *Hint 2:* What happens if the superloop stalls for 2^32 + 2 ms while f->candidate != f->stable so (uint32_t)(now - f->since) aliases back to 2U < 10U?
  1. Why does bsp_step() call output_write(dr, 1U, *enabled, true) unconditionally or on state change rather than blocking inside sample_key() for 10 ms?
  • *Hint 1:* Count how many independent peripherals (UART RX FIFO, LED heartbeat, watchdog service, multiple buttons) share a bare-metal cooperative superloop.
  • *Hint 2:* If UART1 receives bytes at 115200 baud (~86.8 us per byte, 32-byte hardware RX FIFO = 2.78 ms to overflow), what happens to incoming serial frames during a 10 ms blocking delay_ms(10) debounce?

13. Independent Challenges

  1. Near Transfer — Asymmetric Press/Release Thresholds & Long-Press Event (LONG_PRESS): Extend enum event with LONG_PRESS (>= 1000 ticks continuous hold after PRESS, emitted at most once per hold via bool long_sent in struct filter) while keeping 10-tick press and 15-tick release qualification wraparound-safe.
  2. Far Transfer — 8-Button Bit-Parallel Vertical Counter Debouncer: Design uint8_t debounce_port8(struct port_deb *d, uint8_t raw_active_low, uint32_t now) that debounces 8 simultaneous GPIO keypad inputs using 2-bit vertical saturating counters sampled every 5 ms (3 consecutive matching samples = 10 - 15 ms qualification) with zero per-pin branches.

14. Solutions & Explanations

  • Guided Question 1: Unsigned subtraction now - since measures exact elapsed ticks modulo 2^32 provided consecutive polls while candidate != stable occur within < 2^32 - 10 ticks (~49.71 days at 1 kHz), so polling every 1 - 5 ms has 9 orders of magnitude safety margin.
  • Guided Question 2: At 115200 8N1 (11,520 bytes/s), 10 ms delivers 115 bytes -- overflowing a 32-byte UART FIFO 3.6x over! Nonblocking state-machine polling finishes in nanoseconds so UART, timers, and other keys stay responsive every millisecond.
  • Challenge 1 Guard: After f->candidate == f->stable && f->stable && !f->long_sent, check (uint32_t)(now - f->since) >= 1000U, set f->long_sent = true, and return LONG_PRESS; clear f->long_sent = false whenever f->stable transitions to false (RELEASE).

Run locally in your terminal and check off each verification milestone.

Not started

Key takeaways

  • Mechanical switch contacts bounce repeatedly across 1..5 ms on both press and release; IOMUXC hysteresis (HYS = 1) cleans slow edges while a software debounce FSM filters millisecond chatter.
  • Tracking (candidate, stable, since_ms) in an O(1) nonblocking poll function qualifies transitions without starving sibling BSP work inside delay_ms() spin loops.
  • Unsigned subtraction (uint32_t)(now_ms - since_ms) >= threshold computes exact elapsed ticks across UINT32_MAX -> 0 wraparound (~49.7 days at 1 kHz), avoiding the since + threshold overflow bug.
  • Sampling GPIO1_PSR (+0x08) and dispatching single-edge EV_PRESS transitions into polarity-aware GPIO1_DR/GPIO5_DR helpers completes an auditable, modular bare-metal BSP.
  • Mechanical contacts can create multiple electrical transitions during one physical press or release.
  • A debouncer can track candidate state, candidate-start time, and accepted stable state separately.
  • PSR, with the selected active-low bit normalized into pressed.
Progress is saved on this device.
up next · module 6 labLab: Wraparound-Safe 10 ms Key Debounce FSM & Active-Low BSP Output Integration (30 min)
→ module 6 lab

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure