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.
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):
- Read
GPIO1_PSR(+0x08), neverGPIO1_DR(+0x00): On inputUART1_CTS_B(ALT5->GPIO1_IO18, pulled to3.3 Vidle and switched toGNDwhen pressed),PSRsamples the live external pad (pressed = (*psr & (1U << 18)) == 0U), whereasDRholds the unused output latch! - Qualify continuous stability (
t = 1..48 msin Figure 6.3a): Raw chatter att = 1, 3, 4keeps resettingsince_ms = 4; att = 13(13 - 4 = 9 < 10), no event fires; att = 14(14 - 4 == 10),stablecommitstrueand oneEV_PRESSfires (turningalarm_on = true)! Holding att = 19seescandidate == stable(EV_NONE); release chatter att = 20, 25, 26settles att = 36(EV_RELEASE, re-arming the button without toggling the alarm); and a second press att = 37firesEV_PRESSatt = 47(togglingalarm_on = false)!
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:
- Step 1. Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.
- Step 2. Step 2: On any pressed != candidate edge or bounce, update candidate and reset since_ms = now_ms.
- Step 3. Step 3: Once candidate != stable and (uint32_t)(now_ms - since_ms) >= 10U, commit stable and emit 1 event.
- 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 + 10Uoverflows32bits and wraps to0x00000004! Just1 mslater (now = 0xFFFFFFFB),0xFFFFFFFB >= 0x00000004evaluatestrueimmediately—passing raw contact bounce straight into your application! - Why
if ((uint32_t)(now - since) >= 10U)is exact: Atnow = 0xFFFFFFFE,0xFFFFFFFE - 0xFFFFFFFA == 4U(< 10U); after wrap atnow = 0x00000003,(3U - 0xFFFFFFFAU) == 9U(< 10U); and atnow = 0x00000004,(4U - 0xFFFFFFFAU) == 10U(>= 10U, firing after the exact10-tick physical interval)!
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 Implementation | Super-Loop CPU Cost | Bounce & UINT32_MAX Behavior | Engineering Verdict |
|---|---|---|---|
Blocking if (!psr) { delay_ms(10); ... } | Burns 5.28M cycles @ 528 MHz | Starves UART/sensors; re-fires while held! | Broken beyond toy demos |
Deadline now >= since + 10U | O(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) >= 10U | O(1) nonblocking (< 30 cycles) | Exact across UINT32_MAX; debounces press & release | Production bare-metal standard |
Reading GPIO1_DR (+0x00) instead of PSR | O(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$ 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. */- Sample GPIO1_PSR at 0x0209C008 (+0x08, never DR at +0x00!) and normalize active-low bit 18 (0V -> pressed = true).
- 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$ 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; }- Normalize active-low GPIO1_PSR bit 18 ((psr & (1U << 18)) == 0U) into logical pressed.
- Use unsigned subtraction (uint32_t)(now - f->since) >= 10U so 32-bit tick wrap across UINT32_MAX never triggers early.
- 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-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-l03learner@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).
→ open standalone lab workbench
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
- Reject sub-
10-tick mechanical contact bounce on both press and release transitions by resettingf->candidateandf->sincewheneverpressed != f->candidate. - Suppress repeated
PRESSevents while a button remains held (f->candidate == f->stable) and require a full10-tickRELEASEqualification before accepting the next press. - Repair
32-bit monotonic tick elapsed-time comparison using unsigned modular subtraction ((uint32_t)(now - f->since) >= 10U) acrossUINT32_MAX -> 0. - Integrate
sample_key()andoutput_write()insidebsp_step()so acceptedPRESSevents toggle active-low bit1(mask = 2U) without disturbing bits[31:2]or bit0.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m06_modular_bsp_io/. - Target Hardware Alignment: Models active-low
KEY0input normalized fromGPIO1_PSR[18](0x0209C008), monotonic32-bit timer ticks (EPIT/GPT), and active-lowPNPbuzzer output onGPIO5_DR[1](0x020AC000).
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0physical switches, buzzers, orCortex-A7boards required for the 5-checkTAPgrader).
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$ 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): Wheneverpressed != f->candidate,sample_key()setsf->candidate = pressed; f->since = now;and returnsNONEimmediately. Intests.ccase1, chatter atnow = 1 (true) -> 3 (false) -> 4 (true)resetsf->sinceto4U, sonow = 13U(elapsed = 9U) still returnsNONEandnow = 14U(elapsed = 10U) emitsPRESS. - Seeded Flaw in
starter/core.c:8(sample_key):startertestsf->candidate != f->stable && now >= f->since + 10U. Whenf->since = UINT32_MAX - 5U(0xFFFFFFFAU) intests.ccase3,f->since + 10Uwraps modulo2^32to4U, makingnow >= 4Uimmediatelytrueatnow = UINT32_MAX - 1U(0xFFFFFFFEU, only4ticks elapsed!). - Verified Repair in
files/core.c:8: Evaluates(uint32_t)(now - f->since) >= 10U. Across the wrap boundary (since = 0xFFFFFFFAU),now = 0xFFFFFFFEUgiveselapsed = 4U < 10U(NONE),now = 3Ugives(uint32_t)(3U - 0xFFFFFFFAU) == 9U < 10U(NONE), andnow = 4Ugives10U >= 10U(PRESS), after whichf->stable = truesuppressesnow = 5U(NONE). output_write&bsp_step(core.c:13-25):bsp_step()toggles*enabled = !*enabledstrictly whenevent == PRESS(RELEASEleaves*enabledunchanged intests.c:36), then callsoutput_write(dr, 1U, *enabled, true)to clear bit1(0U) when enabled and set bit1(2U) when disabled while preservingsiblings = dr & ~2U.
7. Expected TAP-13 Output
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/58. 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
- Toggle on Both Edges Bug (
bsp_step): Changeif (event == PRESS)toif (event != NONE)in a scratch copy and runverify 4:*enabledturns on att = 11(PRESS) and immediately turns off upon finger lift att = 31(RELEASE), converting a latching toggle button into a momentary dead-man switch (tests.c:36aborts). - Off-By-One Threshold (
> 10Uvs>= 10U): Change>= 10Uto> 10Uinsample_key():tests.ccase1(since = 4U, now = 14U), case2(1 -> 11), case3(UINT32_MAX - 5U -> 4U), and case4(1 -> 11) all fail because10elapsed ticks require an11thtick to fire. - Held-At-Boot Policy Check: Initialize
struct filter f = {true, true, 0U};whenGPIO1_PSR[18]reads0at reset and verify a button already held across power-on emits zero spuriousPRESSevents 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 p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Superloop Impact |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 143.97 ms | 169.45 ms | 170.52 ms | Host compile + link + process launch |
verify 4-case capstone FSM suite (verify 1..4) | 3668.5 us | 4674.6 us | 4923.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 / poll | Saves 5,280,000 stalled CPU cycles (10 ms) per bounce! |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
not ok 4 (sample_key fires PRESS at UINT32_MAX - 1U) | Deadline addition f->since + 10U wraps modulo 2^32 to 4U | Compare 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->candidate | Reset 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->stable | Gate 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_write | Mask single bit 1U via output_write(dr, 1U, *enabled, true) |
12. Guided Questions
- Under what maximum polling-gap constraint is
(uint32_t)(now - f->since) >= 10Uguaranteed free of wraparound ambiguity on a1 kHz(1 ms)uint32_ttick counter?
- *Hint 1:* Compute the full period
2^32 msin 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 mswhilef->candidate != f->stableso(uint32_t)(now - f->since)aliases back to2U < 10U?
- Why does
bsp_step()calloutput_write(dr, 1U, *enabled, true)unconditionally or on state change rather than blocking insidesample_key()for10 ms?
- *Hint 1:* Count how many independent peripherals (
UARTRX FIFO,LEDheartbeat, watchdog service, multiple buttons) share a bare-metal cooperative superloop. - *Hint 2:* If
UART1receives bytes at115200baud (~86.8 usper byte,32-byte hardware RX FIFO =2.78 msto overflow), what happens to incoming serial frames during a10 msblockingdelay_ms(10)debounce?
13. Independent Challenges
- Near Transfer — Asymmetric Press/Release Thresholds & Long-Press Event (
LONG_PRESS): Extendenum eventwithLONG_PRESS(>= 1000ticks continuous hold afterPRESS, emitted at most once per hold viabool long_sentinstruct filter) while keeping10-tick press and15-tick release qualification wraparound-safe. - 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 debounces8simultaneousGPIOkeypad inputs using2-bit vertical saturating counters sampled every5 ms(3consecutive matching samples =10 - 15 msqualification) with zero per-pin branches.
14. Solutions & Explanations
- Guided Question 1: Unsigned subtraction
now - sincemeasures exact elapsed ticks modulo2^32provided consecutive polls whilecandidate != stableoccur within< 2^32 - 10ticks (~49.71 daysat1 kHz), so polling every1 - 5 mshas9orders of magnitude safety margin. - Guided Question 2: At
115200 8N1(11,520bytes/s),10 msdelivers115bytes -- overflowing a32-byteUARTFIFO3.6xover! Nonblocking state-machine polling finishes in nanoseconds soUART, 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, setf->long_sent = true, and returnLONG_PRESS; clearf->long_sent = falsewheneverf->stabletransitions tofalse(RELEASE).
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
- Mechanical switch contacts bounce repeatedly across
1..5 mson both press and release;IOMUXChysteresis (HYS = 1) cleans slow edges while a software debounce FSM filters millisecond chatter. - Tracking
(candidate, stable, since_ms)in anO(1)nonblocking poll function qualifies transitions without starving siblingBSPwork insidedelay_ms()spin loops. - Unsigned subtraction
(uint32_t)(now_ms - since_ms) >= thresholdcomputes exact elapsed ticks acrossUINT32_MAX -> 0wraparound (~49.7days at1 kHz), avoiding thesince + thresholdoverflow bug. - Sampling
GPIO1_PSR(+0x08) and dispatching single-edgeEV_PRESStransitions into polarity-awareGPIO1_DR/GPIO5_DRhelpers completes an auditable, modular bare-metalBSP. - 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.