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

30 minfree previewLinux 6.12C11U-Boot 2025.x← module 6

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

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-m06
learner@ksa:~/gl-e01/lab-m06ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m06
starter: starter/Makefile
learner@ksa: ~/gl-e01/lab-m06
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_demo
starter: starter/core.c
learner@ksa: ~/gl-e01/lab-m06
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
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);    #endif
starter: starter/main.c
learner@ksa: ~/gl-e01/lab-m06
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

  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.

step 3/15 · 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).

step 4/15 · 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).

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
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): 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.

step 7/15 · 7. expected tap-13 output

learner@ksa: ~/gl-e01/lab-m06
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/5

step 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

  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.

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 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!

step 11/15 · 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)

step 12/15 · 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?

step 13/15 · 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.

step 14/15 · 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).

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
learner@ksa:~/gl-e01/lab-m06./check.shlearner@ksa:~/gl-e01/lab-m06
expected output
TAP version 131..5ok 1 - strict C11 build and trusted grader link

Progressive 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

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:

./check.sh — lab m06
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/5

On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:

./check.sh — lab m06 (starter)
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/5

note: 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
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.

Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure