Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home/WSL Laboratories/Lab 35 · Pi ↔ Arduino · USB serial LED control
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P35
IoT Programming and Applications

Lab 35 · Pi ↔ Arduino · USB serial LED control

Ask Dr. Mohammad · P35 →

Use Wokwi Arduino serial forwarding to control the onboard LED from WSL Python.

Design experiment & verify evidence →
P35 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP35 · Pi ↔ Arduino · USB serial LED control
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Networking and Communication — same laboratory, notebook and completion record.

P35 · Academic orientation

Scope and objectives

Scope of the experiment

Translate typed on/off into the exact H/L bytes in pi_led_control.py; calculate 8N1 wire time and update Arduino pin 13.

The focus of this experiment is to trace a USB serial command from Raspberry Pi to Arduino LED logic. Students then interpret baud rate, line framing and command recognition, and diagnose disconnected, malformed or mismatched serial configurations. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace a USB serial command from Raspberry Pi to Arduino LED logic.
  • Interpret baud rate, line framing and command recognition.
  • Diagnose disconnected, malformed or mismatched serial configurations.
  • Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace a USB serial command from Raspberry Pi to Arduino LED logic, interpret baud rate, line framing and command recognition, and diagnose disconnected, malformed or mismatched serial configurations.

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 diagnose disconnected, malformed or mismatched serial configurations. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 36 · Arduino telemetry, CSV and ThingSpeak.

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.

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

Build before starting Wokwi. Keep only one serial client on port 4000; stop the simulator/client before the fallback. The virtual cable is an alternative, not a second simultaneous method.

CONCEPTS / ACTIVE RECALL

Understand the experiment

UART 8N1 · ASCII H and L

Idle HIGH, start LOW, 8 data bits least significant bit first, stop HIGH
Idle HIGH, start LOW, 8 data bits least significant bit first, stop HIGH

Scientific architecture · Raspberry Pi → Arduino serial LED control

UART single-byte LED command — Pi serial client; Arduino Uno; GPIO LED; Send H byte / 0>1; Set output HIGH / 1>2; Send L byte / 0>1; Set output LOW / 1>2
Scientific concept map: Raspberry Pi — Send H or L; USB serial — UART byte stream; Arduino Uno — Decode command; GPIO output — LED HIGH / LOW; Response evidence — Command and LED state.

Scientific foundations and analytical reasoning

UART 8N1 encodes a byte with a start bit, eight LSB-first data bits and a stop bit. Sender/receiver baud must agree; H and L are the actual command bytes.

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 · Serial framing and command bytes

UART 8N1 sends a low start bit, eight data bits least-significant first and a high stop bit. Baud is the symbol rate, equal to bit rate for this binary waveform. A USB serial bridge presents the port to the host; the Arduino parser expects H and L bytes in this lab. Both ends must agree on framing and baud.

Worked example and engineering interpretation

ASCII H is 0x48 = 01001000 in most-significant-first notation; its transmitted data-bit order is 0,0,0,1,0,0,1,0. At 9600 baud a ten-bit 8N1 frame occupies about 1.042 ms. Compare a correct command and an unrelated byte.

Engineering principles · additional worked teaching example

UART 8N1 sends one start bit, eight data bits least-significant first and one stop bit; at 19200 baud a ten-bit frame takes 10/19200=0.5208 ms. Byte framing is separate from a command parser; USB serial may present a virtual port.

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 35 · Pi ↔ Arduino · USB serial LED control

The Pi controller sends ASCII H or L over USB serial to the Arduino; the Arduino changes its LED state. The default 8N1 UART frame model has 10 bits per byte. A command model is not a physical USB link.

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: Build the Arduino serial exercise and verify serial LED control.

  1. Select H, 9600 baud at both ends and enable connection. Step and inspect 8N1 bits and LED state.
  2. Send L and X separately; record state.
  3. Set receiver baud to 19200; send H. Restore matching baud and repeat. Calculate bit duration.
  4. Use the original Arduino sketch and Pi controller; confirm port and close competing serial programs.

