Lab 6: Wraparound-Safe 10 ms Key Debounce FSM & Active-Low BSP Output Integration
Implement, compile, and verify lab_m06_modular_bsp_io against ./check.sh.
Prerequisites in this module
What ./check.sh verifies
- Strict C11 build and trusted grader link.
- Repair the C11 build before testing behavior.
- Rejects a bouncing press until the full stable interval.
- Suppresses held repeats and accepts release before the next press.
step 1/15 · inspect starter files and specification
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.
learner@ksa:~/gl-e01/lab-m06ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m06starter: starter/Makefile
learner@ksa:~/gl-e01/lab-m06$ bat starter/Makefile File: starter/Makefile CC = gcc AR = ar override CFLAGS += -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP all: libbsp.a bsp_demo libbsp.a: core.o $(AR) rcs $@ $^ bsp_demo: main.o libbsp.a $(CC) $(CFLAGS) main.o libbsp.a -o $@ %.o: %.c core.h $(CC) $(CFLAGS) -c $< -o $@ -include core.d main.d .PHONY: all clean clean: rm -f core.o main.o core.d main.d libbsp.a bsp_demostarter: starter/core.c
learner@ksa:~/gl-e01/lab-m06$ bat starter/core.c File: starter/core.c #include "core.h" #include <stddef.h> enum event sample_key(struct filter *f,bool pressed,uint32_t now) { if (pressed!=f->candidate) { f->candidate=pressed; f->since=now; return NONE; } if (f->candidate!=f->stable && now>=f->since+10U) { f->stable=f->candidate; return f->stable?PRESS:RELEASE; } return NONE; } bool output_write(uint32_t *dr,unsigned pin,bool asserted,bool active_low) { if (dr==NULL || pin>=32U) return false; uint32_t mask=UINT32_C(1)<<pin; *dr=(asserted!=active_low)?*dr|mask:*dr&~mask; return true; } enum event bsp_step(struct filter *f,bool pressed,uint32_t now,bool *enabled,uint32_t *dr) { enum event event=sample_key(f,pressed,now); if (event==PRESS) *enabled=!*enabled; (void)output_write(dr,1U,*enabled,true); return event; }starter: starter/core.h
learner@ksa:~/gl-e01/lab-m06$ bat starter/core.h File: starter/core.h #ifndef GL_E01_CORE_H #define GL_E01_CORE_H #include <stdbool.h> #include <stdint.h> enum event { NONE, PRESS, RELEASE }; struct filter { bool candidate,stable; uint32_t since; }; enum event sample_key(struct filter *f,bool pressed,uint32_t now); bool output_write(uint32_t *dr,unsigned pin,bool asserted,bool active_low); enum event bsp_step(struct filter *f,bool pressed,uint32_t now,bool *enabled,uint32_t *dr); #endifstarter: starter/main.c
learner@ksa:~/gl-e01/lab-m06$ bat starter/main.c File: starter/main.c #include "core.h" #include <stdio.h> int main(void) { puts("GL-E01 BSP laboratory: run ../check.sh for graded evidence"); return 0; }step 2/15 · 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.
step 3/15 · 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).
step 4/15 · 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).
step 5/15 · 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/lab-m06$ 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.
step 6/15 · 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.
step 7/15 · 7. expected tap-13 output
learner@ksa:~/gl-e01/lab-m06$ 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/5step 8/15 · 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).
step 9/15 · 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.
step 10/15 · 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! |
step 11/15 · 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) |
step 12/15 · 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?
step 13/15 · 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.
step 14/15 · 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).
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-e01/lab-m06./check.shlearner@ksa:~/gl-e01/lab-m06TAP version 131..5ok 1 - strict C11 build and trusted grader linkProgressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Strict C11 build and trusted grader link.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-e01/lab-m06$ bat files/Makefile File: files/Makefile CC = gcc AR = ar override CFLAGS += -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP all: libbsp.a bsp_demo libbsp.a: core.o $(AR) rcs $@ $^ bsp_demo: main.o libbsp.a $(CC) $(CFLAGS) main.o libbsp.a -o $@ %.o: %.c core.h $(CC) $(CFLAGS) -c $< -o $@ -include core.d main.d .PHONY: all clean clean: rm -f core.o main.o core.d main.d libbsp.a bsp_demosolution: files/core.c
learner@ksa:~/gl-e01/lab-m06$ bat files/core.c File: files/core.c #include "core.h" #include <stddef.h> enum event sample_key(struct filter *f,bool pressed,uint32_t now) { if (pressed!=f->candidate) { f->candidate=pressed; f->since=now; return NONE; } if (f->candidate!=f->stable && (uint32_t)(now-f->since)>=10U) { f->stable=f->candidate; return f->stable?PRESS:RELEASE; } return NONE; } bool output_write(uint32_t *dr,unsigned pin,bool asserted,bool active_low) { if (dr==NULL || pin>=32U) return false; uint32_t mask=UINT32_C(1)<<pin; *dr=(asserted!=active_low)?*dr|mask:*dr&~mask; return true; } enum event bsp_step(struct filter *f,bool pressed,uint32_t now,bool *enabled,uint32_t *dr) { enum event event=sample_key(f,pressed,now); if (event==PRESS) *enabled=!*enabled; (void)output_write(dr,1U,*enabled,true); return event; }solution: files/core.d
learner@ksa:~/gl-e01/lab-m06$ bat files/core.d File: files/core.d core.o: core.c core.h core.h:solution: files/core.h
learner@ksa:~/gl-e01/lab-m06$ bat files/core.h File: files/core.h #ifndef GL_E01_CORE_H #define GL_E01_CORE_H #include <stdbool.h> #include <stdint.h> enum event { NONE, PRESS, RELEASE }; struct filter { bool candidate,stable; uint32_t since; }; enum event sample_key(struct filter *f,bool pressed,uint32_t now); bool output_write(uint32_t *dr,unsigned pin,bool asserted,bool active_low); enum event bsp_step(struct filter *f,bool pressed,uint32_t now,bool *enabled,uint32_t *dr); #endifsolution: files/main.c
learner@ksa:~/gl-e01/lab-m06$ bat files/main.c File: files/main.c #include "core.h" #include <stdio.h> int main(void) { puts("GL-E01 BSP laboratory: run ../check.sh for graded evidence"); return 0; }solution: files/main.d
learner@ksa:~/gl-e01/lab-m06$ bat files/main.d File: files/main.d main.o: main.c core.h core.h:Run the check
From labs/lab_m06_modular_bsp_io/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-e01/lab-m06./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - rejects a bouncing press until the full stable intervalok 3 - suppresses held repeats and accepts release before the next pressok 4 - handles tick wrap and threshold boundaries without deadline overflowok 5 - integrates two accepted presses with sibling-safe active-low output updates# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-e01/lab-m06./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - rejects a bouncing press until the full stable intervalok 3 - suppresses held repeats and accepts release before the next pressnot 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/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-e01/lab-m06$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "./.check.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM printf 'TAP version 13\n1..5\n' if make -B -C files >"$WORK/build.log" 2>&1 && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Ifiles tests.c files/libbsp.a -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 1 - strict C11 build and trusted grader link\n' PASS=$((PASS + 1)) else printf 'not ok 1 - strict C11 build and trusted grader link\n' printf " ---\n message: 'Compilation failed'\n hint: 'Fix the C11 diagnostics in files and preserve the exported ABI'\n ...\n" printf 'FAIL: repair the C11 build before testing behavior\n' >&2 fi if [ -x "$WORK/verify" ] && "$WORK/verify" 1 >"$WORK/case2.log" 2>&1; then printf 'ok 2 - rejects a bouncing press until the full stable interval\n' PASS=$((PASS + 1)) else printf 'not ok 2 - rejects a bouncing press until the full stable interval\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 1; inspect tests.c for the exact input and expected result'\n ...\n" fi if [ -x "$WORK/verify" ] && "$WORK/verify" 2 >"$WORK/case3.log" 2>&1; then printf 'ok 3 - suppresses held repeats and accepts release before the next press\n' PASS=$((PASS + 1)) else printf 'not ok 3 - suppresses held repeats and accepts release before the next press\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 2; inspect tests.c for the exact input and expected result'\n ...\n" fi if [ -x "$WORK/verify" ] && "$WORK/verify" 3 >"$WORK/case4.log" 2>&1; then printf 'ok 4 - handles tick wrap and threshold boundaries without deadline overflow\n' PASS=$((PASS + 1)) else printf 'not ok 4 - handles tick wrap and threshold boundaries without deadline overflow\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 3; inspect tests.c for the exact input and expected result'\n ...\n" fi if [ -x "$WORK/verify" ] && "$WORK/verify" 4 >"$WORK/case5.log" 2>&1; then printf 'ok 5 - integrates two accepted presses with sibling-safe active-low output updates\n' PASS=$((PASS + 1)) else printf 'not ok 5 - integrates two accepted presses with sibling-safe active-low output updates\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 4; inspect tests.c for the exact input and expected result'\n ...\n" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m06_modular_bsp_io/ so relative paths to files/ resolve directly.