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 33 · DHT22 CSV logging
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P33
IoT Programming and Applications

Lab 33 · DHT22 CSV logging

Ask Dr. Mohammad · P33 →

The CSV file is real; the readings come from the fake DHT22.

Design experiment & verify evidence →
P33 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP33 · DHT22 CSV logging
Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Machine Learning and Edge AI — same laboratory, notebook and completion record.

P33 · Academic orientation

Scope and objectives

Scope of the experiment

Build actual CSV text from valid observations and measure record count, size and missing data.

The focus of this experiment is to connect validated DHT22 samples to timestamped CSV rows. Students then trace file opening, header handling and missing measurements, and verify row count, units and reproducibility of the resulting log. 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

  • Connect validated DHT22 samples to timestamped CSV rows.
  • Trace file opening, header handling and missing measurements.
  • Verify row count, units and reproducibility of the resulting log.
  • Identify the configured inputs (Reference temperature (°C); Reference humidity (%); Sampling interval (s); Attempt count; Fail every N attempts (0 = none)) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can connect validated DHT22 samples to timestamped CSV rows, trace file opening, header handling and missing measurements, and verify row count, units and reproducibility of the resulting log.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify row count, units and reproducibility of the resulting log. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 34 · DHT22 to 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.

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

Record the line count before running, treating a nonexistent file as zero rows. Verify three successful appends rather than exactly three total lines.

CONCEPTS / ACTIVE RECALL

Understand the experiment

CSV acquisition · Append versus skip

Reference fixture: sequence, measured values and row persistence
Reference fixture: sequence, measured values and row persistence

Scientific architecture · DHT22 CSV acquisition and missing values

DHT22 CSV acquisition — Sample at t=0 / 25°C, 55% RH; Validity check / finite measurements; CSV row / t,temp,hum; Append / do not overwrite earlier rows; Read back / separate missing samples
Scientific concept map: DHT22 sample — Timestamp + readings; Validity check — Missing sample handling; CSV serializer — Header and data row; File append — Persistent records; Analysis — Read rows / missing data.

Scientific foundations and analytical reasoning

A CSV log stores successive observations as rows; missing-value handling changes completeness and statistical bias.

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 · Time-stamped sampling and storage

CSV is a text representation of rows and fields, not a database transaction mechanism. Use a stable schema, consistent units and an unambiguous timestamp. An acquisition may fail before storage; a write can fail after acquisition. Separate scheduled, accepted and stored counts. Preserve missing values explicitly.

Worked example and engineering interpretation

Six samples of which five are valid and four are stored have 5/6 acquisition completeness and 4/6 end-to-end completeness. A zero humidity observation is a numeric value, whereas an empty field means missing under the defined schema. Compare the log with the sample history.

Engineering principles · additional worked teaching example

CSV is a row-oriented text format; a header is metadata, not a sample. If five attempts contain one missing observation, skip yields four data rows, whereas explicit missing yields five rows with a validity flag. Explicit missing aids reconstruction of acquisition times.

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 33 · DHT22 CSV logging

CSV preserves structured observations in rows with a fixed header. Include timestamp, temperature and humidity; mark the source as simulated. Re-reading validates the serialization rather than measuring a physical sensor.

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: Append sensor records to CSV and verify newly written rows.

  1. Collect eight samples at 2 s. Inspect CSV header, timestamp and byte count.
  2. Inject every second failure; compare skip and empty-field policies.
  3. Compare the number of successful sensor reads to CSV data rows.
  4. Run the actual logger and inspect the file with head and wc -l; distinguish header from records.

Reference check:

Model boundary:

Independent task and submission evidence

Add a third reading at 4 s without changing the header. Record line count and parsed values. Explain why a missing humidity field is different from 0%.

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: Reference temperature (°C) = 25; Reference humidity (%) = 55; Sampling interval (s) = 2; Attempt count = 8; Fail every N attempts (0 = none) = 0; Invalid sample policy = skip. In the classroom model, Valid reads = 8; Data rows = 8; CSV bytes = 106. UTF-8 bytes are computed from the generated CSV, including header and newlines. 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.

