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 41 · LED control class with a mock GPIO
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P41
IoT Programming and Applications

Lab 41 · LED control class with a mock GPIO

Ask Dr. Mohammad · P41 →

This lab already uses its own MockGPIO class, so it runs on WSL with no fake Pi at all.

Design experiment & verify evidence →
P41 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP41 · LED control class with a mock GPIO
Readiness checksRevision deckEngineering workspaceRecord evidence
P41 · Academic orientation

Scope and objectives

Scope of the experiment

Exercise a virtual LED object through on/off/toggle/close operations.

The focus of this experiment is to explain object construction, attributes and LED methods using mock GPIO. Students then predict state and side effects of sequential method calls, and verify reusable behavior independently of physical pin access. 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

  • Explain object construction, attributes and LED methods using mock GPIO.
  • Predict state and side effects of sequential method calls.
  • Verify reusable behavior independently of physical pin access.
  • Identify the configured inputs (Method calls; Initial output on) 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 explain object construction, attributes and LED methods using mock GPIO, predict state and side effects of sequential method calls, and verify reusable behavior independently of physical pin access.

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 reusable behavior independently of physical pin access. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 42 · IoT time-series data with InfluxDB.

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.

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

Run the repaired tests in the same activated lab directory; record actual exit status and assertions. Do not equate mock test success with real GPIO validation.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Mock GPIO object state and lifecycle

GPIO object lifecycle — Construct mock pin / direction=output; on() / value=1; off() / value=0; toggle() / value=1; close() / release resources
Scientific concept map: GPIO object — Mock interface; Constructor — Set initial state; Methods — on / off / toggle; State log — Observe each call; Cleanup — Release virtual GPIO.

Scientific foundations and analytical reasoning

An object encapsulates state and methods; close terminates resource use and later calls should follow the documented lifecycle.

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 · Object-oriented device lifecycle

A class groups state and operations behind a defined interface. Instance state must remain independent across objects. Initializing, toggling and closing an output are state transitions, and cleanup should release resources. A mock records logical behavior without energizing physical hardware.

Worked example and engineering interpretation

Starting OFF, two toggle calls return the logical state to OFF. A close call changes the lifecycle even if the output was already off. Test separate instances and behavior after close according to the actual implementation; do not infer real GPIO timing from the mock.

Engineering principles · additional worked teaching example

An object owns state and exposes operations that preserve invariants. A GPIO mock isolates logical behavior from pin hardware. Calling on twice is idempotent for state; close should release resources and later operations must follow the defined closed-state policy.

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 41 · LED control class with a mock GPIO

An LED class encapsulates pin, state and cleanup. A mock GPIO adapter records output transitions without hardware. Toggle reverses state; cleanup makes the object unusable for further writes.

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: Use classes and tests to verify reusable GPIO behavior.

  1. Trace the reference sequence and record state after every method.
  2. Select close;on and identify the rejected use-after-close call.
  3. Toggle twice and observe return to initial state.
  4. Use the actual mock GPIO Python class; inspect assertions and no physical voltage claims.

Reference check:

Model boundary:

Independent task and submission evidence

Compare three and four toggles from OFF, holding initial state fixed. Record trace and final state; verify cleanup prevents further output changes.

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: Method calls = on;toggle;on;close; Initial output on = false. In the classroom model, Final state = Closed; Rejected calls = 0. Software fixture only. 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 · independent state notebook

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 41 · LED control class with a mock GPIO: independent state notebook1234Calculated state 1MethodonResultOKStateON

Step 1 of 4 · Calculated state 1

Calculated state 1

Method
on
Result
OK
State
ON

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P41 · 01 / 08Why use a class?Reveal explanation
Engineering explanation

Encapsulate LED state and reusable behavior behind methods.

P41 · 02 / 08What do mock tests prove?Reveal explanation
Engineering explanation

The tested program logic, not an electrical circuit.

P41 · 03 / 08What does the GPIO class test require before interpreting the object lifecycle?Reveal explanation
Engineering explanation

Run the repaired tests in the same activated lab directory; record actual exit status and assertions. Do not equate mock test success with real GPIO validation.

P41 · 04 / 08Why use a mock GPIO class in automated testing?Reveal explanation
Engineering reasoning

It makes program behavior observable without hardware and permits reproducible state assertions.

P41 · 05 / 08What does a passing mock test not establish?Reveal explanation
Engineering reasoning