Reference check:

Model boundary:

Independent task and submission evidence

Keep the command sequence fixed and compare 9600 versus 19200 baud in the frame model. Record transmitted byte, LED state and frame duration; explain why both physical endpoints must use compatible settings.

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: Typed commands separated by ; = on;off;ON;bad; Pi serial baud = 9600; Arduino baud = 9600; Serial link open = true; Initial LED = OFF. In the classroom model, Sent bytes = 3; Accepted commands = 3; Final LED = ON; 8N1 wire time = 3.125 ms. The Pi sends one ASCII H/L byte, not a newline-delimited command. USB/RFC2217 transport delays are excluded. 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 35 · Pi ↔ Arduino · USB serial LED control: independent state notebook1234Calculated state 1Command #1TypedonTransmitted byteH / 0x48Receiver resultAppliedPin 13 LEDON

Step 1 of 4 · Calculated state 1

Calculated state 1

Command #
1
Typed
on
Transmitted byte
H / 0x48
Receiver result
Applied
Pin 13 LED
ON

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P35 · 01 / 08What is RFC2217?Reveal explanation
Engineering explanation

Serial-port control and data transported over a TCP connection.

P35 · 02 / 08What does H/L mean?Reveal explanation
Engineering explanation

The supplied Arduino firmware controls its LED using these serial characters.

P35 · 03 / 08Why choose one Wokwi or virtual-serial route rather than connect both clients?Reveal explanation
Engineering explanation

Build before starting Wokwi. Keep only one serial client on port 4000; stop the simulator/client before the fallback. The virtual cable is an alternative, not a second simultaneous method.

P35 · 04 / 08Why match serial baud rates on both ends?Reveal explanation
Engineering reasoning

Different symbol timings cause framing/decoding errors and corrupt command interpretation.

P35 · 05 / 08Why verify the selected USB serial device?Reveal explanation
Engineering reasoning

The port must refer to the intended controller; a WSL substitute or inaccessible port does not prove Arduino communication.

P35 · 06 / 08A Pi sends LED commands over USB serial. Select every technically valid statement. A. Both endpoints must agree on the serial settings. B. A command and its observed output are separate verification steps. C. USB serial always uses the MQTT protocol. D. A correct baud rate proves the LED is physically wired.Reveal explanation
Applied scenario

Correct: A. Both endpoints must agree on the serial settings.; B. A command and its observed output are separate verification steps.

P35 · 07 / 08In Pi ↔ Arduino · USB serial LED control, which command or code executes Terminal C — original serial route?Reveal explanation
Implementation recall

source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab35 export SERIAL_PORT=/tmp/psut-pi-serial python pi_led_control.py

P35 · 08 / 08For Pi ↔ Arduino · USB serial LED control, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Choose exactly one route. Wokwi: open the provided uno-led-serial folder in Windows VS Code, build with PlatformIO, start Wokwi, confirm RFC2217 port 4000, then open the Python client. Type on/off at its prompt. Confirm LED state in Wokwi, not just the client prompt. Alternative: start arduino_link.sh, keep it running, start fake_arduino.py led in a separate activated terminal, then open the client with /tmp/psut-pi-serial. Stop all three only when done.

Execution boundary · Real serial + real or fake Arduino. 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.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research

Live experimental workstations

Loading experiment-specific apparatus…
Previous model / additional reference tools
Simulation task

Build the Arduino serial exercise and verify serial LED control.

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 workbenchP35 · 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
Arduino onboard LEDD13Onboard LED, no external wire; serial H/L commandswokwi/uno-led-serial/diagram.json
P35 · 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

P35 · 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 35 · Pi ↔ Arduino · USB serial LED control

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Run & verify — acceptance checklist

Build verification: Source/firmware reviewed; actual serial and Wokwi pending.

