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 29 · GPIO output · LED
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P29
IoT Programming and Applications

Lab 29 · GPIO output · LED

Ask Dr. Mohammad · P29 →

gpiozero and RPi.GPIO drive GPIO17 on the fake Pi; every change is printed.

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

Scope and objectives

Scope of the experiment

An LED driven by a digital output illustrates the relationship between logic level and circuit current. The series resistor and LED forward voltage constrain the output current; software timing determines when the output changes.

The focus of this experiment is to model an active-high GPIO-driven LED and its series resistor. Students then calculate ideal LED current and resistor power and trace HIGH/LOW timing, and validate pin numbering and output behavior without exceeding electrical ratings. 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

  • Model an active-high GPIO-driven LED and its series resistor.
  • Calculate ideal LED current and resistor power and trace HIGH/LOW timing.
  • Validate pin numbering and output behavior without exceeding electrical ratings.
  • Identify the configured inputs (GPIO level; GPIO supply (V); LED forward voltage (V); Series resistor (Ω)) 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 model an active-high GPIO-driven LED and its series resistor, calculate ideal LED current and resistor power and trace HIGH/LOW timing, and validate pin numbering and output behavior without exceeding electrical ratings.

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 validate pin numbering and output behavior without exceeding electrical ratings. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 30 · GPIO input · Button and events.

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.

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

Press Enter for led.py; stop both blinking variants with Ctrl+C before the next variant. WSL GPIO messages are simulated.

CONCEPTS / ACTIVE RECALL

Understand the experiment

GPIO17 · LED and current-limiting resistor

Raspberry Pi 3.3 V logic • ideal fixed-forward-voltage model
Raspberry Pi 3.3 V logic • ideal fixed-forward-voltage model

Scientific architecture · LED circuit and GPIO output

GPIO17 current-limited LED — GPIO17 high / 3.3 V; Resistor / 330 Ω; LED / Vf ≈ 2.0 V; Ground / current return; I ≈ 3.94 mA / idealized example
Scientific concept map: GPIO17 output — 3.3V or 0V; Series resistor — I=(V−Vf)/R; LED junction — Forward voltage; Ground return — Common GND; Observation — Current and on/off state.

Scientific foundations and analytical reasoning

An ideal GPIO LED circuit uses a series resistor to bound current. I=max(0,Vout−Vf)/R; actual current depends on output impedance and the LED curve.

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 · Electrical model of a GPIO LED

A forward-biased LED emits light when current flows from anode to cathode. A series resistor limits current; ideal current is (Vout−Vf)/R when Vout exceeds the forward drop. Resistor dissipation is \(I^2R\). Real GPIO output has finite drive capability and the LED voltage depends on current and temperature.

Worked example and engineering interpretation

At 3.3 V, Vf=2.0 V and R=330 Ω, I≈3.94 mA and resistor power≈5.12 mW. Increasing R to 660 Ω halves the ideal current. A simulated current is a prediction, not a measured pin voltage or an electrical safety certification.

Engineering principles · additional worked teaching example

The ideal voltage across a series resistor is max(Vout−Vf,0). At 3.3 V, Vf=1.9 V, R=470 Ω, current=1.4/470=2.979 mA; P=1.\(4^{2}\)/470=4.170 mW. Doubling resistance halves current under the fixed-drop assumption. GPIO drive limits and actual LED characteristics must be checked separately.

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 29 · GPIO output · LED

BCM17 (physical pin 11) is a digital output. HIGH is nominally 3.3 V, LOW is 0 V. A series resistor limits LED current: \(I=\frac{\max(0,V_{\mathrm{out}}-V_f)}{R}\); resistor power = \(I^2R\). The virtual clock advances without waiting; it cannot measure a physical pin.

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: Verify GPIO17 digital output transitions and stop continuous programs.

  1. Set HIGH at 3.3 V and R=330 Ω. Calculate (3.3−2.0)/330 and compare mA.
  2. Select LOW and observe zero current; select HIGH and increase R to 1 kΩ.
  3. Raise forward voltage toward supply; inspect the model’s cutoff.
  4. Use the original LED wiring and gpiozero source; measure real current only with suitable equipment.

Reference check:

Model boundary:

Independent task and submission evidence

Keep supply, forward voltage and timing fixed; predict current at 220 Ω and 660 Ω, then add those values to the final loop. Record current, resistor power and HIGH/LOW trace; explain why this is not a physical drive-rating test.

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

For an active-high LED connected from output through a resistor to ground, the circuit is GPIO→R→LED→GND. In the ideal fixed-drop model at 3.3 V, Vf=1.8 V, R=680 Ω, current=1.5/680=2.21 mA and P=\(I^2R\)=3.31 mW. Active-low wiring sinks current when the output is LOW. Check board limits and wiring with power off.

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.

