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()
```