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 36 · Arduino telemetry, CSV and ThingSpeak
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P36
IoT Programming and Applications

Lab 36 · Arduino telemetry, CSV and ThingSpeak

Ask Dr. Mohammad · P36 →

Receive simulated Arduino temperature telemetry through RFC2217 and log or upload it.

Design experiment & verify evidence →
P36 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP36 · Arduino telemetry, CSV and ThingSpeak
Readiness checksRevision deckEngineering workspaceRecord evidence

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

P36 · Academic orientation

Scope and objectives

Scope of the experiment

Decode the Arduino TEMP:<value> lines, record accepted CSV rows, and model cloud pacing separately.

The focus of this experiment is to parse Arduino telemetry into timestamped CSV and cloud fields. Students then separate serial framing errors from storage and HTTP upload failures, and reconcile received records, stored rows and accepted uploads. 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

  • Parse Arduino telemetry into timestamped CSV and cloud fields.
  • Separate serial framing errors from storage and HTTP upload failures.
  • Reconcile received records, stored rows and accepted uploads.
  • 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 parse Arduino telemetry into timestamped CSV and cloud fields, separate serial framing errors from storage and HTTP upload failures, and reconcile received records, stored rows and accepted uploads.

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 reconcile received records, stored rows and accepted uploads. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 40 · IoT gateway · JSON lines and fan commands.

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.

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

Stop the client with Ctrl+C before reading the CSV or starting the optional cloud client. If using the fallback, keep the cable and virtual Arduino terminals running and use the /tmp serial endpoint, not RFC2217.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Arduino telemetry · Serial validation and routing

Source-aligned TEMP: records · accepted records and rejected input
Source-aligned TEMP: records · accepted records and rejected input

Scientific architecture · Arduino TEMP telemetry → CSV → ThingSpeak

Serial telemetry to cloud — Arduino / TEMP message; Receiver / complete serial line; Parser / validate numeric value; CSV file / append timestamped sample; ThingSpeak / write accepted separately
Scientific concept map: Arduino sensor — TEMP:value; Serial receiver — Read complete line; Parser — Validate temperature; CSV logger — Append timestamp and value; ThingSpeak — HTTPS upload + response.

Scientific foundations and analytical reasoning

A serial parser accepts the specified TEMP: message format, validates the numeric field and records a timestamped value. Cloud acceptance is independent of local CSV storage.

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 telemetry pipeline

The receiver buffers incoming bytes until a complete record is available. The TEMP: prefix identifies a record type; numeric parsing, finite-value validation and timestamping establish a usable observation. CSV persistence and cloud submission are independent outcomes, and an incomplete line must not be treated as a complete measurement.

Worked example and engineering interpretation

A valid TEMP:25.0 record followed by malformed TEMP:bad yields one valid sample. If cloud submission fails, the local CSV record can still exist. Track accepted parses, stored rows and successful uploads separately to isolate the failed stage.

Engineering principles · additional worked teaching example

A serial parser should distinguish complete lines from fragments, validate fields and forward only accepted records. For TEMP:20, BAD, TEMP:28, mean=(20+28)/2=24 °C; the invalid frame is a separate error count, not a numeric reading.

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 36 · Arduino telemetry, CSV and ThingSpeak

Arduino telemetry arrives as serial text. Validate a temperature/humidity row, store it in CSV and map it to ThingSpeak field1/field2. This notebook prepares payloads; it does not send them to a cloud account.

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: Decode serial telemetry and verify its logging or upload.

  1. Send TEMP:25 and TEMP:26 to the parser. Record CSV rows. Send BAD, TEMP:NaN and TEMP:100; check the row count.
  2. In the independent cloud instrument set the temperature and 20 s minimum. Step to send Field 1 only; reduce interval and observe pacing.
  3. Disable the credential condition, compare rejection with pacing, then restore.
  4. Run the original Arduino telemetry, CSV and cloud programs. The independent browser fixtures do not share state.

Reference check:

Model boundary:

Independent task and submission evidence

