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 2 · LED & buzzer timing
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X2
IoT Programming and Applications

Lab 2 · LED & buzzer timing

Ask Dr. Mohammad · X2 →

LED on GPIO24, buzzer on GPIO23: the fake pins print each change with its timing.

Design experiment & verify evidence →
X2 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX2 · LED & buzzer timing
Readiness checksRevision deckEngineering workspaceRecord evidence
X2 · Academic orientation

Scope and objectives

Scope of the experiment

Reproduce the separate LED and active-buzzer timings from the source code; measure duty and elapsed time.

The focus of this experiment is to trace LED and buzzer timing through output-state transitions. Students then calculate cycle durations and compare blocking versus timed logic, and verify independent actuator state and stop behavior. 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

  • Trace LED and buzzer timing through output-state transitions.
  • Calculate cycle durations and compare blocking versus timed logic.
  • Verify independent actuator state and stop behavior.
  • Identify the configured inputs (Practical; Cycles; LED ON interval (ms); LED OFF interval (ms)) 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 trace LED and buzzer timing through output-state transitions, calculate cycle durations and compare blocking versus timed logic, and verify independent actuator state and stop behavior.

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 independent actuator state and stop behavior. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 3 · Push-button relay & motor.

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.

X2 / 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

Wait for three LED cycles and the finite buzzer sequence. Record terminal state changes rather than claiming audible sound.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Raspberry Pi GPIO24 LED and GPIO23 active buzzer

Separate LED and buzzer outputs — GPIO24 / LED + resistor; GPIO23 / active buzzer signal; Sequence / independent timings; Common GND / reference; Driver / verify load current rating
Scientific concept map: Python GPIO24 — LED output; Python GPIO23 — Active buzzer; Timing sequence — HIGH then LOW; Actuator states — Light and tone; Cleanup — Outputs inactive.

Scientific foundations and analytical reasoning

Digital outputs activate an LED or active buzzer according to the configured timing; duty cycle is the active-time fraction.

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 · Digital actuator timing

A digital output drives a binary logic state. An LED needs current limiting, and an active buzzer sounds when correctly powered; a passive buzzer instead needs a time-varying drive. On/off durations determine period and duty cycle, and blocking delays constrain responsiveness.

Worked example and engineering interpretation

If an actuator is on for 0.2 s and off for 0.8 s, period=1 s and duty=20%. Changing the off time changes both frequency and duty. Compare measured transition timestamps with the specified program timing; use a suitable driver when load current exceeds GPIO limits.

Engineering principles · additional worked teaching example

A repeating timed waveform alternates on and off; total period is their sum. For a 150 ms pulse followed by 350 ms silence, duty=30%, frequency=2 Hz; four cycles take 2 s. A passive buzzer additionally requires a suitable excitation frequency.

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 2 · LED & buzzer timing

The LED and active buzzer are separate outputs. The active buzzer contains an oscillator; digital HIGH/LOW determines on/off, not tone frequency. Duty = on/(on+off).

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: Observe LED and buzzer behavior in the teaching model.

  1. Select LED, three cycles, 1 s HIGH and 2 s LOW. Observe GPIO24, 33.33% duty and total 9 s.
  2. Select Active buzzer and 16 cycles: the supplied GPIO23 source uses 0.5 s ON, 0.5 s OFF. These times are fixed in this mode; LED controls do not affect it.
  3. Vary LED ON/OFF intervals and compare the period, duty and total ON duration. An active buzzer has its own oscillator; no arbitrary PWM tone frequency is assumed.
  4. Run python -m labs.exp02.led --cycles 3 and python -m labs.exp02.buzzer in the appropriate GPIO environment. Compare printed events with the timing trace.

Reference check:

Model boundary:

Independent task and submission evidence

Hold LED cycles and OFF time fixed; vary ON time. Record total duration and duty. Explain why the supplied active-buzzer timing is fixed independently.

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

Engineering reference configuration: Practical = LED; Cycles = 3; LED ON interval (ms) = 1000; LED OFF interval (ms) = 2000. In the classroom model, GPIO = 24; Duty = 33.33 %; ON time = 3000 ms; Elapsed = 9000 ms. No physical audio or electrical output. Active-buzzer gate frequency is independent of its internal sound oscillator. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

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 · progressive data plot

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 2 · LED & buzzer timing: progressive data plot00.250.50.751LED output090000

Step 1 of 7 · Observation 0

Observation 0

