Compare raw transitions with a declared refractory debounce filter.
The focus of this experiment is to distinguish pull-up, pull-down, active level and switch bounce. Students then trace input states and count debounced button events, and verify event behavior with controlled presses or the supplied mock. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.
Learning objectives
Distinguish pull-up, pull-down, active level and switch bounce.
Trace input states and count debounced button events.
Verify event behavior with controlled presses or the supplied mock.
Identify the configured inputs (Minimum accepted edge spacing (ms); Event mode) and record the corresponding observed outputs with units where applicable.
Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.
Expected learning outcomes
On completion, students can distinguish pull-up, pull-down, active level and switch bounce, trace input states and count debounced button events, and verify event behavior with controlled presses or the supplied mock.
Required deliverables
Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify event behavior with controlled presses or the supplied mock. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Lab 31 · PWM brightness and alternate functions.
Browser teaching model, the named WSL or Python environment, and the physical board/components only for the hardware activity described in the practical instructions.
Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.
P30 / PREPARE
Before starting
Follow the setup guide and use the named terminal or editor. A browser model is not a real GPIO measurement or a running service.
An active-low pull-up input reads HIGH when released and LOW when pressed. Contact bounce creates multiple transitions; debouncing suppresses closely spaced edges.
Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.
Scientific theory · Pull-up logic and edge qualification
A pull-up holds an otherwise open input HIGH; closing the button to ground makes it LOW. This is active-low logic. Mechanical contacts can bounce between states before settling. An edge callback observes transitions, while a polling loop samples the current state; both require a defined debounce policy.
Worked example and engineering interpretation
With a 20 ms debounce window, falling edges at 0, 4 and 9 ms belong to one accepted action in a simple suppression model. A later falling edge at 100 ms may count as a second press if the button was released. Distinguish raw edges from accepted events.
Engineering principles · additional worked teaching example
A pull-up holds an open switch at logic 1; closing to ground gives logic 0. A debounce gate based on last accepted edge ignores further events until the minimum spacing has elapsed. With rising times 0,2,18 ms and spacing 10 ms, accept 0 and 18, not 2.
From theory to experiment
Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.
How to investigate Lab 30 · GPIO input · Button and events
A pull-up input reads HIGH when released and LOW when pressed. Mechanical bounce causes multiple rapid edges. A refractory debounce filter ignores falling edges arriving too soon after an accepted press; it is a simplified callback model.
Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.
Experiment-specific guided practice
Objective: Explain active-low button input and observe mock press events.
Inspect the supplied bounce timestamps around 0 ms and 50 ms.
Set debounce to zero and count all rising edges.
Set 15 ms then 50 ms and explain rejected transitions and potential missed presses.
Compare the browser refractory filter with the actual button callback/polling code; record callback count.
Reference check:
Model boundary:
Independent task and submission evidence
Keep the event timestamps fixed; compare debounce 0, 15 and 250 ms. Record accepted timestamps and count, then explain bounce rejection versus missed valid presses.
Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.
Worked engineering reasoning and boundary conditions
A pull-up sets an open switch HIGH; a closed switch to ground reads LOW. A stable-state debounce accepts a state after it remains stable for a chosen interval, unlike edge-spacing filters. Example: LOW begins at 30 ms and remains until 80 ms; 15 ms stability confirms press at 45 ms.
Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.
Concept animation · operation pathway
Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.
Step 1 of 4 · Pull-up
Pull-up
Pull-up
open switch HIGH
Press
Pull-up
open switch HIGH
Press
LOW begins at 30 ms
Debounce
Pull-up
open switch HIGH
Press
LOW begins at 30 ms
Debounce
stable LOW for 15 ms
Accept
Pull-up
open switch HIGH
Press
LOW begins at 30 ms
Debounce
stable LOW for 15 ms
Accept
45 ms; release after stability
Teaching example only; inspect live calculations or real practical evidence separately.
Recall the concept before revealing its explanation.
0 / 3 revealed
P30 · 01 / 08What is active-low?Reveal explanation
Engineering explanation
A pull-up input reads HIGH at rest and LOW when pressed.
P30 · 02 / 08What is debounce?Reveal explanation
Engineering explanation
A time filter reduces repeated transitions caused by switch bounce.
P30 · 03 / 08What produces scheduled button events under WSL and when should the callback loop stop?Reveal explanation
Engineering explanation
The scheduled presses are generated by FAKEPI_PRESS, not a physical button. Stop callback loop after the final event; timing is approximate.
P30 · 04 / 08What does a pull-up resistor do for an open button?Reveal explanation
Engineering reasoning
It establishes a defined HIGH idle state; an active-low button to ground produces LOW when pressed.
P30 · 05 / 08Why distinguish polling from an event callback?Reveal explanation
Engineering reasoning
Polling repeatedly reads input, while a callback responds to transitions; debounce can suppress multiple events from one mechanical press.
P30 · 06 / 08A button uses an active-low input with pull-up. Select every technically valid statement.
A. The released input is HIGH.
B. A press connects the input to LOW in the reference topology.
C. A held button is always a sequence of independent presses.
D. Pull-up means the released input is LOW.Reveal explanation
Applied scenario
Correct: A. The released input is HIGH.; B. A press connects the input to LOW in the reference topology.
P30 · 07 / 08In GPIO input · Button and events, which command or code executes button_events.py: callbacks?Reveal explanation
Implementation recall
FAKEPI_PRESS=18@1,18@2.5,18@4 python button_events.py # Ctrl+C after 5 s
P30 · 08 / 08For GPIO input · Button and events, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance
Use a fresh activated terminal per example. FAKEPI_PRESS uses seconds relative to process startup. For the first example expect one Button was pressed message after the scheduled GPIO18 LOW. For events, expect three callbacks when the process remains running for 5 s. Interrupt only after observing them. If a scheduled event is missed, record it and repeat.
Execution boundary · Simulated (fake Pi). Browser simulation below is a teaching model, not execution of Python or firmware. The real commands run in VS Code/WSL; Wokwi is used for Arduino/ESP32 where indicated.
Pull-up pushbutton. Digital input and contact closure.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery researchLoading experiment-specific apparatus…Previous model / additional reference tools
Simulation task
Explain active-low button input and observe mock press events.
Explore the model using its own controls. Record a prediction before changing a condition. Compare the reference with a changed condition, then use the Experiment tab for the procedure, acceptance criteria and notebook. Model outputs and physical observations must remain separate.
Interactive engineering workbenchP30 · Existing model
01 / Explore
Interactive lab simulation
Browser model
Pin and connection reference
WSL uses simulated GPIO. These are source-derived signal mappings; physical connection notes are guidance, not a claim of physical testing.
Original virtual instrument; model signals and execution trace.
Loading instrument…
Awaiting model display.
Experimental instrumentation · A/B
Compare two model conditions
Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.
Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.
Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.
Prepare a contextual AI prompt
0 characters
Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.
Prepare → review → copy & open your selected provider → paste and submit there.
Run & verify — acceptance checklist
Build verification: Source and model reviewed; GPIO Zero runtime pending.
Use a fresh activated terminal per example. FAKEPI_PRESS uses seconds relative to process startup. For the first example expect one Button was pressed message after the scheduled GPIO18 LOW. For events, expect three callbacks when the process remains running for 5 s. Interrupt only after observing them. If a scheduled event is missed, record it and repeat.
Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.
Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.
01 · Predict and derive using the given inputs
For rising edges at 0, 3, 7, 25 and 40 ms, accept the first edge and then require at least 15 ms since the last accepted edge. List accepted events.
Engineering method — A pull-up holds an open switch at logic 1; closing to ground gives logic 0. A debounce gate based on last accepted edge ignores further events until the minimum spacing has elapsed. With rising times 0,2,18 ms and spacing 10 ms, accept 0 and 18, not 2. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Compare or justify using evidence
Draw press/release waveforms and explain how choosing falling instead of rising edges changes the event being counted.
Engineering method — A pull-up holds an open switch at logic 1; closing to ground gives logic 0. A debounce gate based on last accepted edge ignores further events until the minimum spacing has elapsed. With rising times 0,2,18 ms and spacing 10 ms, accept 0 and 18, not 2. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · State tracing
State tracing · Independent work
For rising timestamps 5,9,20,24,35 ms and 12 ms minimum accepted-edge spacing, list accepted events. Explain whether rejecting a bounce restarts the timer in this model.
State tracing — A pull-up holds an open switch at logic 1; closing to ground gives logic 0. A debounce gate based on last accepted edge ignores further events until the minimum spacing has elapsed. With rising times 0,2,18 ms and spacing 10 ms, accept 0 and 18, not 2. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.
Expanded independent theoretical exercise bank
Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.
Foundational · Apply the principle
Independent theoretical exercise · P30-01
Open switch with pull-up reads which value? What does a press change?
Intermediate · Calculate or trace
Independent theoretical exercise · P30-02
With edge-spacing filter 10 ms and falling edges at 0,4,13,17,30 ms, list accepted edges.
Intermediate · Interpret the result
Independent theoretical exercise · P30-03
With stable-state debounce 20 ms, LOW from t=10 to 25 ms, then HIGH until 40 ms, then LOW until 90 ms. When is press accepted?
Advanced · Analyze a condition
Independent theoretical exercise · P30-04
A button wired to ground uses a pull-down instead of a pull-up. Why may open and closed appear identical?
Advanced · Diagnose or compare
Independent theoretical exercise · P30-05
A 10 kΩ pull-up on 3.3 V is pressed. Estimate steady pull-up current.
Challenging · Engineering verification
Independent theoretical exercise · P30-06
Compare polling every 50 ms with interrupt capture for a 12 ms press.
Step-by-step experimental procedure
Compare raw transitions with a declared refractory debounce filter.
1 · Reference workbench configuration
Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.
Minimum accepted edge spacing (ms)15
Event moderising
2 · Perform the investigation in order
Inspect the supplied bounce timestamps around 0 ms and 50 ms.
Set debounce to zero and count all rising edges.
Set 15 ms then 50 ms and explain rejected transitions and potential missed presses.
Compare the browser refractory filter with the actual button callback/polling code; record callback count.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Filtered
Use reference inputs above
Accepted rising events: 1
Record actual result
No debounce
Minimum accepted edge spacing (ms) = 0
Accepted rising events: 5
Record actual result
4 · Analyze and report
This simplified edge lockout is not a stable-duration debounce algorithm.
Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.
Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.
Controlled investigation · reproducible evidence
Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.
Trial
Independent change
Dependent observation
Filtered
Use reference inputs above
Record actual outcome and units
No debounce
Minimum accepted edge spacing (ms) = 0
Record actual outcome and units
Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.
Loading laboratory-specific procedure…
Python / Google Colab notebook
Stateful virtual GPIO with explicit direction, input stimulation, PWM and verification; optional real MQTT telemetry exercise. Default profile executed in an isolated local Python kernel. Live services and physical hardware are separate acceptance tasks.
The scheduled presses are generated by FAKEPI_PRESS, not a physical button. Stop callback loop after the final event; timing is approximate.
Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.
01
Open a terminal
WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab30
ls
✓ Expected: The requested files/directories are listed; compare names and permissions with the guide. An empty directory can produce no output.Expected result for each action (3)
source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
cd ~/psut-wsl/labs/python/lab30Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
lsThe requested files/directories are listed; compare names and permissions with the guide. An empty directory can produce no output.
Checkpoint the lab’s programs are listed.
02
button.py: wait for one press
WSL · Bash
FAKEPI_PRESS=18@2 python button.py
✓ Expected: Waiting for button press... , after 2 s [fake-pi] GPIO18 pressed (line LOW) and Button was pressed.
Checkpoint Waiting for button press... , after 2 s [fake-pi] GPIO18 pressed (line LOW) and Button was pressed.
03
button_events.py: callbacks
WSL · Bash
FAKEPI_PRESS=18@1,18@2.5,18@4 python button_events.py # Ctrl+C after 5 s
✓ Expected: three Button pressed! lines, each right after a scheduled press.
Checkpoint three Button pressed! lines, each right after a scheduled press.
04
Discuss
Change the times or add a press at 0.1 s after another one: how does bounce_time=0.2 change what you see?
Checkpoint presses closer than 0.2 s count once.
Experimental notebook
Record your own results. Values are not prefilled or independently verified.
Optional physical acceptance · supervised low-voltage work
Active-low input on Raspberry Pi 4
Apparatus: Actual Raspberry Pi 4, suitable 3.3 V-compatible components, appropriate supply and instrument. WSL mock output is not physical evidence.
Wiring and safety: Use BCM18 (physical pin 12) with a button to GND and the documented pull-up input configuration. Disconnect power before wiring; never connect to 5 V.
Procedure: Press/release using the documented program. Measure released input voltage; verify pressed LOW separately.
Declare prediction, tolerance and uncertainty before measurements. Collect at least three readings under the same condition. If hardware is unavailable, record the limitation; do not fabricate readings.
Within tolerance requires every absolute error plus declared uncertainty to lie within tolerance. If any interval is entirely outside, the result is outside; overlap is inconclusive. User-attested evidence is not independent hardware validation.
Save the actual terminal output from the checkpoints above. For simulated inputs explicitly record browser model, fakepi, mock or Wokwi. Never present those data as physical measurements. If a checkpoint fails, see the troubleshooting guide.
Inspect source-aligned signals, make a prediction, compare the idealized readings and export model evidence. This is supplementary to the practical procedure.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# P30 · Lab 30 · GPIO input · Button and events
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## Theory and purpose
A pull-up input reads HIGH when released and LOW when pressed. Mechanical bounce causes multiple rapid edges. A refractory debounce filter ignores falling edges arriving too soon after an accepted press; it is a simplified callback model.
**Execution boundary:** local computational model or loopback as explicitly described; not physical measurements or external service certification. Run cells in order.
02Instructions · Markdown
## 1. Define the experiment mechanism and inputs
03Python · executable cell
PYTHON · Code cell
# =====================================================================
# P30 | Code cell 01 | Lab 30 · GPIO input · Button and events
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set events for the next computation or reference condition.
events = [(0,1),(100,0),(104,1),(108,0),(200,1),(300,0),(400,1)]
# Define the reusable operation presses; keep its logic separate from the trial.
def presses(events, debounce_ms):
accepted = []; last = 1
for ms, level in events:
if last == 1 and level == 0 and (not accepted or ms-accepted[-1] >= debounce_ms):
accepted.append(ms) # Record only accepted falling edges
last = level
return accepted
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P30 | Code cell 02 | Lab 30 · GPIO input · Button and events
# Purpose: 2. Execute the reference and inspect observations
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for debounce in (0,15,50,250):
print(debounce, 'ms:', presses(events,debounce))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert presses(events,15)==[100,300]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert presses(events,0)==[100,108,300]