Choose exactly one route. Wokwi: open the provided uno-led-serial folder in Windows VS Code, build with PlatformIO, start Wokwi, confirm RFC2217 port 4000, then open the Python client. Type on/off at its prompt. Confirm LED state in Wokwi, not just the client prompt. Alternative: start arduino_link.sh, keep it running, start fake_arduino.py led in a separate activated terminal, then open the client with /tmp/psut-pi-serial. Stop all three only when done.

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

Write the 8N1 frames for ASCII H (0x48) and L (0x4C). Calculate frame duration at 9600 baud.

02 · Compare or justify using evidence

Predict LED states for H;L;H;X according to the actual Arduino single-byte parser (initial LED OFF). Explain why mismatched baud does not guarantee valid decoding.

03 · Protocol tracing

Protocol tracing · Independent work

Write the 8N1 logical frame for ASCII 'A' (0x41) at 4800 baud. What happens if sender and receiver use different baud rates?

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

Use the reference configuration (Typed commands separated by ; = on;off;ON;bad; Pi serial baud = 9600; Arduino baud = 9600; Serial link open = true; Initial LED = OFF), but change Pi serial baud = 9602. The model reports Accepted commands = 0. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P35-02

Two model observations of Accepted commands are 3 (reference) and 0 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · P35-03

For Arduino baud = 9602, the model supplies this excerpt from Command and LED trace: Command # · Typed · Transmitted byte · Receiver result · Pin 13 LED 1 · on · H / 0x48 · Baud mismatch · OFF 2 · off · L / 0x4c · Baud mismatch · OFF 3 · ON · H / 0x48 · Baud mismatch · OFF 4 · bad · — · Invalid input · OFF Count rows whose Typed value is exactly “on”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · P35-04

An observation is Accepted commands = 0. Candidate A uses Typed commands separated by ; = on;off;ON;bad; Pi serial baud = 9600; Arduino baud = 9600; Serial link open = true; Initial LED = OFF. Candidate B changes the listed settings (Arduino baud = 9602) 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 · P35-05

A student configures Arduino baud = 19200 while preserving all other reference settings, but copies the reference report of Accepted commands = 3. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P35-06

Design a controlled comparison for Lab 35 · Pi ↔ Arduino · USB serial LED control using reference Typed commands separated by ; = on;off;ON;bad; Pi serial baud = 9600; Arduino baud = 9600; Serial link open = true; Initial LED = OFF and test Pi serial baud = 9602. Specify the changed setting(s), measured metric Accepted commands, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · Serial LED control

Perform these controlled trials before the existing practical experiment. Independent workstations have separate state.

  1. Select H, 9600 baud at both ends and enable connection. Step and inspect 8N1 bits and LED state.
  2. Send L and X separately; record state.
  3. Set receiver baud to 19200; send H. Restore matching baud and repeat. Calculate bit duration.
  4. Use the original Arduino sketch and Pi controller; confirm port and close competing serial programs.

Evidence

Record initial settings, actual observations, one failure and a restored condition. Compare calculated values with the practical run; distinguish virtual and physical/cloud evidence.

Step-by-step experimental procedure

Translate typed on/off into the exact H/L bytes in pi_led_control.py; calculate 8N1 wire time and update Arduino pin 13.

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.

Typed commands separated by ;on;off;ON;bad
Pi serial baud9600
Arduino baud9600
Serial link openYes
Initial LEDOFF

2 · Perform the investigation in order

  1. Run on;off;ON;bad at 9600 baud. The Python function lowercases each command and sends ASCII H (0x48) or L (0x4c); invalid text sends nothing.
  2. Step through individual bytes. Check Arduino pin 13 after each byte, and calculate 10 wire bits per byte for the UART 8N1 approximation.
  3. Change Arduino baud to 19200 while Pi remains at 9600. The model assumes no correctly decoded commands; real mismatch behavior may be corrupted bytes.
  4. Open the Wokwi Arduino Uno serial project. Set SERIAL_PORT to the actual Wokwi RFC2217 endpoint or a physical serial device, run pi_led_control.py, and type on/off. No newline framing or Arduino acknowledgement is implemented by that source.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