Physical pin voltage, LED current, electrical safety or behavior of the actual driver on a board.

P41 · 06 / 08A reusable mock GPIO class is tested. Select every technically valid statement. A. Tests can verify state transitions independently of hardware. B. Cleanup behavior is part of the class contract. C. Mock success proves pin electrical safety. D. One instance must always share all mutable state with another.Reveal explanation
Applied scenario

Correct: A. Tests can verify state transitions independently of hardware.; B. Cleanup behavior is part of the class contract.

P41 · 07 / 08In LED control class with a mock GPIO, which command or code executes Run the repaired example tests?Reveal explanation
Implementation recall

python test_toggle.py python test_pattern.py python test_pins.py

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

The mock classes print state changes. Run all five files separately. test_pattern.py intentionally reports Use only dot and dash; test_pins.py rejects GPIO30 under its accepted BCM2–27 range. Two GPIO17 creations may both be accepted; range checking is not an exclusive pin allocator. The traffic-light sample runs one short green/yellow/red cycle and cleans up.

Execution boundary · Real on WSL. 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.
GPIO object and output. Software state controls an electrical output.
GPIO object and output. Software state controls an electrical output.
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

Use classes and tests to verify reusable GPIO behavior.

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 workbenchP41 · 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
LED / redBCM GPIO17 · physical 11LED with current-limiting resistorlab41/led_mock_gpio.py
Yellow / greenBCM GPIO27 · physical 13 / GPIO22 · physical 15Traffic-light outputs; each LED needs resistorlab41/traffic_light_mock_gpio.py
P41 · 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

P41 · 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 41 · LED control class with a mock GPIO

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: Actual five OOP/mock GPIO programs executed.

The mock classes print state changes. Run all five files separately. test_pattern.py intentionally reports Use only dot and dash; test_pins.py rejects GPIO30 under its accepted BCM2–27 range. Two GPIO17 creations may both be accepted; range checking is not an exclusive pin allocator. The traffic-light sample runs one short green/yellow/red cycle and cleans up.

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

Trace on;toggle;on;close from initial OFF. Draw a transition table and identify the final closed state.

02 · Compare or justify using evidence

Propose assertions for idempotent on, toggle, and post-close behavior; distinguish mock state from electrical output.

03 · Code reasoning

Code reasoning · Independent work

Starting OFF, trace toggle, toggle, on, off, close. Propose a unit test for an operation after close.

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

Use the reference configuration (Method calls = on;toggle;on;close; Initial output on = false), but change Method calls = on;off;toggle. The model reports Final state = ON. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · P41-02

The reference model reports Final state: Closed. Under Method calls = on;off;toggle it reports ON. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

Intermediate · Interpret a technical trace

Independent theoretical exercise · P41-03

For Method calls = close;on, the model supplies this excerpt from Object lifecycle: Method · Result · State close · OK · Closed on · Rejected: closed · Closed Count rows whose Result value is exactly “OK”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · P41-04

An observation is Rejected calls = 1. Candidate A uses Method calls = on;toggle;on;close; Initial output on = false. Candidate B changes the listed settings (Method calls = close;on) 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 · P41-05

A student configures Method calls = close;on while preserving all other reference settings, but copies the reference report of Rejected calls = 0. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P41-06

Design a controlled comparison for Lab 41 · LED control class with a mock GPIO using reference Method calls = on;toggle;on;close; Initial output on = false and test Method calls = on;off;toggle. Specify the changed setting(s), measured metric Final state, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Exercise a virtual LED object through on/off/toggle/close operations.

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.

Method callson;toggle;on;close
Initial output onNo

2 · Perform the investigation in order

  1. Trace the reference sequence and record state after every method.
  2. Select close;on and identify the rejected use-after-close call.
  3. Toggle twice and observe return to initial state.
  4. Use the actual mock GPIO Python class; inspect assertions and no physical voltage claims.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
LifecycleUse reference inputs aboveFinal state: ClosedRecord actual result
Use after closeMethod calls = close;onRejected calls: 1Record actual result

4 · Analyze and report

A mock tests software state, not electrical output.

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
LifecycleUse reference inputs aboveRecord actual outcome and units
Use after closeMethod calls = close;onRecord 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

Original mock GPIO unit tests. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Run LED and traffic light examples
  2. Run the repaired example tests
02 / Implement