Mathematical representation and interpretation

Sampling and sensor summary

Delta t is the sampling interval in seconds, f_s is in hertz, and x_i are valid observations in a consistent unit. Missing readings are not automatically zero.

\[f_s=\frac1{\Delta t},\qquad \bar x=\frac1N\sum_{i=1}^{N}x_i\]

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 33 · DHT22 CSV logging: independent state notebook12345678Calculated state 1time_s0temp_c24.6humidity_pct54

Step 1 of 8 · Calculated state 1

Calculated state 1

time_s
0
temp_c
24.6
humidity_pct
54

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P33 · 01 / 08What is CSV?Reveal explanation
Engineering explanation

A text file of comma-separated fields, here timestamp and sensor readings.

P33 · 02 / 08Why count before and after?Reveal explanation
Engineering explanation

The logger appends, so existing rows must not be counted as new measurements.

P33 · 03 / 08Why measure the CSV line-count increase rather than the final total?Reveal explanation
Engineering explanation

Record the line count before running, treating a nonexistent file as zero rows. Verify three successful appends rather than exactly three total lines.

P33 · 04 / 08Why include a timestamp with each CSV record?Reveal explanation
Engineering reasoning

It establishes sample order and permits interval, gap and time-series checks.

P33 · 05 / 08How do you verify a logging experiment?Reveal explanation
Engineering reasoning

Inspect the header, row count, units and timestamps; compare one recorded row against the corresponding acquisition output.

P33 · 06 / 08A sensor logger appends CSV rows. Select every technically valid statement. A. Check the header and field order. B. Verify that new rows are appended rather than overwriting earlier ones. C. A file's existence proves every sample was recorded. D. CSV automatically verifies sensor calibration.Reveal explanation
Applied scenario

Correct: A. Check the header and field order.; B. Verify that new rows are appended rather than overwriting earlier ones.

P33 · 07 / 08In DHT22 CSV logging, which command or code executes Open it in Excel?Reveal explanation
Implementation recall

explorer.exe . # opens this Ubuntu folder in Windows Explorer

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

The CSV has no header: timestamp, temperature, humidity. In an existing log record the previous row count (wc -l dht22_log.csv); if absent use zero. Run three successful acquisitions and compare the count increase by three, not total rows. An exhausted read exits nonzero and appends nothing. Do not delete earlier evidence; archive it separately.

Execution boundary · Simulated (fake Pi). Browser simulation below is a teaching model, not execution of Python or firmware. The real commands run in VS Code/WSL; Wokwi is used for Arduino/ESP32 where indicated.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research
Loading experiment-specific apparatus…
Previous model / additional reference tools
Simulation task

Append sensor records to CSV and verify newly written rows.

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 workbenchP33 · 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
DHT22 DATABCM GPIO23 · physical 163.3 V power, GND, pull-up on bare sensor datalab33/dht22_log.py
P33 · 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

P33 · 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 33 · DHT22 CSV logging

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

Prepare a contextual AI prompt

0 characters

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

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

Run & verify — acceptance checklist

Build verification: Actual three CSV appends and forced-failure no-file control passed.

The CSV has no header: timestamp, temperature, humidity. In an existing log record the previous row count (wc -l dht22_log.csv); if absent use zero. Run three successful acquisitions and compare the count increase by three, not total rows. An exhausted read exits nonzero and appends nothing. Do not delete earlier evidence; archive it separately.

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 the eight-attempt fixture with every third sample invalid, calculate number of written rows under skip and blank-row policies, excluding header.

02 · Compare or justify using evidence

For valid temperatures 24,25,26 and one missing value, calculate mean excluding missing and mean after zero filling. Explain which is defensible.

03 · Data quality

Data quality · Independent work

A logger attempts 12 readings and fails on every fourth. Compare valid counts and total CSV lines including one header for skip versus explicit missing rows. Explain how to calculate mean.

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

