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 32 · DHT22 temperature and humidity
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P32
IoT Programming and Applications

Lab 32 · DHT22 temperature and humidity

Ask Dr. Mohammad · P32 →

The fake DHT22 on GPIO23 returns a slowly changing room climate.

Design experiment & verify evidence →
P32 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP32 · DHT22 temperature and humidity
Readiness checksRevision deckEngineering workspaceRecord evidence

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

P32 · Academic orientation

Scope and objectives

Scope of the experiment

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.

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.

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.

Ubuntu WSL setup →
Before you run / verification gate

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
Illustrative acquisition state machine · invalid samples must not be logged

Scientific architecture · DHT22 sampling validity and retries

DHT22 acquisition and retry — Trigger acquisition / obey sampling interval; Check returned values / temperature and humidity; Both finite and valid? / accepted sample; Invalid / wait and retry; History / retain valid timestamped record
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.

  1. Run eight requests spaced two seconds apart. Inspect each timestamp and temperature/humidity pair.
  2. Reduce the interval to one second and inspect the alternating invalid readings.
  3. Restore 2 s and inject every second request as a failure; compare valid sample count.
  4. 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.

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

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.

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

Concept animation · operation pathway

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 32 · DHT22 temperature and humidity: operation pathwayAcquire22.2 °CAcquire22.4 °CAcquire22.3 °CAggregate(22.2+22.4+22.3)/3=22.3 °CRead the active operation, then inspect the accumulated state.

Step 1 of 4 · Acquire

Acquire

Acquire
22.2 °C

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P32 · 01 / 08Why retry DHT22 reads?Reveal explanation
Engineering 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.

P32 · 05 / 08Why avoid rapid DHT22 polling?Reveal explanation
Engineering reasoning

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
Implementation recall

FAKEPI_DHT_FAIL=0 FAKEPI_TEMP=31.5 FAKEPI_HUM=40 python dht22_new.py

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.

Build and validate this circuit in Circuit Studio →

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.
DHT22 sampling. Temperature and humidity traces.
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

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

Explore the interactive 3D electronics laboratory ↗ · 3D system simulation ↗

01 / Explore

Interactive lab simulation

Browser model

Pin and connection reference

WSL uses simulated GPIO. These are source-derived signal mappings; physical connection notes are guidance, not a claim of physical testing.

ComponentSignal / pinConnection notesSource
DHT22 DATABCM GPIO23 · physical 163.3 V power, GND, pull-up on bare sensor datalab32/dht22_new.py
P32 · 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

P32 · 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 32 · DHT22 temperature and humidity

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.

Complete lab-by-lab verification report →
Ubuntu WSL · Bash (same lab folder)
FAKEPI_DHT_FAIL=1 python dht22_new.py
echo $?
✓ Expected: Five failed attempts, explicit failure message, then exit status 1. No valid reading should appear. This is an intentional negative control.
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 8 attempts beginning at t=0, spaced 2 s apart, with every third attempt invalid, list timestamps and valid sample count.

02 · Compare or justify using evidence

Calculate success percentage; explain why a zero-filled humidity curve and a missing-value marker carry different meanings.

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.

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

  1. Run eight requests spaced two seconds apart. Inspect each timestamp and temperature/humidity pair.
  2. Reduce the interval to one second and inspect the alternating invalid readings.
  3. Restore 2 s and inject every second request as a failure; compare valid sample count.
  4. Use the original DHT22 code and observe exceptions/NaN rather than treating failed values as zero.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Two-second intervalUse reference inputs aboveValid samples: 8Record actual result
Too frequentSampling interval (s) = 1Valid samples: 4Record actual result
Intermittent failuresFail every N attempts (0 = none) = 2Valid samples: 4Record 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.

TrialIndependent changeDependent observation
Two-second intervalUse reference inputs aboveRecord actual outcome and units
Too frequentSampling interval (s) = 1Record actual outcome and units
Intermittent failuresFail every N attempts (0 = none) = 2Record 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. dht22_new.py
  3. Show the retry loop
  4. A hot room
02 / Implement

Step-by-step instructions

Before you run / verification gate

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)
  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/lab32Normally 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

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.

04

A hot room

WSL · Bash
FAKEPI_DHT_FAIL=0 FAKEPI_TEMP=31.5 FAKEPI_HUM=40 python dht22_new.py
✓ 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.

Existing live hardware bench

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.

03 / Inspect

Source code and method

labs/python/lab32/dht22_new.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Install once, inside a virtual environment (Part 1):
#   python3 -m venv --system-site-packages ~/iot-env
#   source ~/iot-env/bin/activate
#   pip install adafruit-circuitpython-dht
# ---- Current DHT22 library: retry on RuntimeError, max 5 times
import time
import board                          # Pi pin names (from Adafruit Blinka)
import adafruit_dht
 
dht = adafruit_dht.DHT22(board.D23)   # DATA on BCM GPIO23 (pin 16)
try:
    for attempt in range(5):
        try:
            t = dht.temperature
            h = dht.humidity
            if t is None or h is None or not (-40 <= t <= 80 and 0 <= h <= 100):
                raise RuntimeError("Invalid DHT22 sample")
            print(f"Temp={t:0.1f} C  Humidity={h:0.1f}%")
            break
        except RuntimeError as err:
            print("Read failed:", err)
            if attempt < 4:
                time.sleep(2.0)
    else:
        raise SystemExit("DHT22 failed after five attempts; no reading recorded.")
finally:
    dht.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

P32 · 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
# 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
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 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))
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 FAKEPI_DHT_FAIL=1 python dht22_new.py echo $? ``` ```bash python dht22_new.py ``` ```bash FAKEPI_DHT_FAIL=0.6 python dht22_new.py ``` ```bash FAKEPI_DHT_FAIL=0 FAKEPI_TEMP=31.5 FAKEPI_HUM=40 python dht22_new.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ---- Install once, inside a virtual environment (Part 1): # python3 -m venv --system-site-packages ~/iot-env # source ~/iot-env/bin/activate # pip install adafruit-circuitpython-dht # ---- Current DHT22 library: retry on RuntimeError, max 5 times import time import board # Pi pin names (from Adafruit Blinka) import adafruit_dht dht = adafruit_dht.DHT22(board.D23) # DATA on BCM GPIO23 (pin 16) try: for attempt in range(5): try: t = dht.temperature h = dht.humidity if t is None or h is None or not (-40 <= t <= 80 and 0 <= h <= 100): raise RuntimeError("Invalid DHT22 sample") print(f"Temp={t:0.1f} C Humidity={h:0.1f}%") break except RuntimeError as err: print("Read failed:", err) if attempt < 4: time.sleep(2.0) else: raise SystemExit("DHT22 failed after five attempts; no reading recorded.") finally: dht.exit() ```
07Instructions · Markdown
## 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.