Step-by-step instructions

Before you run / verification gate

Run the repaired tests in the same activated lab directory; record actual exit status and assertions. Do not equate mock test success with real GPIO validation.

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

Run LED and traffic light examples

Observe the mock GPIO transitions.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab41
python led_mock_gpio.py
python traffic_light_mock_gpio.py
✓ Expected: LED and traffic-light state changes; Ctrl+C if needed.
Expected result for each action (4)
  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/lab41Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. python led_mock_gpio.pyLED and traffic-light state changes; Ctrl+C if needed.
  4. python traffic_light_mock_gpio.pyLED and traffic-light state changes; Ctrl+C if needed.
Checkpoint LED and traffic-light state changes; Ctrl+C if needed.
02

Run the repaired example tests

Run these as scripts, not Python expressions. The pattern method and imports have been added.

WSL · Bash
python test_toggle.py
python test_pattern.py
python test_pins.py
✓ Expected: The corresponding test program reports its checks and returns; investigate any failed assertion or error.
Expected result for each action (3)
  1. python test_toggle.pyThe corresponding test program reports its checks and returns; investigate any failed assertion or error.
  2. python test_pattern.pyThe corresponding test program reports its checks and returns; investigate any failed assertion or error.
  3. python test_pins.pyThe corresponding test program reports its checks and returns; investigate any failed assertion or error.
Checkpoint Toggle output, dot/dash flashes, deliberate invalid-pin/pattern errors. GPIO30 is invalid; repeated GPIO17 is accepted by this simple mock factory.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab41/led_mock_gpio.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Exercise: an LED control class on Raspberry Pi, tested with a mock GPIO
# Runs anywhere (Google Colab, a laptop, the Pi itself). On a real Raspberry Pi,
# delete the MockGPIO class and write:  import RPi.GPIO as GPIO

import time                         # time.sleep() for the blink timing


# ---- Mock RPi.GPIO: prints every call instead of driving real hardware
class MockGPIO:
    """Stand-in for the RPi.GPIO library, so the class can be tested without a Pi."""
    BCM = 'BCM'                     # numbering mode: Broadcom GPIO numbers (GPIO17)
    OUT = 'OUT'                     # pin direction: output
    HIGH = True                     # logic 1 → 3.3 V on the pin → LED on
    LOW = False                     # logic 0 → 0 V on the pin → LED off

    @staticmethod
    def setmode(mode):
        """Choose the pin numbering scheme (here BCM)."""
        print(f"GPIO mode set to {mode}")

    @staticmethod
    def setup(pin, mode):
        """Configure one pin as input or output."""
        print(f"GPIO pin {pin} set up as {mode}")

    @staticmethod
    def output(pin, state):
        """Drive an output pin HIGH or LOW."""
        print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}")

    @staticmethod
    def cleanup():
        """Release every pin the program used (back to safe inputs)."""
        print("GPIO cleanup")


GPIO = MockGPIO                     # on a real Pi: import RPi.GPIO as GPIO