Use the reference configuration (Reference temperature (°C) = 25; Reference humidity (%) = 55; Sampling interval (s) = 2; Attempt count = 8; Fail every N attempts (0 = none) = 0; Invalid sample policy = skip), but change Reference temperature (°C) = 24.8. The model reports CSV bytes = 108. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · P33-02

Two model observations of CSV bytes are 106 (reference) and 108 (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 · P33-03

For Reference humidity (%) = 55.2, the model supplies this excerpt from CSV records: time_s · temp_c · humidity_pct 0 · 24.6 · 54.2 2 · 24.8 · 55.2 4 · 25 · 56.2 6 · 25.2 · 54.2 8 · 25.4 · 55.2 Compute the range (maximum minus minimum) of the temp_c column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · P33-04

An observation is CSV bytes = 122. Candidate A uses Reference temperature (°C) = 25; Reference humidity (%) = 55; Sampling interval (s) = 2; Attempt count = 8; Fail every N attempts (0 = none) = 0; Invalid sample policy = skip. Candidate B changes the listed settings (Reference humidity (%) = 55.2) 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 · P33-05

A student configures Sampling interval (s) = 4 while preserving all other reference settings, but copies the reference report of CSV bytes = 106. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · P33-06

Design a controlled comparison for Lab 33 · DHT22 CSV logging using reference Reference temperature (°C) = 25; Reference humidity (%) = 55; Sampling interval (s) = 2; Attempt count = 8; Fail every N attempts (0 = none) = 0; Invalid sample policy = skip and test Reference temperature (°C) = 24.8. Specify the changed setting(s), measured metric CSV bytes, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Build actual CSV text from valid observations and measure record count, size and missing data.

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.

Reference temperature (°C)25
Reference humidity (%)55
Sampling interval (s)2
Attempt count8
Fail every N attempts (0 = none)0
Invalid sample policyskip

2 · Perform the investigation in order

  1. Collect eight samples at 2 s. Inspect CSV header, timestamp and byte count.
  2. Inject every second failure; compare skip and empty-field policies.
  3. Compare the number of successful sensor reads to CSV data rows.
  4. Run the actual logger and inspect the file with head and wc -l; distinguish header from records.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Valid CSVUse reference inputs aboveData rows: 8Record actual result
Skip failuresFail every N attempts (0 = none) = 2Data rows: 4Record actual result
Retain missing rowsFail every N attempts (0 = none) = 2; Invalid sample policy = empty fieldsData rows: 8Record actual result

4 · Analyze and report

Never silently replace missing temperature with 0 °C.

Required evidence: Record the named metrics and trace for the reference and changed cases, then attach the corresponding practical command output or device evidence if available.

Model boundary: A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Controlled investigation · reproducible evidence

Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

TrialIndependent changeDependent observation
Valid CSVUse reference inputs aboveRecord actual outcome and units
Skip failuresFail every N attempts (0 = none) = 2Record actual outcome and units
Retain missing rowsFail every N attempts (0 = none) = 2; Invalid sample policy = empty fieldsRecord actual outcome and units

Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Original program using the packaged fakepi driver; no physical sensor. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Open a terminal
  2. Log three times
  3. Open it in Excel
02 / Implement

Step-by-step instructions

Before you run / verification gate

Record the line count before running, treating a nonexistent file as zero rows. Verify three successful appends rather than exactly three total lines.

Complete one-time setup first. Copy one command block at a time into the indicated environment. Do not copy prompt characters. Open new terminals where named; variables are terminal-specific. Ctrl+C stops a running foreground command.

01

Open a terminal

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/python/lab33
ls
✓ Expected: The requested files/directories are listed; compare names and permissions with the guide. An empty directory can produce no output.
Expected result for each action (3)
  1. source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
  2. cd ~/psut-wsl/labs/python/lab33Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. lsThe requested files/directories are listed; compare names and permissions with the guide. An empty directory can produce no output.
Checkpoint the lab’s programs are listed.
02

Log three times

WSL · Bash
python dht22_log.py && python dht22_log.py && python dht22_log.py && tail -n 3 dht22_log.csv
✓ Expected: CSV rows appear with timestamp, temperature and humidity; existing data may add earlier rows.
Expected result for each action (2)
  1. python dht22_log.py; python dht22_log.py; python dht22_log.pyEach invocation appends one CSV row and prints Reading stored in CSV.; three successful runs add three rows.
  2. cat dht22_log.csvCSV rows appear with timestamp, temperature and humidity; existing data may add earlier rows.
Checkpoint three Reading stored in CSV. and three rows like 2026-12-02T09:00:49.104844,23.9,61.1 .
03

Open it in Excel

WSL · Bash
explorer.exe .        # opens this Ubuntu folder in Windows Explorer
✓ Expected: Windows File Explorer opens the current Linux folder; no terminal output is normally required.
Checkpoint double-click dht22_log.csv.

Experimental notebook

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

03 / Inspect

Source code and method

labs/python/lab33/dht22_log.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import csv
from datetime import datetime
import time
import board
import adafruit_dht
sensor = adafruit_dht.DHT22(board.D23)
try:
    for attempt in range(5):
        try:
            temperature, humidity = sensor.temperature, sensor.humidity
        except RuntimeError as err:
            print('Read failed:', err)
            if attempt < 4:
                time.sleep(2)
            continue
        if temperature is not None and humidity is not None and -40 <= temperature <= 80 and 0 <= humidity <= 100:
            with open('dht22_log.csv', 'a', newline='', encoding='utf-8') as file:
                csv.writer(file).writerow([datetime.now().isoformat(), temperature, humidity])
            print('Reading stored in CSV.')
            break
        if attempt < 4:
            time.sleep(2)
    else:
        raise SystemExit("DHT22 failed after five attempts; no CSV row appended.")
finally:
    sensor.exit()
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

P33 · 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
# P33 · Lab 33 · DHT22 CSV logging **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose CSV preserves structured observations in rows with a fixed header. Include timestamp, temperature and humidity; mark the source as simulated. Re-reading validates the serialization rather than measuring a physical sensor. **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
# =====================================================================
# P33 | Code cell 01 | Lab 33 · DHT22 CSV logging
# 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
# Set rows for the next computation or reference condition.
rows=[{'seconds':0,'temperature_c':25.1,'humidity_pct':45.0,'source':'simulated'}, {'seconds':2,'temperature_c':25.2,'humidity_pct':46.0,'source':'simulated'}]
# Define the reusable operation log; keep its logic separate from the trial.
def log(records):
    buffer=io.StringIO()
    writer=csv.DictWriter(buffer,fieldnames=list(records[0]))
    writer.writeheader()  # Consistent names permit reliable parsing
    writer.writerows(records)
    return buffer.getvalue()
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P33 | Code cell 02 | Lab 33 · DHT22 CSV logging
# 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 text for the next computation or reference condition.
text=log(rows)
print(text)
# Set readback for the next computation or reference condition.
readback=list(csv.DictReader(io.StringIO(text)))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert len(readback)==len(rows)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert float(readback[0]['temperature_c'])==rows[0]['temperature_c']
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 python dht22_log.py && python dht22_log.py && python dht22_log.py && tail -n 3 dht22_log.csv ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ import csv from datetime import datetime import time import board import adafruit_dht sensor = adafruit_dht.DHT22(board.D23) try: for attempt in range(5): try: temperature, humidity = sensor.temperature, sensor.humidity except RuntimeError as err: print('Read failed:', err) if attempt < 4: time.sleep(2) continue if temperature is not None and humidity is not None and -40 <= temperature <= 80 and 0 <= humidity <= 100: with open('dht22_log.csv', 'a', newline='', encoding='utf-8') as file: csv.writer(file).writerow([datetime.now().isoformat(), temperature, humidity]) print('Reading stored in CSV.') break if attempt < 4: time.sleep(2) else: raise SystemExit("DHT22 failed after five attempts; no CSV row appended.") finally: sensor.exit() ```
07Instructions · Markdown
## Independent investigation and submission Add a third reading at 4 s without changing the header. Record line count and parsed values. Explain why a missing humidity field is different from 0%. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.