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.
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.
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.
Collect eight samples at 2 s. Inspect CSV header, timestamp and byte count.
Inject every second failure; compare skip and empty-field policies.
Compare the number of successful sensor reads to CSV data rows.
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.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
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.
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.
Step 1 of 8 · Calculated state 1
Calculated state 1
time_s
0
temp_c
24.6
humidity_pct
54
Calculated state 2
time_s
2
temp_c
24.8
humidity_pct
55
Calculated state 3
time_s
4
temp_c
25
humidity_pct
56
Calculated state 4
time_s
6
temp_c
25.2
humidity_pct
54
Calculated state 5
time_s
8
temp_c
25.4
humidity_pct
55
Calculated state 6
time_s
10
temp_c
24.6
humidity_pct
56
Calculated state 7
time_s
12
temp_c
24.8
humidity_pct
54
Calculated state 8
time_s
14
temp_c
25
humidity_pct
55
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 studiesConcurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery researchLoading 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.
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.
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.
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.
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.
Engineering method — 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. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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.
Engineering method — 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. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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.
Data quality — 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. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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
Collect eight samples at 2 s. Inspect CSV header, timestamp and byte count.
Inject every second failure; compare skip and empty-field policies.
Compare the number of successful sensor reads to CSV data rows.
Run the actual logger and inspect the file with head and wc -l; distinguish header from records.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Valid CSV
Use reference inputs above
Data rows: 8
Record actual result
Skip failures
Fail every N attempts (0 = none) = 2
Data rows: 4
Record actual result
Retain missing rows
Fail every N attempts (0 = none) = 2; Invalid sample policy = empty fields
Data rows: 8
Record 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.
Trial
Independent change
Dependent observation
Valid CSV
Use reference inputs above
Record actual outcome and units
Skip failures
Fail every N attempts (0 = none) = 2
Record actual outcome and units
Retain missing rows
Fail every N attempts (0 = none) = 2; Invalid sample policy = empty fields
Record 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.
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)
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.
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.
lsThe requested files/directories are listed; compare names and permissions with the guide. An empty directory can produce no output.
✓ Expected: CSV rows appear with timestamp, temperature and humidity; existing data may add earlier rows.Expected result for each action (2)
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.
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.
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.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
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()
## 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']
## 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.