# ---- The LED class: one object = one LED on one GPIO pin
class LED:
    """Control an LED connected (through a resistor) to one GPIO pin."""

    def __init__(self, pin: int) -> None:
        """Set the pin up as an output and start with the LED OFF."""
        self.pin = pin                          # remember which pin this LED uses
        GPIO.setmode(GPIO.BCM)                  # use BCM (GPIO) numbers, not header numbers
        GPIO.setup(self.pin, GPIO.OUT)          # the pin drives the LED → output
        self.state = GPIO.LOW                   # the object keeps the current state
        GPIO.output(self.pin, self.state)       # start OFF

    def __repr__(self) -> str:
        """Developer view, e.g. in a list or the interpreter: LED(pin=17, state=OFF)."""
        return f"LED(pin={self.pin}, state={'ON' if self.state == GPIO.HIGH else 'OFF'})"

    def __str__(self) -> str:
        """Readable view used by print(led)."""
        return f"LED on pin {self.pin} is {'ON' if self.state == GPIO.HIGH else 'OFF'}"

    # ---- Basic switching: update the stored state, then drive the pin
    def turn_on(self) -> None:
        """Switch the LED on (pin HIGH)."""
        self.state = GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def turn_off(self) -> None:
        """Switch the LED off (pin LOW)."""
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)

    def toggle(self) -> None:
        """Invert the state: ON becomes OFF and OFF becomes ON."""
        self.state = GPIO.LOW if self.state == GPIO.HIGH else GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def blink(self, times: int = 1, on_time: float = 0.5, off_time: float = 0.5) -> None:
        """Blink `times` times: on for on_time seconds, then off for off_time seconds."""
        for _ in range(times):
            self.turn_on()
            time.sleep(on_time)
            self.turn_off()
            time.sleep(off_time)

    # ---- Pin validation: belongs to the class, needs no object → @staticmethod
    @staticmethod
    def check_pin_availability(pin: int) -> bool:
        """True if the number is in the accepted range (BCM GPIO2–27)."""
        return isinstance(pin, int) and 2 <= pin <= 27

    # ---- Safe factory: build an LED only for a valid pin → @classmethod
    @classmethod
    def create_led(cls, pin: int) -> 'LED':
        """Return a new LED, or raise ValueError if the pin is not available."""
        if cls.check_pin_availability(pin):
            return cls(pin)
        else:
            raise ValueError("GPIO pin is not available")

    def pattern(self, symbols: str) -> None:
        """Dot = short flash, dash = long flash; reject invalid symbols first."""
        if not symbols or any(c not in '.-' for c in symbols):
            raise ValueError('Use only dot and dash')
        for c in symbols:
            self.blink(1, 0.15 if c == '.' else 0.45, 0.15)

    def cleanup(self) -> None:
        """Release the GPIO pins when the program ends."""
        GPIO.cleanup()


# ---- Main script: LED on GPIO17, print it, blink 3 times, always clean up
if __name__ == "__main__":
    led = None                                  # defined before try, so finally can test it
    try:
        led_pin = 17                            # BCM GPIO17 = physical header pin 11
        led = LED.create_led(led_pin)           # validated construction
        print(led)                              # __str__ → "LED on pin 17 is OFF"
        led.blink(3)                            # 3 × (0.5 s ON + 0.5 s OFF)
    finally:
        if led is not None:                     # cleanup only if the LED was created
            led.cleanup()                       # runs even if an error happened above
labs/python/lab41/test_pattern.pyDownload source
PY · source file
from led_mock_gpio import LED, GPIO
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
led = LED.create_led(17)
led.pattern("..-")
try:
    led.pattern(".x")
except ValueError as e:
    print("Error:", e)
led.cleanup()
labs/python/lab41/test_pins.pyDownload source
PY · source file
from led_mock_gpio import LED, GPIO
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
for pin in (17, 17, 30, 4):
    try:
        LED.create_led(pin)
        print(f"GPIO{pin} OK")
    except ValueError as e:
        print("Error:", e)
GPIO.cleanup()
labs/python/lab41/test_toggle.pyDownload source
PY · source file
from led_mock_gpio import LED, GPIO
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import time
led = LED.create_led(17)
for _ in range(5):
    led.toggle()
    time.sleep(0.3)
print(led)
led.cleanup()
labs/python/lab41/traffic_light_mock_gpio.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 2: a traffic light built from three LED objects (composition)
# Runs anywhere (Google Colab, a laptop, the Pi itself). On a real Raspberry Pi,
# delete the MockGPIO class and write:  import RPi.GPIO as GPIO

import time                         # time.sleep() for the blink timing


# ---- Mock RPi.GPIO: prints every call instead of driving real hardware
class MockGPIO:
    """Stand-in for the RPi.GPIO library, so the class can be tested without a Pi."""
    BCM = 'BCM'                     # numbering mode: Broadcom GPIO numbers (GPIO17)
    OUT = 'OUT'                     # pin direction: output
    HIGH = True                     # logic 1 → 3.3 V on the pin → LED on
    LOW = False                     # logic 0 → 0 V on the pin → LED off

    @staticmethod
    def setmode(mode):
        """Choose the pin numbering scheme (here BCM)."""
        print(f"GPIO mode set to {mode}")

    @staticmethod
    def setup(pin, mode):
        """Configure one pin as input or output."""
        print(f"GPIO pin {pin} set up as {mode}")

    @staticmethod
    def output(pin, state):
        """Drive an output pin HIGH or LOW."""
        print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}")

    @staticmethod
    def cleanup():
        """Release every pin the program used (back to safe inputs)."""
        print("GPIO cleanup")


GPIO = MockGPIO                     # on a real Pi: import RPi.GPIO as GPIO