Mathematical representation and interpretation

LED series circuit

V_GPIO and V_f are volts, R is ohms, I is amperes and P_R watts. This ideal forward-voltage approximation applies when V_GPIO exceeds V_f; otherwise approximate I=0. Check the board and component ratings independently.

\[I=\frac{V_{\mathrm{GPIO}}-V_f}{R},\qquad P_R=I^2R\]

For a separate teaching case with a 3.3 V output, 1.9 V LED and 470 Ω resistor, the ideal current is \(I=1.4/470\approx2.98\,\mathrm{mA}\) and \(P_R\approx4.17\,\mathrm{mW}\). These values are different from the independent exercise.

Concept animation · LED series-circuit analysis

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 29 · GPIO output · LED: LED series-circuit analysisGPIOHIGH · 3.3 V680 ΩGNDLED · 1.8 V

Step 1 of 4 · Supply and GPIO HIGH

Supply and GPIO HIGH

GPIO output
3.3 V

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P29 · 01 / 08How does an LED output work?Reveal explanation
Engineering explanation

BCM17 is driven HIGH or LOW; the mock reports state rather than supplying current.

P29 · 02 / 08Why use a resistor?Reveal explanation
Engineering explanation

A physical LED needs current limitation; the mock does not verify electrical safety.

P29 · 03 / 08How do you end each LED script before starting the next GPIO variant?Reveal explanation
Engineering explanation

Press Enter for led.py; stop both blinking variants with Ctrl+C before the next variant. WSL GPIO messages are simulated.

P29 · 04 / 08What is the ideal peak LED current at 3.3 V with a 2 V drop and 330 Ω?Reveal explanation
Engineering reasoning

Approximately (3.3−2)/330 = 3.94 mA. A real LED drop and GPIO drive capability must be checked.

P29 · 05 / 08Why distinguish a single output operation from blinking?Reveal explanation
Engineering reasoning

A steady program retains a state until its stop condition, while blinking alternates states with delays; stop the first process before starting another.

P29 · 06 / 08An LED mock test passes on GPIO17. Select every technically valid statement. A. The mock demonstrates software output transitions. B. A physical test must separately verify wiring and voltage. C. Mock output proves current through the physical LED. D. A continuous GPIO program never needs cleanup.Reveal explanation
Applied scenario

Correct: A. The mock demonstrates software output transitions.; B. A physical test must separately verify wiring and voltage.

P29 · 07 / 08In GPIO output · LED, which command or code executes legacy_rpigpio_pi4_only.py (RPi.GPIO)?Reveal explanation
Implementation recall

python legacy_rpigpio_pi4_only.py # Ctrl+C to stop

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

All examples use BCM17, physical pin 11. Press Enter to end led.py; interrupt each continuous blinking script before starting the next. Expect repeated HIGH/LOW on the mock at approximately 0.5 s intervals, not physical LED light. Use a suitable series resistor for real hardware.

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.
LED output circuit. GPIO output and series current limiting.
LED output circuit. GPIO output and series current limiting.
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

Verify GPIO17 digital output transitions and stop continuous programs.

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 workbenchP29 · 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
LED outputBCM GPIO17 · physical 11LED via current-limiting resistor to GNDlab29/led.py, blink_gpiozero.py
P29 · 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

P29 · 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 29 · GPIO output · LED

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: Legacy RPi.GPIO mock program executed; gpiozero exercises pending.

All examples use BCM17, physical pin 11. Press Enter to end led.py; interrupt each continuous blinking script before starting the next. Expect repeated HIGH/LOW on the mock at approximately 0.5 s intervals, not physical LED light. Use a suitable series resistor for real hardware.

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 3.3 V, forward voltage 2.0 V and 330 Ω, calculate current and resistor dissipation. Repeat for 220 Ω and LOW.

02 · Compare or justify using evidence

Explain why this calculation does not establish a safe GPIO drive rating; draw the circuit and identify the common ground.

03 · Calculation and design

Calculation and design · Independent work

For Vout=3.3 V, Vf=2.1 V and target current at most 3 mA, derive the minimum resistance and select from 330, 470, 680 Ω. Calculate selected ideal current.

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 · P29-01

Calculate R for 3.3 V, Vf=2.1 V, target current 5 mA. Select the smallest of 220, 270, 330 Ω giving no more than 5 mA.

Intermediate · Calculate or trace

Independent theoretical exercise · P29-02

For 270 Ω calculate resistor power in mW.

Intermediate · Interpret the result

Independent theoretical exercise · P29-03

For active-low wiring from 3.3 V through R and LED to GPIO, predict LED state at output HIGH and LOW.

Advanced · Analyze a condition

Independent theoretical exercise · P29-04

A gpiozero script uses LED(17); the wire is connected to physical pin 17. Diagnose.