Add a malformed and an out-of-range sample, keeping parsing rules fixed. Record accepted/rejected counts, CSV rows and encoded field mapping. For live uploads use only the portal’s authorized channel procedure.

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: Serial lines separated by ; = TEMP:25;TEMP:26;BAD;TEMP:27; Line interval (s) = 1; Upload minimum interval (s) = 20; Cloud write key accepted = true; HTTPS reachable = true. In the classroom model, Valid frames = 3; CSV rows = 3; Cloud attempts = 1; Stored entries = 1. CSV and cloud scripts are separate consumers; the diagram compares their handling of the same fixture, not simultaneous ownership of a serial port. 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 36 · Arduino telemetry, CSV and ThingSpeak: independent state notebook1234Calculated state 1Time s0Raw lineTEMP:25Temperature °C25Local loggerCSV rowEntry/body1Cloud outcomeStored

Step 1 of 4 · Calculated state 1

Calculated state 1

Time s
0
Raw line
TEMP:25
Temperature °C
25
Local logger
CSV row
Entry/body
1
Cloud outcome
Stored

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P36 · 01 / 08What is serial telemetry?Reveal explanation
Engineering explanation

Arduino sends textual measurements that the Python client parses and records.

P36 · 02 / 08Why retain source labels?Reveal explanation
Engineering explanation

Virtual readings must not be described as physical measurements.

P36 · 03 / 08How must the serial reader be stopped before inspecting CSV or switching upload clients?Reveal explanation
Engineering explanation

Stop the client with Ctrl+C before reading the CSV or starting the optional cloud client. If using the fallback, keep the cable and virtual Arduino terminals running and use the /tmp serial endpoint, not RFC2217.

P36 · 04 / 08What makes a telemetry record traceable across serial, CSV and cloud stages?Reveal explanation
Engineering reasoning

A consistent sample identifier or timestamp plus matching values lets you reconcile the same observation at each stage.

P36 · 05 / 08Why verify each stage separately?Reveal explanation
Engineering reasoning

A serial read can succeed while parsing, local storage or remote upload fails; inspect each boundary before concluding end-to-end success.

P36 · 06 / 08Arduino telemetry is received and logged. Select every technically valid statement. A. Validate the received fields before logging. B. Check storage or upload independently of parsing. C. Every received line is necessarily valid telemetry. D. Parsing a record proves the remote upload succeeded.Reveal explanation
Applied scenario

Correct: A. Validate the received fields before logging.; B. Check storage or upload independently of parsing.

P36 · 07 / 08In Arduino telemetry, CSV and ThingSpeak, which command or code executes Terminal C — original serial route?Reveal explanation
Implementation recall

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

P36 · 08 / 08For Arduino telemetry, CSV and ThingSpeak, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Use uno-telemetry rather than uno-led-serial. Build and start Wokwi, or use the separate fake Arduino telemetry route. Only one Python client should read a serial stream at a time. Let at least three TEMP: lines arrive, stop with Ctrl+C, then inspect the last new CSV rows. For the ThingSpeak variant, start only after stopping the logger; positive entry IDs and channel read-back are required.

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.

ThingSpeak integration center

Use the dedicated setup, upload, readback and Node-RED walkthrough.

Open ThingSpeak Cloud Studio →
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

Decode serial telemetry and verify its logging or upload.

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 workbenchP36 · 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
Arduino virtual telemetryUSB serial (RFC2217)No external sensor in supplied virtual firmwarewokwi/uno-telemetry/src/main.cpp
P36 · 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

P36 · 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 36 · Arduino telemetry, CSV and ThingSpeak

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/cloud pending.

Use uno-telemetry rather than uno-led-serial. Build and start Wokwi, or use the separate fake Arduino telemetry route. Only one Python client should read a serial stream at a time. Let at least three TEMP: lines arrive, stop with Ctrl+C, then inspect the last new CSV rows. For the ThingSpeak variant, start only after stopping the logger; positive entry IDs and channel read-back are required.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

For TEMP:25;TEMP:26;BAD;TEMP:27 at one-second intervals, list accepted temperatures and calculate their mean.

02 · Compare or justify using evidence

With a 20 s minimum cloud-write interval and initial upload allowed, compare local rows and accepted cloud rows; explain the difference.

03 · Debugging

Debugging · Independent work

Given byte chunks 'TEMP:2', '3\nBAD\nTEMP:', '24\n', determine complete accepted readings and mean. Explain why reading each chunk as a line fails.

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

Use the reference configuration (Serial lines separated by ; = TEMP:25;TEMP:26;BAD;TEMP:27; Line interval (s) = 1; Upload minimum interval (s) = 20; Cloud write key accepted = true; HTTPS reachable = true), but change Line interval (s) = 60. The model reports Cloud attempts = 3. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P36-02