# ---- The LED class: one object = one LED on one GPIO pin
class LED:
    """Control an LED connected (through a resistor) to one GPIO pin."""

    def __init__(self, pin: int) -> None:
        """Set the pin up as an output and start with the LED OFF."""
        self.pin = pin                          # remember which pin this LED uses
        GPIO.setmode(GPIO.BCM)                  # use BCM (GPIO) numbers, not header numbers
        GPIO.setup(self.pin, GPIO.OUT)          # the pin drives the LED → output
        self.state = GPIO.LOW                   # the object keeps the current state
        GPIO.output(self.pin, self.state)       # start OFF

    def __repr__(self) -> str:
        """Developer view, e.g. in a list or the interpreter: LED(pin=17, state=OFF)."""
        return f"LED(pin={self.pin}, state={'ON' if self.state == GPIO.HIGH else 'OFF'})"

    def __str__(self) -> str:
        """Readable view used by print(led)."""
        return f"LED on pin {self.pin} is {'ON' if self.state == GPIO.HIGH else 'OFF'}"

    # ---- Basic switching: update the stored state, then drive the pin
    def turn_on(self) -> None:
        """Switch the LED on (pin HIGH)."""
        self.state = GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def turn_off(self) -> None:
        """Switch the LED off (pin LOW)."""
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)

    def toggle(self) -> None:
        """Invert the state: ON becomes OFF and OFF becomes ON."""
        self.state = GPIO.LOW if self.state == GPIO.HIGH else GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def blink(self, times: int = 1, on_time: float = 0.5, off_time: float = 0.5) -> None:
        """Blink `times` times: on for on_time seconds, then off for off_time seconds."""
        for _ in range(times):
            self.turn_on()
            time.sleep(on_time)
            self.turn_off()
            time.sleep(off_time)

    # ---- Pin validation: belongs to the class, needs no object → @staticmethod
    @staticmethod
    def check_pin_availability(pin: int) -> bool:
        """True if the number is in the accepted range (simulation assumption: 1–40)."""
        return 1 <= pin <= 40

    # ---- Safe factory: build an LED only for a valid pin → @classmethod
    @classmethod
    def create_led(cls, pin: int) -> 'LED':
        """Return a new LED, or raise ValueError if the pin is not available."""
        if cls.check_pin_availability(pin):
            return cls(pin)
        else:
            raise ValueError("GPIO pin is not available")

    def cleanup(self) -> None:
        """Release the GPIO pins when the program ends."""
        GPIO.cleanup()



# ---- TrafficLight: one object that owns three LED objects
class TrafficLight:
    """Red, yellow and green LEDs controlled as one traffic light."""
    ORDER = ('green', 'yellow', 'red')          # the order of one full cycle

    def __init__(self, red_pin: int = 17, yellow_pin: int = 27, green_pin: int = 22) -> None:
        """Create the three LEDs (each one validated by LED.create_led)."""
        self.leds = {'red': LED.create_led(red_pin),       # composition: a TrafficLight
                     'yellow': LED.create_led(yellow_pin), # HAS three LEDs; it is not
                     'green': LED.create_led(green_pin)}   # itself an LED
        self.current = None                                 # no colour shown yet

    def __repr__(self) -> str:
        """Developer view: which pin each colour uses."""
        return (f"TrafficLight(red={self.leds['red'].pin}, "
                f"yellow={self.leds['yellow'].pin}, green={self.leds['green'].pin})")

    def __str__(self) -> str:
        """Readable view used by print()."""
        return f"Traffic light shows {self.current.upper() if self.current else 'nothing'}"

    # ---- Show exactly one colour: switch the old one off, the new one on
    def show(self, colour: str) -> None:
        """Light only `colour`; raise ValueError for an unknown colour."""
        if colour not in self.leds:
            raise ValueError(f"unknown colour: {colour}")
        if self.current:                                    # something is lit
            self.leds[self.current].turn_off()
        self.leds[colour].turn_on()
        self.current = colour

    def cycle(self, times: int = 1, green: float = 2.0, yellow: float = 0.5, red: float = 2.0) -> None:
        """Run green → yellow → red `times` times, holding each colour for its duration."""
        hold = {'green': green, 'yellow': yellow, 'red': red}
        for _ in range(times):
            for colour in self.ORDER:
                self.show(colour)
                print(self)                                 # __str__
                time.sleep(hold[colour])

    def cleanup(self) -> None:
        """Everything off, then release the pins."""
        for led in self.leds.values():
            led.turn_off()
        GPIO.cleanup()


