Inspect sensor requests, minimum interval and failed observations.
The focus of this experiment is to distinguish temperature, relative humidity and invalid DHT22 readings. Students then trace acquisition, sampling interval and validation of sensor data, and record valid readings and distinguish missing samples from measured zero. 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
Distinguish temperature, relative humidity and invalid DHT22 readings.
Trace acquisition, sampling interval and validation of sensor data.
Record valid readings and distinguish missing samples from measured zero.
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 distinguish temperature, relative humidity and invalid DHT22 readings, trace acquisition, sampling interval and validation of sensor data, and record valid readings and distinguish missing samples from measured zero.
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 record valid readings and distinguish missing samples from measured zero. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Lab 33 · DHT22 CSV logging.
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.
P32 / 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 run can have no errors or all five attempts can fail. Record the actual outcome; rerun for a successful sample if none appears. Exit status alone does not prove a reading.
CONCEPTS / ACTIVE RECALL
Understand the experiment
DHT22 · Sampling and retry
Illustrative acquisition state machine · invalid samples must not be logged
Scientific architecture · DHT22 sampling validity and retries
Scientific concept map: Ambient environment — Temperature / humidity; DHT22 sensor — Digital sample; Acquisition — Read and retry; Validity check — Accept or discard; History — Two separate time series.
Scientific foundations and analytical reasoning
DHT22 measurements are sampled rather than continuous. A failed read is missing data, not a zero measurement; retries must respect the sensor timing.
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 · Sensor acquisition and validity
Relative humidity expresses water vapor pressure relative to saturation at the measured temperature, as a percentage. A digital DHT22 reading has finite resolution, accuracy and a minimum sampling interval. Acquisition failure or a corrupted response must be marked missing rather than replaced with zero. Sensor placement and thermal lag affect the physical response.
Worked example and engineering interpretation
If ten scheduled readings yield eight valid results, acquisition completeness is 80%. A mean computed on the eight valid samples is not automatically representative of the missing periods. Compare a changed temperature or humidity in subsequent samples; do not rewrite the recorded history.
Engineering principles · additional worked teaching example
A sensor read can be valid, invalid, or stale; retry count is not the number of independent measurements. At 3 s spacing six attempts span 15 s from first to last; if attempt 4 fails, five measurements remain. Preserve timestamps and do not fabricate a failed 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 32 · DHT22 temperature and humidity
DHT22 produces temperature and relative humidity readings. Invalid sensor samples must be rejected; a simulated sample is not a physical reading. Respect the physical sensor sampling interval of at least two seconds.
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: Read mock DHT22 temperature/humidity and interpret retries.
Run eight requests spaced two seconds apart. Inspect each timestamp and temperature/humidity pair.
Reduce the interval to one second and inspect the alternating invalid readings.
Restore 2 s and inject every second request as a failure; compare valid sample count.
Use the original DHT22 code and observe exceptions/NaN rather than treating failed values as zero.
Reference check:
Model boundary:
Independent task and submission evidence
Keep samples fixed and vary retry limit 1, 2 and 3. Record attempts and success/failure; explain why a failed read must not be treated as zero humidity.
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
DHT22 reports temperature and relative humidity as digital measurements with validity status. Accuracy differs from precision and resolution. A failed read must remain missing. Example readings 22.2,22.4,22.3 °C average 22.3 °C.
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 4 · Acquire
Acquire
Acquire
22.2 °C
Acquire
Acquire
22.4 °C
Acquire
Acquire
22.3 °C
Aggregate
Acquire
22.3 °C
Aggregate
(22.2+22.4+22.3)/3=22.3 °C
Teaching example only; inspect live calculations or real practical evidence separately.
Recall the concept before revealing its explanation.
Timing or checksum failures can occur; the program retries up to five times.
P32 · 02 / 08What does FAKEPI_DHT_FAIL do?Reveal explanation
Engineering explanation
It sets a probability of simulated failure, not a guaranteed failure sequence.
P32 · 03 / 08Why does a DHT22 process exit alone not establish a successful reading?Reveal explanation
Engineering explanation
A run can have no errors or all five attempts can fail. Record the actual outcome; rerun for a successful sample if none appears. Exit status alone does not prove a reading.
P32 · 04 / 08Why does a failed DHT22 read not justify recording zero?Reveal explanation
Engineering reasoning
Zero can be a valid numerical value; failed acquisition must be identified separately, not substituted as a measurement.
The sensor has a finite measurement/update interval; observe the documented timing and distinguish cached or mock readings.
P32 · 06 / 08A DHT22 read fails intermittently. Select every technically valid statement.
A. Record failed reads separately from valid samples.
B. Respect the sensor sampling interval.
C. Replace all failed samples with zero degrees.
D. Successful mock reads calibrate the physical sensor.Reveal explanation
Applied scenario
Correct: A. Record failed reads separately from valid samples.; B. Respect the sensor sampling interval.
P32 · 07 / 08In DHT22 temperature and humidity, which command or code executes A hot room?Reveal explanation
P32 · 08 / 08For DHT22 temperature and humidity, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance
Use the updated toolkit. A failure probability of 0.6 can cause zero, some or five failures; it is not a required number of retries. FAKEPI_DHT_FAIL=1 guarantees exhaustion and exit status 1. With FAKEPI_DHT_FAIL=0 and fixed values 31.5/40, expect Temp=31.5 C and Humidity=40.0%. Do not record a failed run as a reading.
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.
DHT22 sampling. Temperature and humidity traces.
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
Read mock DHT22 temperature/humidity and interpret retries.
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 workbenchP32 · Existing model
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 successful and forced-failure CPython runs passed.
Use the updated toolkit. A failure probability of 0.6 can cause zero, some or five failures; it is not a required number of retries. FAKEPI_DHT_FAIL=1 guarantees exhaustion and exit status 1. With FAKEPI_DHT_FAIL=0 and fixed values 31.5/40, expect Temp=31.5 C and Humidity=40.0%. Do not record a failed run as a reading.
Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.
✓ Expected: Five failed attempts, explicit failure message, then exit status 1. No valid reading should appear. This is an intentional negative control.
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 8 attempts beginning at t=0, spaced 2 s apart, with every third attempt invalid, list timestamps and valid sample count.
Engineering method — A sensor read can be valid, invalid, or stale; retry count is not the number of independent measurements. At 3 s spacing six attempts span 15 s from first to last; if attempt 4 fails, five measurements remain. Preserve timestamps and do not fabricate a failed reading. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Compare or justify using evidence
Calculate success percentage; explain why a zero-filled humidity curve and a missing-value marker carry different meanings.
Engineering method — A sensor read can be valid, invalid, or stale; retry count is not the number of independent measurements. At 3 s spacing six attempts span 15 s from first to last; if attempt 4 fails, five measurements remain. Preserve timestamps and do not fabricate a failed reading. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Data interpretation
Data interpretation · Independent work
Seven attempts start at t=1 s with 2.5 s spacing. Attempts 2 and 6 fail. List valid times, success rate and final attempt time.
Data interpretation — A sensor read can be valid, invalid, or stale; retry count is not the number of independent measurements. At 3 s spacing six attempts span 15 s from first to last; if attempt 4 fails, five measurements remain. Preserve timestamps and do not fabricate a failed reading. 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.
Foundational · Apply the principle
Independent theoretical exercise · P32-01
Given 23.1,23.5,23.3 °C, compute mean and range.
Intermediate · Calculate or trace
Independent theoretical exercise · P32-02
Compare 25.0 °C and 50% RH. Can they be directly averaged?
Intermediate · Interpret the result
Independent theoretical exercise · P32-03
Samples at t=0,2,4,6,8 s, t=4 invalid. Give valid count, rate and span.
Advanced · Analyze a condition
Independent theoretical exercise · P32-04
If reference temperature is 24.0 °C and instrument reads 24.6 °C, estimate one-point offset and corrected 25.1 reading.
Advanced · Diagnose or compare
Independent theoretical exercise · P32-05
A moving average over last three valid readings [22,23,28] yields what? Does it reject all outliers?
Challenging · Engineering verification
Independent theoretical exercise · P32-06
Design a repeatability test at stable ambient conditions.
Step-by-step experimental procedure
Inspect sensor requests, minimum interval and failed observations.
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
2 · Perform the investigation in order
Run eight requests spaced two seconds apart. Inspect each timestamp and temperature/humidity pair.
Reduce the interval to one second and inspect the alternating invalid readings.
Restore 2 s and inject every second request as a failure; compare valid sample count.
Use the original DHT22 code and observe exceptions/NaN rather than treating failed values as zero.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Two-second interval
Use reference inputs above
Valid samples: 8
Record actual result
Too frequent
Sampling interval (s) = 1
Valid samples: 4
Record actual result
Intermittent failures
Fail every N attempts (0 = none) = 2
Valid samples: 4
Record actual result
4 · Analyze and report
The sampling interval and read failure are separate mechanisms.
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
Two-second interval
Use reference inputs above
Record actual outcome and units
Too frequent
Sampling interval (s) = 1
Record actual outcome and units
Intermittent failures
Fail every N attempts (0 = none) = 2
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.
A run can have no errors or all five attempts can fail. Record the actual outcome; rerun for a successful sample if none appears. Exit status alone does not prove a reading.
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/lab32
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/lab32Normally 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.
Checkpoint the lab’s programs are listed.
02
dht22_new.py
WSL · Bash
python dht22_new.py
✓ Expected: The simulated DHT22 reading is printed; configured failure probability may produce retries before a valid reading. Values follow the selected overrides.
Checkpoint [fake-pi] DHT22 on board.D23 (simulated sensor) and Temp=24.0 C Humidity=61.0% (values vary).
03
Show the retry loop
WSL · Bash
FAKEPI_DHT_FAIL=0.6 python dht22_new.py
✓ Expected: One or more simulated checksum errors may occur before a valid reading; failures are probabilistic, not guaranteed.
Checkpoint Zero or more checksum errors may occur. A valid reading is success; exhaustion after five attempts is explicit failure (exit 1).
Interpret the trial correctly
Zero failures is possible, as is exhaustion of all five retries. Only a printed Temp/Humidity sample is a successful reading. Repeat the experiment if needed; never invent a checksum error.
✓ Expected: Temp=31.5 C and Humidity=40.0% are expected for these overrides.
Checkpoint Temp=31.5 C Humidity=40.0% .
Experimental notebook
Record your own results. Values are not prefilled or independently verified.
Optional physical acceptance · supervised low-voltage work
DHT22 sensor on Raspberry Pi 4
Apparatus: Actual Raspberry Pi 4, suitable 3.3 V-compatible components, appropriate supply and instrument. WSL mock output is not physical evidence.
Wiring and safety: Use the physical driver and verify the GPIO pin in its actual configuration. A bare sensor requires an appropriate data pull-up to 3.3 V, typically 4.7–10 kΩ. Check sensor pin order with power disconnected.
Procedure: Use the real sensor driver rather than fakepi. Compare temperature with a colocated calibrated reference after stabilization; respect documented sample intervals. No fabricated zero for failed reads.
Declare prediction, tolerance and uncertainty before measurements. Collect at least three readings under the same condition. If hardware is unavailable, record the limitation; do not fabricate readings.
Within tolerance requires every absolute error plus declared uncertainty to lie within tolerance. If any interval is entirely outside, the result is outside; overlap is inconclusive. User-attested evidence is not independent hardware validation.
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.
Inspect source-aligned signals, make a prediction, compare the idealized readings and export model evidence. This is supplementary to the practical procedure.
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
# P32 · Lab 32 · DHT22 temperature and humidity
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## Theory and purpose
DHT22 produces temperature and relative humidity readings. Invalid sensor samples must be rejected; a simulated sample is not a physical reading. Respect the physical sensor sampling interval of at least two seconds.
**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
# =====================================================================
# P32 | Code cell 01 | Lab 32 · DHT22 temperature and humidity
# 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.
# =====================================================================
# Fictional sensor readings (°C, %RH); None represents a failed acquisition.
samples=[None,(31.5,40.0),(32.0,41.0)]
# Define the reusable operation read with retry; keep its logic separate from the trial.
def read_with_retry(samples, max_attempts):
for attempt, sample in enumerate(samples[:max_attempts],1):
if sample is not None and 0 <= sample[1] <= 100:
return attempt,sample
return max_attempts,None
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P32 | Code cell 02 | Lab 32 · DHT22 temperature and humidity
# 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.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for limit in (1,2,3):
print(limit,read_with_retry(samples,limit))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert read_with_retry(samples,1)[1] is None
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert read_with_retry(samples,2)==(2,(31.5,40.0))
## Independent investigation and submission
Keep samples fixed and vary retry limit 1, 2 and 3. Record attempts and success/failure; explain why a failed read must not be treated as zero humidity.
| Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation |
|---|---|---|---|---|---|
| A | baseline | | | | |
| B | one change | | | | |
| A repeat | baseline | | | | |
Save outputs and state one limitation.