LED output
1

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
X2 · 01 / 08What controls blink timing?Reveal explanation
Engineering explanation

The program alternates HIGH and LOW with explicit delays.

X2 · 02 / 08Does the WSL buzzer produce sound?Reveal explanation
Engineering explanation

The mock prints output state; real acoustic output is not guaranteed.

X2 · 03 / 08What must be verified in the LED and buzzer timing exercise?Reveal explanation
Engineering explanation

Wait for three LED cycles and the finite buzzer sequence. Record terminal state changes rather than claiming audible sound.

X2 · 04 / 08How does the delay affect blinking frequency?Reveal explanation
Engineering reasoning

A full cycle is the sum of HIGH and LOW durations; frequency is the reciprocal of that period.

X2 · 05 / 08Why distinguish a buzzer state message from sound?Reveal explanation
Engineering reasoning

A simulated output reports logic transitions, whereas sound requires a compatible physical transducer and drive signal.

X2 · 06 / 08A timed LED and buzzer sequence runs. Select every technically valid statement. A. Compare expected event order and durations. B. Distinguish a digital buzzer command from an acoustic measurement. C. A model animation proves sound pressure level. D. Changing delay never affects event timing.Reveal explanation
Applied scenario

Correct: A. Compare expected event order and durations.; B. Distinguish a digital buzzer command from an acoustic measurement.

X2 · 07 / 08In LED & buzzer timing, which command or code executes Buzzer?Reveal explanation
Implementation recall

python -m labs.exp02.buzzer

X2 · 08 / 08For LED & buzzer timing, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Activate toolkit, cd to pi-practical. LED program --cycles 3 runs about 9 seconds (1 s ON,2 s OFF each). Buzzer runs 16 beeps over about 16 seconds. Both finish automatically. WSL reports GPIO/Beep logs; physical sound is not required.

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.
Digital output and buzzer. Actuator switching and delay.
Digital output and buzzer. Actuator switching and delay.
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

Observe LED and buzzer behavior in the teaching model.

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 workbenchX2 · Existing model

Explore the interactive 3D electronics laboratory ↗ · 3D system simulation ↗

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
LEDBCM GPIO24 · physical 18LED via resistor to GNDexp02/led.py
BuzzerBCM GPIO23 · physical 16Active buzzer with suitable driver; observe voltage/current limitsexp02/buzzer.py
X2 · 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

X2 · 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 2 · LED & buzzer timing

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/model reviewed; GPIO Zero runtime pending.

Activate toolkit, cd to pi-practical. LED program --cycles 3 runs about 9 seconds (1 s ON,2 s OFF each). Buzzer runs 16 beeps over about 16 seconds. Both finish automatically. WSL reports GPIO/Beep logs; physical sound is not required.

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 three cycles with 1000 ms ON and 2000 ms OFF, calculate total time, ON time and duty cycle.

02 · Compare or justify using evidence

Sketch both GPIO24 LED and GPIO23 buzzer timelines for their respective modes; explain why a GPIO should not directly drive a high-current load.

03 · Timing calculation

Timing calculation · Independent work

For six cycles with LED on 120 ms and off 280 ms, compute duty, repetition rate, total elapsed and total on time.

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.

Intermediate · Explain a changed-input result

Independent theoretical exercise · X2-01

Use the reference configuration (Practical = LED; Cycles = 3; LED ON interval (ms) = 1000; LED OFF interval (ms) = 2000), but change Practical = Active buzzer. The model reports GPIO = 23. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · X2-02

Two model observations of GPIO are 24 (reference) and 23 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · X2-03

For Cycles = 5, the model supplies this excerpt from Output timing: Cycle · Time ms · Output · Hold ms 1 · 0 · ON · 1000 1 · 1000 · OFF · 2000 2 · 3000 · ON · 1000 2 · 4000 · OFF · 2000 3 · 6000 · ON · 1000 Compute the range (maximum minus minimum) of the Time ms column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · X2-04

An observation is ON time = 5000 ms. Candidate A uses Practical = LED; Cycles = 3; LED ON interval (ms) = 1000; LED OFF interval (ms) = 2000. Candidate B changes the listed settings (Cycles = 5) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · X2-05

A student configures LED ON interval (ms) = 1002 while preserving all other reference settings, but copies the reference report of Duty = 33.33 %. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X2-06