Two model observations of Cloud attempts are 1 (reference) and 3 (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 · P36-03

For Upload minimum interval (s) = 1, the model supplies this excerpt from Serial / CSV / upload: Time s · Raw line · Temperature °C · Local logger · Entry/body · Cloud outcome 0 · TEMP:25 · 25 · CSV row · 1 · Stored 1 · TEMP:26 · 26 · CSV row · 2 · Stored 2 · BAD · not applicable · Rejected · — · Invalid line 3 · TEMP:27 · 27 · CSV row · 3 · Stored Count rows whose Raw line value is exactly “TEMP:25”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · P36-04

An observation is Cloud attempts = 3. Candidate A uses Serial lines separated by ; = TEMP:25;TEMP:26;BAD;TEMP:27; Line interval (s) = 1; Upload minimum interval (s) = 20; Cloud write key accepted = true; HTTPS reachable = true. Candidate B changes the listed settings (Upload minimum interval (s) = 1) 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 · P36-05

A student configures HTTPS reachable = false while preserving all other reference settings, but copies the reference report of Stored entries = 1. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P36-06

Design a controlled comparison for Lab 36 · Arduino telemetry, CSV and ThingSpeak using reference Serial lines separated by ; = TEMP:25;TEMP:26;BAD;TEMP:27; Line interval (s) = 1; Upload minimum interval (s) = 20; Cloud write key accepted = true; HTTPS reachable = true and test Line interval (s) = 60. Specify the changed setting(s), measured metric Cloud attempts, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Live simulation · Serial telemetry and cloud

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

  1. Send TEMP:25 and TEMP:26 to the parser. Record CSV rows. Send BAD, TEMP:NaN and TEMP:100; check the row count.
  2. In the independent cloud instrument set the temperature and 20 s minimum. Step to send Field 1 only; reduce interval and observe pacing.
  3. Disable the credential condition, compare rejection with pacing, then restore.
  4. Run the original Arduino telemetry, CSV and cloud programs. The independent browser fixtures do not share state.

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

Decode the Arduino TEMP:<value> lines, record accepted CSV rows, and model cloud pacing separately.

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.

Serial lines separated by ;TEMP:25;TEMP:26;BAD;TEMP:27
Line interval (s)1
Upload minimum interval (s)20
Cloud write key acceptedYes
HTTPS reachableYes

2 · Perform the investigation in order

  1. Run the Arduino TEMP:25;TEMP:26;BAD;TEMP:27 stream. Inspect the parser, CSV rows and field1 uploads. Arduino telemetry.ino emits TEMP: and newline every second.
  2. Compare the serial line interval 1 s to 20 s; the cloud forwarding practical permits at most one attempted upload per 20 s, independently of CSV logging.
  3. Change the key or HTTPS availability. CSV storage remains independent of the cloud. Reject malformed/non-finite or out-of-range temperatures before writing.
  4. Use pi_read_arduino.py for CSV and pi_to_thingspeak.py for cloud as separate serial sessions; close the first process before opening the same port in the second. Set SERIAL_PORT correctly and use a hidden write-key prompt.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
ReferenceUse reference inputs aboveValid frames: 3; CSV rows: 3; Stored entries: 1Record actual result
Paced serialLine interval (s) = 20Stored entries: 3Record actual result
Invalid keyCloud write key accepted = NoStored entries: 0Record actual result
Malformed valuesSerial lines separated by ; = TEMP:bad;TEMP:NaN;TEMP:81Valid frames: 0Record actual result

4 · Analyze and report

Do not assume every local CSV row reaches the channel. Only temperature is sent; no humidity is emitted by this Arduino sketch.

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. Inspect the CSV
  7. Optional ThingSpeak upload
  8. Fallback when RFC2217 is unavailable
  9. Terminal B — virtual Arduino
  10. Terminal C — original serial route
ThingSpeak credential and response checks

Use the channel Write API Key for writes; a private readback needs the channel Read API Key and numeric channel ID. Hidden input displays no characters. A positive entry ID confirms acceptance; zero or an HTTP error does not. Wait 20 seconds between writes; do not share keys or disable TLS verification.

02 / Implement

Step-by-step instructions

Before you run / verification gate

Stop the client with Ctrl+C before reading the CSV or starting the optional cloud client. If using the fallback, keep the cable and virtual Arduino terminals running and use the /tmp serial endpoint, not RFC2217.

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-telemetry
✓ 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/lab36
export SERIAL_PORT=rfc2217://127.0.0.1:4000
python pi_read_arduino.py
✓ Expected: Serial TEMP readings appear and are logged to CSV. Stop with Ctrl+C after several samples.
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/lab36Normally 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_read_arduino.pySerial TEMP readings appear and are logged to CSV. Stop with Ctrl+C after several samples.
Checkpoint Generated random TEMP values appear once per second. Ctrl+C after a few lines.
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

Inspect the CSV

This is simulated Arduino telemetry.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab36
tail -n 5 temp_log.csv
✓ Expected: The last five CSV lines (or fewer if the file is shorter) appear.
Expected result for each action (3)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. cd ~/psut-wsl/labs/python/lab36Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. tail -n 5 temp_log.csvThe last five CSV lines (or fewer if the file is shorter) appear.
Checkpoint Timestamp and temperature rows.
07

Optional ThingSpeak upload

Keep the simulator running and stop the CSV client first. Create your channel and key using Lab 34. Enter the Write key at the hidden prompt.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab36
export SERIAL_PORT=rfc2217://127.0.0.1:4000
unset THINGSPEAK_WRITE_KEY
python pi_to_thingspeak.py
✓ Expected: Successful service submission reports a positive entry ID; verify the private ThingSpeak channel. A zero or HTTP error is not success.
Checkpoint Positive entry ID; Ctrl+C to stop.
08

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.
09

Terminal B — virtual Arduino

Keep running.

WSL · Bash
source ~/psut-wsl/activate.sh
python ~/psut-wsl/tools/fake_arduino.py telemetry
✓ 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 telemetryThe virtual Arduino starts and waits or emits simulated telemetry according to the selected mode. Keep it running.
Checkpoint Virtual Arduino is ready.
10

Terminal C — original serial route

Run client in a third terminal.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab36
export SERIAL_PORT=/tmp/psut-pi-serial
python pi_read_arduino.py
✓ Expected: Serial TEMP readings appear and are logged to CSV. Stop with Ctrl+C after several samples.
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/lab36Normally 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_read_arduino.pySerial TEMP readings appear and are logged to CSV. Stop with Ctrl+C after several samples.
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/lab36/pi_read_arduino.pyDownload source
PY · source file
import os
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import serial, csv, math
from datetime import datetime
with serial.serial_for_url(os.getenv('SERIAL_PORT', '/dev/ttyACM0'), 9600, timeout=1) as ser:
    while True:
        line = ser.readline().decode('utf-8', errors='replace').strip()
        if line.startswith('TEMP:'):
            try:
                value = float(line.split(':', 1)[1])
            except ValueError:
                continue
if not math.isfinite(value) or not -40 <= value <= 80:
                continue
timestamp = datetime.now().isoformat()
            print(timestamp, value)
            with open('temp_log.csv', 'a', newline='') as file:
                csv.writer(file).writerow([timestamp, value])
labs/python/lab36/pi_to_thingspeak.pyDownload source
PY · source file
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform — P36
"""Forward temperature-only TEMP:<value> serial lines to a private channel."""
import os, time, sys, math
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
# Reuse P34's key and response validation without importing hardware drivers.
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'lab34'))
from dht22_thingspeak import validate_key, response_entry
from getpass import getpass, GetPassWarning
import warnings
warnings.filterwarnings("error",category=GetPassWarning)
import serial
def main():
    try:
        key=validate_key(os.getenv('THINGSPEAK_WRITE_KEY','').strip() or getpass('ThingSpeak channel Write API Key (hidden): '))
    except (ValueError,EOFError,GetPassWarning) as e:
        print('Credential error:',str(e),file=sys.stderr);return 1