ReferenceUse reference inputs aboveSent bytes: 3; Accepted commands: 3; Final LED: ONRecord actual result
Baud mismatchArduino baud = 19200Accepted commands: 0Record actual result
Invalid commandTyped commands separated by ; = badSent bytes: 0Record actual result
DisconnectedSerial link open = NoSent bytes: 0Record actual result

4 · Analyze and report

Separate typed commands, encoded bytes, serial transport and LED output. A valid sent byte is not proof of real delivery.

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.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Actual Linux pseudo-terminal byte exchange, virtual Arduino GPIO, acknowledgements and telemetry; no USB hardware. 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 the Wokwi project in a separate Windows VS Code window
  2. Build and start the simulator
  3. Check Windows serial forwarding
  4. Run the Python serial client
  5. Stop the serial session
  6. Fallback when RFC2217 is unavailable
  7. Terminal B — virtual Arduino
  8. Terminal C — original serial route
02 / Implement

Step-by-step instructions

Before you run / verification gate

Build before starting Wokwi. Keep only one serial client on port 4000; stop the simulator/client before the fallback. The virtual cable is an alternative, not a second simultaneous method.

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 the Wokwi project in a separate Windows VS Code window

Use File → Open Folder in a local Windows window, not a Remote WSL window. Open the project folder listed below (inside the extracted website). Install PlatformIO IDE and Wokwi Simulator extensions. Activate Wokwi if prompted.

Folder path · Windows Explorer
psut-wsl/wokwi/uno-led-serial
✓ Expected: Open this folder in Windows VS Code; platformio.ini, wokwi.toml, diagram.json and src/main.cpp should be present. This is a path, not a shell command.
Checkpoint The project root contains platformio.ini, wokwi.toml, diagram.json and src/main.cpp.
02

Build and start the simulator

Use PlatformIO: Build (checkmark in the status bar). Then press Ctrl+Shift+P → Wokwi: Start Simulator. Keep the simulator visible. Wokwi does not compile the firmware.

Checkpoint Build SUCCESS; the virtual board is visible. Serial forwarding listens on port 4000. Do not open a second serial client.
03

Check Windows serial forwarding

While Wokwi is running, check that port 4000 is listening. Keep the simulator visible.

Windows PowerShell
Test-NetConnection localhost -Port 4000
✓ Expected: Look for TcpTestSucceeded : True for the specified port. This proves TCP reachability only.
Checkpoint TcpTestSucceeded: True.
04

Run the Python serial client

In the WSL VS Code window use RFC2217. Under mirrored networking, Windows localhost is reachable from WSL. In NAT mode, use the three-terminal virtual cable fallback below if localhost is unreachable.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab35
export SERIAL_PORT=rfc2217://127.0.0.1:4000
python pi_led_control.py
✓ Expected: The serial client accepts on/off commands; verify the LED state in Wokwi or the virtual Arduino fallback.
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/lab35Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. export SERIAL_PORT=rfc2217://127.0.0.1:4000Usually silent. The variable is inherited by child processes launched from this terminal; never print a secret to verify it.
  4. python pi_led_control.pyThe serial client accepts on/off commands; verify the LED state in Wokwi or the virtual Arduino fallback.
Checkpoint Type on and off (not blink) and watch the Uno LED.
05

Stop the serial session

Press Ctrl+C before closing Wokwi. Only one serial client at a time.

Checkpoint Complete the action before continuing.
06

Fallback when RFC2217 is unavailable

Use the original virtual cable instead of Wokwi, in three WSL terminals. Do not run both serial routes at once.

WSL · Bash
bash ~/psut-wsl/tools/arduino_link.sh
✓ Expected: The local serial link is prepared; keep this terminal running while the virtual Arduino and Python client connect.
Checkpoint Terminal A stays open.
07