Advanced · Diagnose or compare

Independent theoretical exercise · P29-05

A working script toggles GPIO17 every 0.4 s (starting ON), then OFF for 0.4 s. Find period, frequency and ON fraction.

Challenging · Engineering verification

Independent theoretical exercise · P29-06

A virtual LED toggles but the physical LED remains OFF. Give a safe test plan.

Step-by-step experimental procedure

Calculate LED current and logical output for a simple series resistor circuit.

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.

GPIO levelHIGH
GPIO supply (V)3.3
LED forward voltage (V)2
Series resistor (Ω)330

2 · Perform the investigation in order

  1. Set HIGH at 3.3 V and R=330 Ω. Calculate (3.3−2.0)/330 and compare mA.
  2. Select LOW and observe zero current; select HIGH and increase R to 1 kΩ.
  3. Raise forward voltage toward supply; inspect the model’s cutoff.
  4. Use the original LED wiring and gpiozero source; measure real current only with suitable equipment.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
LED onUse reference inputs aboveLED current: 3.9394Record actual result
Output lowGPIO level = LOWLED current: 0Record actual result
Larger resistorSeries resistor (Ω) = 1000LED current: 1.3Record actual result

4 · Analyze and report

The constant forward-voltage assumption approximates an LED, not its nonlinear I–V curve.

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 onUse reference inputs aboveRecord actual outcome and units
Output lowGPIO level = LOWRecord actual outcome and units
Larger resistorSeries resistor (Ω) = 1000Record 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. led.py: on until Enter
  3. blink_gpiozero.py
  4. legacy_rpigpio_pi4_only.py (RPi.GPIO)
02 / Implement

Step-by-step instructions

Before you run / verification gate

Press Enter for led.py; stop both blinking variants with Ctrl+C before the next variant. WSL GPIO messages are simulated.

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/lab29
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/lab29Normally 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

led.py: on until Enter

WSL · Bash
python led.py
✓ Expected: Fake GPIO17 becomes HIGH and the program waits for Enter; pressing Enter returns the output to LOW.
Checkpoint [fake-pi] GPIO17 = HIGH , the prompt, and after Enter [fake-pi] GPIO17 = LOW .
03

blink_gpiozero.py

WSL · Bash
python blink_gpiozero.py        # Ctrl+C to stop
✓ Expected: The fake GPIO17 output alternates HIGH/LOW every 0.5 seconds. Press Ctrl+C to stop.
Checkpoint GPIO17 = HIGH / GPIO17 = LOW every 0.5 s.
04

legacy_rpigpio_pi4_only.py (RPi.GPIO)

WSL · Bash
python legacy_rpigpio_pi4_only.py   # Ctrl+C to stop
✓ Expected: Mock GPIO17 setup followed by repeated HIGH/LOW changes; stop with Ctrl+C.
Checkpoint GPIO17 set up as OUT, LOW , then HIGH/LOW every 0.5 s. On WSL it works on any “Pi model”: the real library only works up to the Pi 4.

Experimental notebook

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

Optional physical acceptance · supervised low-voltage work

LED output 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: BCM17 (physical pin 11) → 330 Ω series resistor → LED anode; LED cathode → GND (physical pin 6). Disconnect power before wiring. Use a low-voltage LED only.

Procedure: With documented LED program held HIGH, measure GPIO17-to-GND DC voltage using a suitable high-impedance meter; verify LOW separately. Do not measure current by placing an ammeter across GPIO.

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/lab29/blink_gpiozero.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- gpiozero: blink in background
from gpiozero import LED
from signal import pause
 
led = LED(17)       # BCM 17, output
# Blink in the background:
# 0.5 s on, 0.5 s off.
led.blink(on_time=0.5, off_time=0.5)
pause()             # keep running
labs/python/lab29/led.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Import the LED class from gpiozero.
from gpiozero import LED
 
# ---- Create an LED object on BCM pin 17.
led = LED(17)
 
# ---- Turn the LED on.
led.on()
 
# ---- Wait until the user presses Enter.
input("LED is on. Press Enter to turn it off... ")
 
# ---- Turn the LED off.
led.off()
labs/python/lab29/legacy_rpigpio_pi4_only.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Blink until Ctrl+C; finally always cleans up the pins
import RPi.GPIO as GPIO
import time
 
LED = 17                       # BCM number (header pin 11)
 
GPIO.setmode(GPIO.BCM)         # 1. numbering mode: Broadcom
GPIO.setwarnings(False)        # hide "channel already in use"
# 2. Mode of operation: output, starting LOW (LED off).
GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
 
try:
    while True:
        GPIO.output(LED, GPIO.HIGH)   # 3.3 V -> LED on
        time.sleep(0.5)
        GPIO.output(LED, GPIO.LOW)    # 0 V -> LED off
        time.sleep(0.5)