last=-float('inf')
    try:
        with serial.serial_for_url(os.getenv('SERIAL_PORT','/dev/ttyACM0'),9600,timeout=1) as ser:
            while True:
                line=ser.readline().decode('utf-8',errors='replace').strip()
                if not line.startswith('TEMP:'):continue
try: temp=float(line.split(':',1)[1])
                except ValueError:continue
if not math.isfinite(temp) or not -40<=temp<=80:continue
if time.monotonic()-last<20:continue
last=time.monotonic() # Pace attempted requests as well as accepted ones.
req=Request('https://api.thingspeak.com/update',data=urlencode({'api_key':key,'field1':temp,'status':'arduino-demo'}).encode(),method='POST',headers={'Content-Type':'application/x-www-form-urlencoded'})
                try:
                    with urlopen(req,timeout=15) as r: entry=response_entry(r.status,r.read(128).decode('ascii',errors='replace'))
                    print('HTTP 200; accepted entry:',entry,'Temperature:',temp,flush=True)
                except HTTPError as e: print('HTTP',e.code,'— check channel credentials/permissions and update interval.',flush=True)
                except (RuntimeError,ValueError) as e:print('Upload rejected:',str(e),flush=True)
                except (URLError,TimeoutError,OSError):print('Connection failed; check DNS, network, clock and TLS trust.',flush=True)
    except serial.SerialException:
        print('Serial unavailable; check SERIAL_PORT and close other applications using the port.',file=sys.stderr);return 1