Terminal B — virtual Arduino

Keep running.

WSL · Bash
source ~/psut-wsl/activate.sh
python ~/psut-wsl/tools/fake_arduino.py led
✓ Expected: The virtual Arduino starts and waits or emits simulated telemetry according to the selected mode. Keep it running.
Expected result for each action (2)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. python ~/psut-wsl/tools/fake_arduino.py ledThe virtual Arduino starts and waits or emits simulated telemetry according to the selected mode. Keep it running.
Checkpoint Virtual Arduino is ready.
08

Terminal C — original serial route

Run client in a third terminal.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab35
export SERIAL_PORT=/tmp/psut-pi-serial
python pi_led_control.py
✓ Expected: The serial client accepts on/off commands; verify the LED state in Wokwi or the virtual Arduino fallback.
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/lab35Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. export SERIAL_PORT=/tmp/psut-pi-serialUsually silent. The variable is inherited by child processes launched from this terminal; never print a secret to verify it.
  4. python pi_led_control.pyThe serial client accepts on/off commands; verify the LED state in Wokwi or the virtual Arduino fallback.
Checkpoint Same application protocol; no Wokwi firmware is running in this fallback.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab35/led_control.inoDownload source
INO · source file
// ------------------------------------------------------------
// Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
// PSUT IoT Engineering Learning Platform
// ------------------------------------------------------------
// ---- Store the pin number of the LED.
int ledPin = 13;                    // on-board LED pin
 
void setup() {                      // runs once at start
  // Configure the LED pin as an output.
  pinMode(ledPin, OUTPUT);          // LED pin = output
 
  // Start serial communication at 9600 bits per second.
  Serial.begin(9600);               // same baud rate as the Pi
}
 
void loop() {                       // repeats forever
  // ---- Check whether data has arrived from the Raspberry Pi.
  if (Serial.available() > 0) {
    // Read one incoming character.
    char received = Serial.read();  // one byte, e.g. 'H'
 
    // If the command is H, turn the LED on.
    if (received == 'H') {
      digitalWrite(ledPin, HIGH);   // LED on
    }
    // If the command is L, turn the LED off.
    else if (received == 'L') {
      digitalWrite(ledPin, LOW);    // LED off
    }
  }
}
labs/python/lab35/pi_led_control.pyDownload source
PY · source file
import os
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Import the serial and time modules.
import serial
import time
 
# ---- Open the Arduino serial connection.
# Change the device name if your system uses a different one.
ser = serial.serial_for_url(os.getenv('SERIAL_PORT', '/dev/ttyACM0'), 9600)
time.sleep(2)   # the Uno resets when the port opens
 
# ---- Helper function that sends LED commands.
def toggle_led(command):
    # Normalise the user text.
    command = command.lower()
    if command == 'on':
        ser.write(b'H')       # H = LED on
    elif command == 'off':
        ser.write(b'L')       # L = LED off
    else:
        print("Invalid command. Use 'on' or 'off'.")

# ---- Main interactive loop (uses toggle_led from part 1).
try:
    while True:
        cmd = input("Enter 'on' or 'off': ")
        toggle_led(cmd)
        time.sleep(1)
except KeyboardInterrupt:
    # Close the serial connection safely.
    ser.close()
wokwi/uno-led-serial/diagram.jsonDownload source
JSON · source file
{
  "version": 1,
  "author": "PSUT IoT Learning Studio",
  "editor": "wokwi",
  "parts": [
    {
      "type": "wokwi-arduino-uno",
      "id": "board",
      "top": 0,
      "left": 0,
      "attrs": {}
    }
  ],
  "connections": []
}
wokwi/uno-led-serial/platformio.iniDownload source
INI · source file
[env:uno]
platform = atmelavr
board = uno
framework = arduino
monitor_speed = 9600
wokwi/uno-led-serial/src/main.cppDownload source
CPP · source file
#include <Arduino.h>
// ------------------------------------------------------------
// Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
// PSUT IoT Engineering Learning Platform
// ------------------------------------------------------------
// ---- Store the pin number of the LED.
int ledPin = 13;                    // on-board LED pin
 
