Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Embedded Systems StudioIoT Programming and ApplicationsExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 30 · GPIO input · Button and events
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P30
IoT Programming and Applications

Lab 30 · GPIO input · Button and events

Ask Dr. Mohammad · P30 →

Nobody can press a button on WSL, so FAKEPI_PRESS schedules presses on GPIO18.

Design experiment & verify evidence →
P30 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP30 · GPIO input · Button and events
Readiness checksRevision deckEngineering workspaceRecord evidence
P30 · Academic orientation

Scope and objectives

Scope of the experiment

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.

Environment and experimental methodology

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.

Ubuntu WSL setup →
Before you run / verification gate

The scheduled presses are generated by FAKEPI_PRESS, not a physical button. Stop callback loop after the final event; timing is approximate.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Pushbutton debounce · edge qualification

Pull-up input: pressed LOW; release HIGH; one accepted transition per selected edge
Pull-up input: pressed LOW; release HIGH; one accepted transition per selected edge

Scientific architecture · Button bounce and event counting

Pushbutton contact bounce — Released / pull-up HIGH; Pressed / active LOW; Contact bounce / rapid transitions; Debounce window / accept stable state; Callback / one counted press
Scientific concept map: Button contacts — Mechanical bounce; Pull-up input — Idle HIGH / pressed LOW; Edge detector — Falling edge; Debounce interval — Suppress rapid changes; Callback — Count valid presses.

Scientific foundations and analytical reasoning

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.

  1. Inspect the supplied bounce timestamps around 0 ms and 50 ms.
  2. Set debounce to zero and count all rising edges.
  3. Set 15 ms then 50 ms and explain rejected transitions and potential missed presses.
  4. 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.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

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.

Lab 30 · GPIO input · Button and events: operation pathwayPull-upopen switch HIGHPressLOW begins at 30 msDebouncestable LOW for 15msAccept45 ms; releaseafter stabilityRead the active operation, then inspect the accumulated state.

Step 1 of 4 · Pull-up

Pull-up

Pull-up
open switch HIGH

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.

Build and validate this circuit in Circuit Studio →

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.
Pull-up pushbutton. Digital input and contact closure.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research
Loading 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.

ComponentSignal / pinConnection notesSource
PushbuttonBCM GPIO18 · physical 12Button to GND; internal pull-up, active-lowlab30/button.py, button_events.py
P30 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

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.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

P30 · current context

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.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
Lab 30 · GPIO input · Button and events

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.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

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.

02 · Compare or justify using evidence

Draw press/release waveforms and explain how choosing falling instead of rising edges changes the event being counted.

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.

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

  1. Inspect the supplied bounce timestamps around 0 ms and 50 ms.
  2. Set debounce to zero and count all rising edges.
  3. Set 15 ms then 50 ms and explain rejected transitions and potential missed presses.
  4. Compare the browser refractory filter with the actual button callback/polling code; record callback count.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
FilteredUse reference inputs aboveAccepted rising events: 1Record actual result
No debounceMinimum accepted edge spacing (ms) = 0Accepted rising events: 5Record 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.

TrialIndependent changeDependent observation
FilteredUse reference inputs aboveRecord actual outcome and units
No debounceMinimum accepted edge spacing (ms) = 0Record 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.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Open a terminal
  2. button.py: wait for one press
  3. button_events.py: callbacks
  4. Discuss
02 / Implement

Step-by-step instructions

Before you run / verification gate

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)
  1. 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.
  2. 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.
  3. 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.

Existing live hardware bench

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.

03 / Inspect

Source code and method

labs/python/lab30/button.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Import Button from gpiozero.
from gpiozero import Button
 
# ---- Create a button object on BCM pin 18.
# pull_up=True means the input is normally high and goes low when pressed.
button = Button(18, pull_up=True)
 
# ---- Wait for one press event.
print("Waiting for button press...")
button.wait_for_press()
print("Button was pressed.")
labs/python/lab30/button_events.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- gpiozero: attach a function to when_pressed
from gpiozero import Button
from signal import pause
btn = Button(18, bounce_time=0.2)   # pull-up is the default
btn.when_pressed = lambda: print("Button pressed!")
pause()
04 / Verify

Evidence of completion

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.

Python / Google Colab laboratory

P30 · 7 notebook cells · 2 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. 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
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 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]
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash FAKEPI_PRESS=18@2 python button.py ``` ```bash FAKEPI_PRESS=18@1,18@2.5,18@4 python button_events.py # Ctrl+C after 5 s ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Import Button from gpiozero. from gpiozero import Button # ---- Create a button object on BCM pin 18. # pull_up=True means the input is normally high and goes low when pressed. button = Button(18, pull_up=True) # ---- Wait for one press event. print("Waiting for button press...") button.wait_for_press() print("Button was pressed.") ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- gpiozero: attach a function to when_pressed from gpiozero import Button from signal import pause btn = Button(18, bounce_time=0.2) # pull-up is the default btn.when_pressed = lambda: print("Button pressed!") pause() ```
07Instructions · Markdown
## Independent investigation and submission 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. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.