if __name__=='__main__':
    try:sys.exit(main())
    except KeyboardInterrupt:sys.exit(130)
labs/python/lab36/telemetry.inoDownload source
INO · source file
// ------------------------------------------------------------
// Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
// PSUT IoT Engineering Learning Platform
// ------------------------------------------------------------
// ---- Start serial communication.
void setup() {
  Serial.begin(9600);              // same baud as the Pi
}
 
void loop() {                      // repeats forever
  // ---- Create a fake sensor value for demonstration.
  int fakeValue = random(20, 31);  // 20 to 30
 
  // ---- Send a line of text to the Raspberry Pi.
  Serial.print("TEMP:");           // label
  Serial.println(fakeValue);       // value + newline
 
  // ---- Wait one second before the next message.
  delay(1000);                     // 1 message/s
}
wokwi/uno-telemetry/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-telemetry/platformio.iniDownload source
INI · source file
[env:uno]
platform = atmelavr
board = uno
framework = arduino
monitor_speed = 9600
wokwi/uno-telemetry/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
// ------------------------------------------------------------
// ---- Start serial communication.
void setup() {
  Serial.begin(9600);              // same baud as the Pi
}
 
void loop() {                      // repeats forever
  // ---- Create a fake sensor value for demonstration.
  int fakeValue = random(20, 31);  // 20 to 30
 
  // ---- Send a line of text to the Raspberry Pi.
  Serial.print("TEMP:");           // label
  Serial.println(fakeValue);       // value + newline
 
  // ---- Wait one second before the next message.
  delay(1000);                     // 1 message/s
}
wokwi/uno-telemetry/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

P36 · 6 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
# P36 · Lab 36 · Arduino telemetry, CSV and ThingSpeak **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose Arduino telemetry arrives as serial text. Validate a temperature/humidity row, store it in CSV and map it to ThingSpeak field1/field2. This notebook prepares payloads; it does not send them to a cloud account. **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
# =====================================================================
# P36 | Code cell 01 | Lab 36 · Arduino telemetry, CSV and ThingSpeak
# 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.
# =====================================================================
import csv,io
from urllib.parse import urlencode
# Set serial_lines for the next computation or reference condition.
serial_lines=['25.4,47.0','bad','26.1,48.0']
# Define the reusable operation parse; keep its logic separate from the trial.
def parse(line):
    try:
        t,h=map(float,line.split(','))
        if not (-40<=t<=80 and 0<=h<=100): return None
        return t,h
    except ValueError: return None
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P36 | Code cell 02 | Lab 36 · Arduino telemetry, CSV and ThingSpeak
# 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 valid for the next computation or reference condition.
valid=[r for line in serial_lines if (r:=parse(line)) is not None]
# Set buffer for the next computation or reference condition.
buffer=io.StringIO(); writer=csv.writer(buffer)
writer.writerow(['temperature_c','humidity_pct']); writer.writerows(valid)
print(buffer.getvalue())
# Repeat the same operation for each configured input so observations are comparable.
for t,h in valid: print('ThingSpeak form:',urlencode({'field1':t,'field2':h}))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert len(valid)==2
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## Independent investigation and submission Add a malformed and an out-of-range sample, keeping parsing rules fixed. Record accepted/rejected counts, CSV rows and encoded field mapping. For live uploads use only the portal’s authorized channel procedure. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.