Design a controlled comparison for Lab 2 · LED & buzzer timing using reference Practical = LED; Cycles = 3; LED ON interval (ms) = 1000; LED OFF interval (ms) = 2000 and test Practical = Active buzzer. Specify the changed setting(s), measured metric GPIO, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Reproduce the separate LED and active-buzzer timings from the source code; measure duty and elapsed time.

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.

PracticalLED
Cycles3
LED ON interval (ms)1000
LED OFF interval (ms)2000

2 · Perform the investigation in order

  1. Select LED, three cycles, 1 s HIGH and 2 s LOW. Observe GPIO24, 33.33% duty and total 9 s.
  2. Select Active buzzer and 16 cycles: the supplied GPIO23 source uses 0.5 s ON, 0.5 s OFF. These times are fixed in this mode; LED controls do not affect it.
  3. Vary LED ON/OFF intervals and compare the period, duty and total ON duration. An active buzzer has its own oscillator; no arbitrary PWM tone frequency is assumed.
  4. Run python -m labs.exp02.led --cycles 3 and python -m labs.exp02.buzzer in the appropriate GPIO environment. Compare printed events with the timing trace.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
LED source timingUse reference inputs aboveDuty: 33.33; ON time: 3000Record actual result
Buzzer source timingPractical = Active buzzer; Cycles = 16Duty: 50; ON time: 8000Record actual result
Short LED pulseLED ON interval (ms) = 100; LED OFF interval (ms) = 900Duty: 10Record actual result

4 · Analyze and report

LED and buzzer are independent practicals with distinct BCM pins.

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
LED source timingUse reference inputs aboveRecord actual outcome and units
Buzzer source timingPractical = Active buzzer; Cycles = 16Record actual outcome and units
Short LED pulseLED ON interval (ms) = 100; LED OFF interval (ms) = 900Record 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 in the project root
  2. LED, 3 cycles
  3. Buzzer
02 / Implement

Step-by-step instructions

Before you run / verification gate

Wait for three LED cycles and the finite buzzer sequence. Record terminal state changes rather than claiming audible sound.

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 in the project root

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
Expected result for each action (2)
  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/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
Checkpoint you are in the folder that contains labs/ ; every command is python -m labs.expNN.… as on the page.
02

LED, 3 cycles

WSL · Bash
python -m labs.exp02.led --cycles 3
✓ Expected: [fake-pi] GPIO24 = HIGH / LED ON , 1 s later GPIO24 = LOW / LED OFF , 2 s off, three times.
Checkpoint [fake-pi] GPIO24 = HIGH / LED ON , 1 s later GPIO24 = LOW / LED OFF , 2 s off, three times.
03

Buzzer

WSL · Bash
python -m labs.exp02.buzzer
✓ Expected: 16 × GPIO23 = HIGH + Beep , 0.5 s on, 0.5 s off (about 16 s).
Checkpoint 16 × GPIO23 = HIGH + Beep , 0.5 s on, 0.5 s off (about 16 s).

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

Optional physical acceptance · supervised low-voltage work

Low-voltage LED timing check

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 the supplied physical LED wiring, 330 Ω series resistor and common ground. Verify GPIO assignment in your actual script before connecting power.

Procedure: Measure LED HIGH duration over at least three complete cycles using a scope or suitable timestamped instrument; compare the configured 1 s ON duration.

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/pi-practical/labs/exp02/buzzer.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / BUZZER
# ====================================================================
"""Experiment 2b: active buzzer on GPIO23, 16 half-second beeps."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
from time import sleep

# ====================================================================
# 02 / INITIALIZE THE BUZZER
# ====================================================================
def main():
    from gpiozero import Buzzer
    # Use BCM GPIO23 and start with the output inactive.
    with Buzzer(23, initial_value=False) as buzzer:
        # ====================================================================
        # 03 / GENERATE THE 16-SECOND ALERT
        # ====================================================================
        for _ in range(16):
            # Activate the driver for half a second.
            # Activate the buzzer driver, announce the beep and wait 0.5 seconds.
            buzzer.on(); print('Beep'); sleep(0.5)
            # Disable the buzzer for the remaining half-cycle.
            # Deactivate the driver for 0.5 seconds; one cycle lasts one second.
            buzzer.off(); sleep(0.5)

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
labs/pi-practical/labs/exp02/led.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / LED
# ====================================================================
"""Experiment 2a: GPIO24 LED, 1 s ON and 2 s OFF."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import argparse
from time import sleep