except KeyboardInterrupt:
    print("Stopped by the user")      # Ctrl+C lands here
finally:
    # Always runs: pins go back to safe inputs.
    GPIO.cleanup()
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

P29 · 9 notebook cells · 3 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
# P29 · Lab 29 · GPIO output · LED **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose BCM17 (physical pin 11) is a digital output. HIGH is nominally 3.3 V, LOW is 0 V. A series resistor limits LED current: \(I=\frac{\max(0,V_{\mathrm{out}}-V_f)}{R}\); resistor power = \(I^2R\). The virtual clock advances without waiting; it cannot measure a physical pin. **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
# =====================================================================
# P29 | Code cell 01 | Lab 29 · GPIO output · LED
# 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 PIN for the next computation or reference condition.
PIN = 17                 # BCM numbering; physical header pin 11
# Set (V_HIGH, V_F) for the next computation or reference condition.
V_HIGH, V_F = 3.3, 2.0    # Nominal output and assumed red LED forward voltage (V)
# Set R for the next computation or reference condition.
R = 330                  # Ohms: limits current through the series circuit

# Ideal LED current; a LOW output cannot forward-bias this LED.
def current_ma(level, resistance):
    """Ideal LED current; a LOW output cannot forward-bias this LED."""
    if level not in (0, 1) or resistance <= 0:
        raise ValueError('Use digital 0/1 and positive resistance')
    return 1000 * max(0, level * V_HIGH - V_F) / resistance

# Return a bounded sequence of timestamped GPIO17 output states.
def blink(cycles, half_period, resistance):
    """Return a bounded sequence of timestamped GPIO17 output states."""
    if cycles < 1 or half_period <= 0:
        raise ValueError('Positive cycles and timing required')
    rows = []
    for step in range(2 * cycles):
        level = 1 - step % 2  # Alternate HIGH and LOW, starting HIGH
        rows.append((round(step * half_period, 3), level, current_ma(level, resistance)))
    return rows
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P29 | Code cell 02 | Lab 29 · GPIO output · LED
# 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.
# =====================================================================
# Set trace for the next computation or reference condition.
trace = blink(3, 0.5, R)
print('time_s | GPIO17 | ideal_current_mA')
# Repeat the same operation for each configured input so observations are comparable.
for t, level, ma in trace:
    print(f'{t:5.1f} | {level} | {ma:.3f}')
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert [row[1] for row in trace] == [1,0,1,0,1,0]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert current_ma(0,R) == 0
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## 3. Compare the controlled conditions
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# P29 | Code cell 03 | Lab 29 · GPIO output · LED
# Purpose: 3. Compare the controlled conditions
# 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 resistance in (330, 470, 1000):
    ma = current_ma(1, resistance)
    print(f'{resistance} ohm: {ma:.3f} mA; resistor power {ma**2 * resistance / 1000:.3f} mW')
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert current_ma(1,1000) < current_ma(1,330)
Ask Dr. Mohammad about this cell
08Instructions · 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 led.py ``` ```bash python blink_gpiozero.py # Ctrl+C to stop ``` ```bash python legacy_rpigpio_pi4_only.py # Ctrl+C to stop ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- gpiozero: blink in background from gpiozero import LED from signal import pause led = LED(17) # BCM 17, output # Blink in the background: # 0.5 s on, 0.5 s off. led.blink(on_time=0.5, off_time=0.5) pause() # keep running ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Import the LED class from gpiozero. from gpiozero import LED # ---- Create an LED object on BCM pin 17. led = LED(17) # ---- Turn the LED on. led.on() # ---- Wait until the user presses Enter. input("LED is on. Press Enter to turn it off... ") # ---- Turn the LED off. led.off() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Blink until Ctrl+C; finally always cleans up the pins import RPi.GPIO as GPIO import time LED = 17 # BCM number (header pin 11) GPIO.setmode(GPIO.BCM) # 1. numbering mode: Broadcom GPIO.setwarnings(False) # hide "channel already in use" # 2. Mode of operation: output, starting LOW (LED off). GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW) try: while True: GPIO.output(LED, GPIO.HIGH) # 3.3 V -> LED on time.sleep(0.5) GPIO.output(LED, GPIO.LOW) # 0 V -> LED off time.sleep(0.5) except KeyboardInterrupt: print("Stopped by the user") # Ctrl+C lands here finally: # Always runs: pins go back to safe inputs. GPIO.cleanup() ```
09Instructions · Markdown
## Independent investigation and submission Keep supply, forward voltage and timing fixed; predict current at 220 Ω and 660 Ω, then add those values to the final loop. Record current, resistor power and HIGH/LOW trace; explain why this is not a physical drive-rating test. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.