void setup() {                      // runs once at start
  // Configure the LED pin as an output.
  pinMode(ledPin, OUTPUT);          // LED pin = output
 
  // Start serial communication at 9600 bits per second.
  Serial.begin(9600);               // same baud rate as the Pi
}
 
void loop() {                       // repeats forever
  // ---- Check whether data has arrived from the Raspberry Pi.
  if (Serial.available() > 0) {
    // Read one incoming character.
    char received = Serial.read();  // one byte, e.g. 'H'
 
    // If the command is H, turn the LED on.
    if (received == 'H') {
      digitalWrite(ledPin, HIGH);   // LED on
    }
    // If the command is L, turn the LED off.
    else if (received == 'L') {
      digitalWrite(ledPin, LOW);    // LED off
    }
  }
}
wokwi/uno-led-serial/wokwi.tomlDownload source
TOML · source file
[wokwi]
version = 1
firmware = ".pio/build/uno/firmware.hex"
elf = ".pio/build/uno/firmware.elf"
rfc2217ServerPort = 4000
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

P35 · 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
# P35 · Lab 35 · Pi ↔ Arduino · USB serial LED control **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose The Pi controller sends ASCII H or L over USB serial to the Arduino; the Arduino changes its LED state. The default 8N1 UART frame model has 10 bits per byte. A command model is not a physical USB link. **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
# =====================================================================
# P35 | Code cell 01 | Lab 35 · Pi ↔ Arduino · USB serial LED control
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation encode; keep its logic separate from the trial.
def encode(command):
    return {'on':b'H','off':b'L'}.get(command.strip().lower())
# Define the reusable operation receive; keep its logic separate from the trial.
def receive(payload, led):
    if payload==b'H': return True
    if payload==b'L': return False
    return led  # Invalid input leaves the previous output unchanged
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P35 | Code cell 02 | Lab 35 · Pi ↔ Arduino · USB serial LED control
# 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=False
# Repeat the same operation for each configured input so observations are comparable.
for command in ('on','off','ON','bad'):
    payload=encode(command)
    led=receive(payload,led)
    print(command,payload,led)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert encode('bad') is None and led is True
# Repeat the same operation for each configured input so observations are comparable.
for baud in (9600,19200): print(baud, '8N1 frame ms:',1000*10/baud)
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/lab35 export SERIAL_PORT=rfc2217://127.0.0.1:4000 python pi_led_control.py ``` ```bash source ~/psut-wsl/activate.sh python ~/psut-wsl/tools/fake_arduino.py led ``` ```bash source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/python/lab35 export SERIAL_PORT=/tmp/psut-pi-serial python pi_led_control.py ``` ```python import os # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Import the serial and time modules. import serial import time # ---- Open the Arduino serial connection. # Change the device name if your system uses a different one. ser = serial.serial_for_url(os.getenv('SERIAL_PORT', '/dev/ttyACM0'), 9600) time.sleep(2) # the Uno resets when the port opens # ---- Helper function that sends LED commands. def toggle_led(command): # Normalise the user text. command = command.lower() if command == 'on': ser.write(b'H') # H = LED on elif command == 'off': ser.write(b'L') # L = LED off else: print("Invalid command. Use 'on' or 'off'.") # ---- Main interactive loop (uses toggle_led from part 1). try: while True: cmd = input("Enter 'on' or 'off': ") toggle_led(cmd) time.sleep(1) except KeyboardInterrupt: # Close the serial connection safely. ser.close() ```
07Instructions · Markdown
## Independent investigation and submission Keep the command sequence fixed and compare 9600 versus 19200 baud in the frame model. Record transmitted byte, LED state and frame duration; explain why both physical endpoints must use compatible settings. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.