# ---- Main script: one full cycle with short (demo) timings, always clean up
light = None
try:
    light = TrafficLight()                  # red GPIO17, yellow GPIO27, green GPIO22
    print(repr(light))                      # __repr__
    light.cycle(times=1, green=1.0, yellow=0.5, red=1.0)
finally:
    if light is not None:
        light.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

P41 · 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
# P41 · Lab 41 · LED control class with a mock GPIO **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose An LED class encapsulates pin, state and cleanup. A mock GPIO adapter records output transitions without hardware. Toggle reverses state; cleanup makes the object unusable for further writes. **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
# =====================================================================
# P41 | Code cell 01 | Lab 41 · LED control class with a mock GPIO
# 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.
# =====================================================================
# Encapsulate state and operations for LED; keep its logic separate from the trial.
class LED:
    def __init__(self,pin): self.pin=pin;self.state=False;self.closed=False;self.trace=[]
    def set(self,value):
        if self.closed: raise RuntimeError('GPIO cleaned up')
        self.state=bool(value);self.trace.append(self.state)
    def toggle(self): self.set(not self.state)
    def cleanup(self): self.set(False);self.closed=True
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P41 | Code cell 02 | Lab 41 · LED control class with a mock GPIO
# 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 led for the next computation or reference condition.
led=LED(17)
# Repeat the same operation for each configured input so observations are comparable.
for _ in range(5): led.toggle()
print(led.trace)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert led.trace==[True,False,True,False,True]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
led.cleanup();assert not led.state and led.closed
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 source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab41 python led_mock_gpio.py python traffic_light_mock_gpio.py ``` ```bash python test_toggle.py python test_pattern.py python test_pins.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Exercise: an LED control class on Raspberry Pi, tested with a mock GPIO # Runs anywhere (Google Colab, a laptop, the Pi itself). On a real Raspberry Pi, # delete the MockGPIO class and write: import RPi.GPIO as GPIO import time # time.sleep() for the blink timing # ---- Mock RPi.GPIO: prints every call instead of driving real hardware class MockGPIO: """Stand-in for the RPi.GPIO library, so the class can be tested without a Pi.""" BCM = 'BCM' # numbering mode: Broadcom GPIO numbers (GPIO17) OUT = 'OUT' # pin direction: output HIGH = True # logic 1 → 3.3 V on the pin → LED on LOW = False # logic 0 → 0 V on the pin → LED off @staticmethod def setmode(mode): """Choose the pin numbering scheme (here BCM).""" print(f"GPIO mode set to {mode}") @staticmethod def setup(pin, mode): """Configure one pin as input or output.""" print(f"GPIO pin {pin} set up as {mode}") @staticmethod def output(pin, state): """Drive an output pin HIGH or LOW.""" print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}") @staticmethod def cleanup(): """Release every pin the program used (back to safe inputs).""" print("GPIO cleanup") GPIO = MockGPIO # on a real Pi: import RPi.GPIO as GPIO # ---- The LED class: one object = one LED on one GPIO pin class LED: """Control an LED connected (through a resistor) to one GPIO pin.""" def __init__(self, pin: int) -> None: """Set the pin up as an output and start with the LED OFF.""" self.pin = pin # remember which pin this LED uses GPIO.setmode(GPIO.BCM) # use BCM (GPIO) numbers, not header numbers GPIO.setup(self.pin, GPIO.OUT) # the pin drives the LED → output self.state = GPIO.LOW # the object keeps the current state GPIO.output(self.pin, self.state) # start OFF def __repr__(self) -> str: """Developer view, e.g. in a list or the interpreter: LED(pin=17, state=OFF).""" return f"LED(pin={self.pin}, state={'ON' if self.state == GPIO.HIGH else 'OFF'})" def __str__(self) -> str: """Readable view used by print(led).""" return f"LED on pin {self.pin} is {'ON' if self.state == GPIO.HIGH else 'OFF'}" # ---- Basic switching: update the stored state, then drive the pin def turn_on(self) -> None: """Switch the LED on (pin HIGH).""" self.state = GPIO.HIGH GPIO.output(self.pin, self.state) def turn_off(self) -> None: """Switch the LED off (pin LOW).""" self.state = GPIO.LOW GPIO.output(self.pin, self.state) def toggle(self) -> None: """Invert the state: ON becomes OFF and OFF becomes ON.""" self.state = GPIO.LOW if self.state == GPIO.HIGH else GPIO.HIGH GPIO.output(self.pin, self.state) def blink(self, times: int = 1, on_time: float = 0.5, off_time: float = 0.5) -> None: """Blink `times` times: on for on_time seconds, then off for off_time seconds.""" for _ in range(times): self.turn_on() time.sleep(on_time) self.turn_off() time.sleep(off_time) # ---- Pin validation: belongs to the class, needs no object → @staticmethod @staticmethod def check_pin_availability(pin: int) -> bool: """True if the number is in the accepted range (BCM GPIO2–27).""" return isinstance(pin, int) and 2 <= pin <= 27 # ---- Safe factory: build an LED only for a valid pin → @classmethod @classmethod def create_led(cls, pin: int) -> 'LED': """Return a new LED, or raise ValueError if the pin is not available.""" if cls.check_pin_availability(pin): return cls(pin) else: raise ValueError("GPIO pin is not available") def pattern(self, symbols: str) -> None: """Dot = short flash, dash = long flash; reject invalid symbols first.""" if not symbols or any(c not in '.-' for c in symbols): raise ValueError('Use only dot and dash') for c in symbols: self.blink(1, 0.15 if c == '.' else 0.45, 0.15) def cleanup(self) -> None: """Release the GPIO pins when the program ends.""" GPIO.cleanup() # ---- Main script: LED on GPIO17, print it, blink 3 times, always clean up if __name__ == "__main__": led = None # defined before try, so finally can test it try: led_pin = 17 # BCM GPIO17 = physical header pin 11 led = LED.create_led(led_pin) # validated construction print(led) # __str__ → "LED on pin 17 is OFF" led.blink(3) # 3 × (0.5 s ON + 0.5 s OFF) finally: if led is not None: # cleanup only if the LED was created led.cleanup() # runs even if an error happened above ``` ```python from led_mock_gpio import LED, GPIO # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ led = LED.create_led(17) led.pattern("..-") try: led.pattern(".x") except ValueError as e: print("Error:", e) led.cleanup() ``` ```python from led_mock_gpio import LED, GPIO # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ for pin in (17, 17, 30, 4): try: LED.create_led(pin) print(f"GPIO{pin} OK") except ValueError as e: print("Error:", e) GPIO.cleanup() ``` ```python from led_mock_gpio import LED, GPIO # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ import time led = LED.create_led(17) for _ in range(5): led.toggle() time.sleep(0.3) print(led) led.cleanup() ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Example 2: a traffic light built from three LED objects (composition) # Runs anywhere (Google Colab, a laptop, the Pi itself). On a real Raspberry Pi, # delete the MockGPIO class and write: import RPi.GPIO as GPIO import time # time.sleep() for the blink timing # ---- Mock RPi.GPIO: prints every call instead of driving real hardware class MockGPIO: """Stand-in for the RPi.GPIO library, so the class can be tested without a Pi.""" BCM = 'BCM' # numbering mode: Broadcom GPIO numbers (GPIO17) OUT = 'OUT' # pin direction: output HIGH = True # logic 1 → 3.3 V on the pin → LED on LOW = False # logic 0 → 0 V on the pin → LED off @staticmethod def setmode(mode): """Choose the pin numbering scheme (here BCM).""" print(f"GPIO mode set to {mode}") @staticmethod def setup(pin, mode): """Configure one pin as input or output.""" print(f"GPIO pin {pin} set up as {mode}") @staticmethod def output(pin, state): """Drive an output pin HIGH or LOW.""" print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}") @staticmethod def cleanup(): """Release every pin the program used (back to safe inputs).""" print("GPIO cleanup") GPIO = MockGPIO # on a real Pi: import RPi.GPIO as GPIO # ---- The LED class: one object = one LED on one GPIO pin class LED: """Control an LED connected (through a resistor) to one GPIO pin.""" def __init__(self, pin: int) -> None: """Set the pin up as an output and start with the LED OFF.""" self.pin = pin # remember which pin this LED uses GPIO.setmode(GPIO.BCM) # use BCM (GPIO) numbers, not header numbers GPIO.setup(self.pin, GPIO.OUT) # the pin drives the LED → output self.state = GPIO.LOW # the object keeps the current state GPIO.output(self.pin, self.state) # start OFF def __repr__(self) -> str: """Developer view, e.g. in a list or the interpreter: LED(pin=17, state=OFF).""" return f"LED(pin={self.pin}, state={'ON' if self.state == GPIO.HIGH else 'OFF'})" def __str__(self) -> str: """Readable view used by print(led).""" return f"LED on pin {self.pin} is {'ON' if self.state == GPIO.HIGH else 'OFF'}" # ---- Basic switching: update the stored state, then drive the pin def turn_on(self) -> None: """Switch the LED on (pin HIGH).""" self.state = GPIO.HIGH GPIO.output(self.pin, self.state) def turn_off(self) -> None: """Switch the LED off (pin LOW).""" self.state = GPIO.LOW GPIO.output(self.pin, self.state) def toggle(self) -> None: """Invert the state: ON becomes OFF and OFF becomes ON.""" self.state = GPIO.LOW if self.state == GPIO.HIGH else GPIO.HIGH GPIO.output(self.pin, self.state) def blink(self, times: int = 1, on_time: float = 0.5, off_time: float = 0.5) -> None: """Blink `times` times: on for on_time seconds, then off for off_time seconds.""" for _ in range(times): self.turn_on() time.sleep(on_time) self.turn_off() time.sleep(off_time) # ---- Pin validation: belongs to the class, needs no object → @staticmethod @staticmethod def check_pin_availability(pin: int) -> bool: """True if the number is in the accepted range (simulation assumption: 1–40).""" return 1 <= pin <= 40 # ---- Safe factory: build an LED only for a valid pin → @classmethod @classmethod def create_led(cls, pin: int) -> 'LED': """Return a new LED, or raise ValueError if the pin is not available.""" if cls.check_pin_availability(pin): return cls(pin) else: raise ValueError("GPIO pin is not available") def cleanup(self) -> None: """Release the GPIO pins when the program ends.""" GPIO.cleanup() # ---- TrafficLight: one object that owns three LED objects class TrafficLight: """Red, yellow and green LEDs controlled as one traffic light.""" ORDER = ('green', 'yellow', 'red') # the order of one full cycle def __init__(self, red_pin: int = 17, yellow_pin: int = 27, green_pin: int = 22) -> None: """Create the three LEDs (each one validated by LED.create_led).""" self.leds = {'red': LED.create_led(red_pin), # composition: a TrafficLight 'yellow': LED.create_led(yellow_pin), # HAS three LEDs; it is not 'green': LED.create_led(green_pin)} # itself an LED self.current = None # no colour shown yet def __repr__(self) -> str: """Developer view: which pin each colour uses.""" return (f"TrafficLight(red={self.leds['red'].pin}, " f"yellow={self.leds['yellow'].pin}, green={self.leds['green'].pin})") def __str__(self) -> str: """Readable view used by print().""" return f"Traffic light shows {self.current.upper() if self.current else 'nothing'}" # ---- Show exactly one colour: switch the old one off, the new one on def show(self, colour: str) -> None: """Light only `colour`; raise ValueError for an unknown colour.""" if colour not in self.leds: raise ValueError(f"unknown colour: {colour}") if self.current: # something is lit self.leds[self.current].turn_off() self.leds[colour].turn_on() self.current = colour def cycle(self, times: int = 1, green: float = 2.0, yellow: float = 0.5, red: float = 2.0) -> None: """Run green → yellow → red `times` times, holding each colour for its duration.""" hold = {'green': green, 'yellow': yellow, 'red': red} for _ in range(times): for colour in self.ORDER: self.show(colour) print(self) # __str__ time.sleep(hold[colour]) def cleanup(self) -> None: """Everything off, then release the pins.""" for led in self.leds.values(): led.turn_off() GPIO.cleanup() # ---- Main script: one full cycle with short (demo) timings, always clean up light = None try: light = TrafficLight() # red GPIO17, yellow GPIO27, green GPIO22 print(repr(light)) # __repr__ light.cycle(times=1, green=1.0, yellow=0.5, red=1.0) finally: if light is not None: light.cleanup() ```
07Instructions · Markdown
## Independent investigation and submission Compare three and four toggles from OFF, holding initial state fixed. Record trace and final state; verify cleanup prevents further output changes. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.