# ====================================================================
# 02 / CONFIGURE THE BLINK EXPERIMENT
# ====================================================================
def main():
    p = argparse.ArgumentParser(description=__doc__)
    # Zero cycles means repeat continuously; otherwise use a finite count.
    p.add_argument('--cycles', type=int, default=0, help='0 means repeat')
    a = p.parse_args()
    if a.cycles < 0: p.error('cycles must be nonnegative')
    from gpiozero import LED
    # ====================================================================
    # 03 / CONFIGURE GPIO24 AND RUN THE BLINK LOOP
    # ====================================================================
    with LED(24, initial_value=False) as led:
        i = 0
        # Repeat indefinitely or stop when the requested count is reached.
        while not a.cycles or i < a.cycles:
            # Set the output HIGH and hold it for one second.
            # Drive the LED HIGH, display its state and wait one second.
            led.on(); print('LED ON'); sleep(1)
            # Set the output LOW and wait two seconds.
            # Drive the LED LOW, display its state and wait two seconds.
            led.off(); print('LED OFF'); sleep(2)
            # Count one completed three-second blink cycle.
            i += 1

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
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

X2 · 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
# X2 · Lab 2 · LED & buzzer timing **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose The LED and active buzzer are separate outputs. The active buzzer contains an oscillator; digital HIGH/LOW determines on/off, not tone frequency. Duty = on/(on+off). **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
# =====================================================================
# X2 | Code cell 01 | Lab 2 · LED & buzzer timing
# 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.
# =====================================================================
# Define the reusable operation timing; keep its logic separate from the trial.
def timing(device, cycles,on,off):
    if device=='buzzer': cycles,on,off=16,.5,.5
    return {'gpio':24 if device=='led' else 23,'duration_s':cycles*(on+off),'on_s':cycles*on,'duty_pct':100*on/(on+off)}
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# X2 | Code cell 02 | Lab 2 · LED & buzzer timing
# 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.
# =====================================================================
print(timing('led',3,1,2));print(timing('buzzer',3,1,2))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert timing('led',3,1,2)['duration_s']==9
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert timing('buzzer',3,1,2)['duration_s']==16
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 python -m labs.exp02.led --cycles 3 ``` ```bash python -m labs.exp02.buzzer ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / BUZZER # ==================================================================== """Experiment 2b: active buzzer on GPIO23, 16 half-second beeps.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== from time import sleep # ==================================================================== # 02 / INITIALIZE THE BUZZER # ==================================================================== def main(): from gpiozero import Buzzer # Use BCM GPIO23 and start with the output inactive. with Buzzer(23, initial_value=False) as buzzer: # ==================================================================== # 03 / GENERATE THE 16-SECOND ALERT # ==================================================================== for _ in range(16): # Activate the driver for half a second. # Activate the buzzer driver, announce the beep and wait 0.5 seconds. buzzer.on(); print('Beep'); sleep(0.5) # Disable the buzzer for the remaining half-cycle. # Deactivate the driver for 0.5 seconds; one cycle lasts one second. buzzer.off(); sleep(0.5) # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / LED # ==================================================================== """Experiment 2a: GPIO24 LED, 1 s ON and 2 s OFF.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import argparse from time import sleep # ==================================================================== # 02 / CONFIGURE THE BLINK EXPERIMENT # ==================================================================== def main(): p = argparse.ArgumentParser(description=__doc__) # Zero cycles means repeat continuously; otherwise use a finite count. p.add_argument('--cycles', type=int, default=0, help='0 means repeat') a = p.parse_args() if a.cycles < 0: p.error('cycles must be nonnegative') from gpiozero import LED # ==================================================================== # 03 / CONFIGURE GPIO24 AND RUN THE BLINK LOOP # ==================================================================== with LED(24, initial_value=False) as led: i = 0 # Repeat indefinitely or stop when the requested count is reached. while not a.cycles or i < a.cycles: # Set the output HIGH and hold it for one second. # Drive the LED HIGH, display its state and wait one second. led.on(); print('LED ON'); sleep(1) # Set the output LOW and wait two seconds. # Drive the LED LOW, display its state and wait two seconds. led.off(); print('LED OFF'); sleep(2) # Count one completed three-second blink cycle. i += 1 # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
07Instructions · Markdown
## Independent investigation and submission Hold LED cycles and OFF time fixed; vary ON time. Record total duration and duty. Explain why the supplied active-buzzer timing is fixed independently. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.