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 6 · DHT22 + SSD1306 OLED
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X6
IoT Programming and Applications

Lab 6 · DHT22 + SSD1306 OLED

Ask Dr. Mohammad · X6 →

The OLED is drawn in the terminal and saved as fakepi_oled.png. raspi-config and i2cdetect do not exist on WSL (no I2C bus).

Design experiment & verify evidence →
X6 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX6 · DHT22 + SSD1306 OLED
Readiness checksRevision deckEngineering workspaceRecord evidence
X6 · Academic orientation

Scope and objectives

Scope of the experiment

Trace a valid sensor sample into a display update at the configured I²C address.

The focus of this experiment is to distinguish DHT22 acquisition from SSD1306 I2C communication. Students then trace seven-bit addressing, acknowledgement and display formatting, and diagnose sensor versus bus failure using separate observations. 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 DHT22 acquisition from SSD1306 I2C communication.
  • Trace seven-bit addressing, acknowledgement and display formatting.
  • Diagnose sensor versus bus failure using separate observations.
  • Identify the configured inputs (Temperature (°C); Relative humidity (%); Configured I²C address; Virtual display address; DHT read valid) 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 DHT22 acquisition from SSD1306 I2C communication, trace seven-bit addressing, acknowledgement and display formatting, and diagnose sensor versus bus failure using separate observations.

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 diagnose sensor versus bus failure using separate observations. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 9 · ThingSpeak HTTPS upload.

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.

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

Wait for the three samples; open the resulting image in the same working directory. Use console-only as an alternative if the image is unavailable.

CONCEPTS / ACTIVE RECALL

Understand the experiment

DHT22 → Raspberry Pi → SSD1306

Logical data and I²C addressing · check physical wiring against the board manual
Logical data and I²C addressing · check physical wiring against the board manual

Scientific architecture · DHT22 OLED display and I²C addressing

DHT22 OLED bus — DHT22; Raspberry Pi; SSD1306; Read sample / 1>0; Return T,RH / 0>1; Address & data on I²C / 1>2; Display glyphs / 2>2
Scientific concept map: DHT22 sample — T and RH; Pi application — Format display strings; I²C bus — SDA / SCL; SSD1306 OLED — Address and buffer; Display — Updated text or failure.

Scientific foundations and analytical reasoning

An I²C address selects a peripheral on a shared bus; a valid sensor sample and a matching display address are separate prerequisites.

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 · I²C addressing and display updates

I²C uses shared clock and data lines with pull-ups and device addresses. The controller initiates transfers to a selected address. The SSD1306 display updates from a buffer; successful DHT22 acquisition and successful display transfer are distinct. Check voltage compatibility, address and bus wiring.

Worked example and engineering interpretation

A successful sensor reading of 24 °C and 55% RH can coexist with a blank OLED if the configured display address is wrong. Inspect bus discovery and display acknowledgments before replacing the sensor. A failed update should not imply a failed sensor reading.

Engineering principles · additional worked teaching example

I²C uses addressed transactions with shared SDA/SCL; 7-bit address 0x3D=61=0111101₂. When transmitted with write direction, address byte is 0x7A (address shifted left). Libraries usually expect the 7-bit value, not the wire byte.

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 6 · DHT22 + SSD1306 OLED

Render the mock OLED output and inspect the generated result.

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: Render the mock OLED output and inspect the generated result.

  1. At matching 0x3C address, inspect formatted temperature and humidity rows.
  2. Change configured address to 0x3D and observe no acknowledgment.
  3. Restore address and fail sensor read. Compare sensor error with I²C failure.
  4. Use the original Wokwi OLED circuit and I²C scan to confirm address and display behavior.

Reference check:

Model boundary:

Independent task and submission evidence

2. Change configured address to 0x3D and observe no acknowledgment. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

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: Temperature (°C) = 25; Relative humidity (%) = 55; Configured I²C address = 0x3C; Virtual display address = 0x3C; DHT read valid = true. In the classroom model, Display = Updated; I²C ACK = Yes. The display bytes are formatted, not sent to a real I²C bus. A closed, deterministic browser model. The existing practical instructions and source files provide independent execution; browser results are not hardware measurements.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · independent state notebook

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

Lab 6 · DHT22 + SSD1306 OLED: independent state notebook1234Calculated state 1Event / itemAddressObserved result0x3C

Step 1 of 4 · Calculated state 1

Calculated state 1

Event / item
Address
Observed result
0x3C

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X6 · 01 / 08What is SSD1306?Reveal explanation
Engineering explanation

An OLED controller used for small displays.

X6 · 02 / 08What does WSL generate?Reveal explanation
Engineering explanation

An image/console representation, not physical I2C signaling.

X6 · 03 / 08What must be checked before interpreting an SSD1306 display update?Reveal explanation
Engineering explanation

Wait for the three samples; open the resulting image in the same working directory. Use console-only as an alternative if the image is unavailable.

X6 · 04 / 08What distinguishes SSD1306 rendering from sensor acquisition?Reveal explanation
Engineering reasoning

The sensor produces data; the display renders text/pixels. Verify both stages independently.

X6 · 05 / 08Why check I2C address and bus wiring for a physical display?Reveal explanation
Engineering reasoning

An incorrect address or bus configuration prevents communication even if the sensor values are valid.

X6 · 06 / 08A DHT22 reading appears on a mock OLED. Select every technically valid statement. A. Check the displayed value against the source record. B. Physical I2C wiring and address require separate verification. C. Mock display success proves the physical I2C bus works. D. Every SSD1306 module has an identical address.Reveal explanation
Applied scenario

Correct: A. Check the displayed value against the source record.; B. Physical I2C wiring and address require separate verification.

X6 · 07 / 08In DHT22 + SSD1306 OLED, which command or code executes Console-only alternative?Reveal explanation
Implementation recall

python -m labs.exp06.oled --mock --console --count 3 --interval 0.2

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

Run the finite --count 3 program. WSL prints OLED text and writes fakepi_oled.png in the current directory when Pillow is present; the last nonblank image is retained. It does not drive I2C hardware. For console-only use --mock --console; no PNG is promised in that mode.

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 and OLED. Acquisition followed by display transfer.
DHT22 and OLED. Acquisition followed by display transfer.
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

Render the mock OLED output and inspect the generated result.

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 workbenchX6 · 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
SSD1306 SDA / SCLBCM GPIO2 · pin 3 / GPIO3 · pin 53.3 V, GND; I2C address 0x3Cexp06/oled.py
DHT22 DATABCM GPIO17 · physical 113.3 V, GND; pull-up on bare sensorlabs/pi-practical/labs/common.py
X6 · 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

X6 · 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 6 · DHT22 + SSD1306 OLED

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 mock console and fake OLED rendering executed.

Run the finite --count 3 program. WSL prints OLED text and writes fakepi_oled.png in the current directory when Pillow is present; the last nonblank image is retained. It does not drive I2C hardware. For console-only use --mock --console; no PNG is promised in that mode.

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

Convert 0x3C to decimal and seven-bit binary. Compare it with 0x3D and predict which matches the configured display.

02 · Compare or justify using evidence

For 25 °C/55% RH, predict the display fields; explain the appropriate response to a failed DHT read versus a missing display.

03 · Debugging

Debugging · Independent work

A display reports 7-bit address 0x3C but code initializes 0x78. Explain the mismatch and give both read/write wire address bytes.

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

Use the reference configuration (Temperature (°C) = 25; Relative humidity (%) = 55; Configured I²C address = 0x3C; Virtual display address = 0x3C; DHT read valid = true), but change Virtual display address = 0x3D. The model reports Display = No ACK. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · X6-02

The reference model reports Display: Updated. Under Virtual display address = 0x3D it reports No ACK. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

Intermediate · Interpret a technical trace

Independent theoretical exercise · X6-03

For Configured I²C address = 0x3D, the model supplies this excerpt from Execution observations: Event / item · Observed result Address · 0x3D Sensor valid · Yes OLED row 1 · No ACK Count rows whose Observed result value is exactly “0x3D”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · X6-04

An observation is Display = No ACK. Candidate A uses Temperature (°C) = 25; Relative humidity (%) = 55; Configured I²C address = 0x3C; Virtual display address = 0x3C; DHT read valid = true. Candidate B changes the listed settings (Configured I²C address = 0x3D) 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 · X6-05

A student configures DHT read valid = false while preserving all other reference settings, but copies the reference report of Display = Updated. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X6-06

Design a controlled comparison for Lab 6 · DHT22 + SSD1306 OLED using reference Temperature (°C) = 25; Relative humidity (%) = 55; Configured I²C address = 0x3C; Virtual display address = 0x3C; DHT read valid = true and test Virtual display address = 0x3D. Specify the changed setting(s), measured metric Display, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Trace a valid sensor sample into a display update at the configured I²C address.

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.

Temperature (°C)25
Relative humidity (%)55
Configured I²C address0x3C
Virtual display address0x3C
DHT read validYes

2 · Perform the investigation in order

  1. At matching 0x3C address, inspect formatted temperature and humidity rows.
  2. Change configured address to 0x3D and observe no acknowledgment.
  3. Restore address and fail sensor read. Compare sensor error with I²C failure.
  4. Use the original Wokwi OLED circuit and I²C scan to confirm address and display behavior.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Display referenceUse reference inputs aboveDisplay: UpdatedRecord actual result
Address mismatchConfigured I²C address = 0x3DDisplay: No ACKRecord actual result
Sensor errorDHT read valid = NoDisplay: Sensor errorRecord actual result

4 · Analyze and report

I²C addressing and sensor validity are independent.

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
Display referenceUse reference inputs aboveRecord actual outcome and units
Address mismatchConfigured I²C address = 0x3DRecord actual outcome and units
Sensor errorDHT read valid = NoRecord 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 common sensor model; mock samples and in-memory output. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Run simulated OLED
  2. Open the last display image
  3. Console-only alternative
02 / Implement

Step-by-step instructions

Before you run / verification gate

Wait for the three samples; open the resulting image in the same working directory. Use console-only as an alternative if the image is unavailable.

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

Run simulated OLED

The fake Pi sensor path is now labelled fakepi; the last nonblank image remains after cleanup.

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
python -m labs.exp06.oled --count 3 --interval 3
✓ Expected: Three samples printed to virtual OLED.
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/pi-practicalNormally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
  3. python -m labs.exp06.oled --count 3 --interval 3Three samples printed to virtual OLED.
Checkpoint Three samples printed to virtual OLED.
02

Open the last display image

Run in same directory.

WSL · Bash
explorer.exe .
✓ Expected: Windows File Explorer opens the current Linux folder; no terminal output is normally required.
Checkpoint Open fakepi_oled.png from Explorer.
03

Console-only alternative

No OLED driver required.

WSL · Bash
python -m labs.exp06.oled --mock --console --count 3 --interval 0.2
✓ Expected: Three mock readings printed.
Checkpoint Three mock readings printed.

Experimental notebook

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

03 / Inspect

Source code and method

labs/pi-practical/labs/exp06/oled.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / OLED
# ====================================================================
"""Experiment 6: show temperature and humidity on a 128x64 I2C SSD1306."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
from labs.common import parser, sensor, samples

# ====================================================================
# 02 / SELECT DISPLAY MODE
# ====================================================================
def main():
    p = parser(__doc__)
    # Allow console-only testing without an attached OLED.
    p.add_argument('--console', action='store_true', help='Display text in terminal rather than OLED')
    a = p.parse_args()
    oled = None
    # ====================================================================
    # 03 / INITIALIZE THE I2C DISPLAY
    # ====================================================================
    if not a.console:
        import board
        import adafruit_ssd1306
        # Create a 128x64 OLED object at I2C address 0x3C.
        oled = adafruit_ssd1306.SSD1306_I2C(128, 64, board.I2C(), addr=0x3c)
    # ====================================================================
    # 04 / MEASURE AND RENDER THE SCREEN
    # ====================================================================
    try:
        with sensor(a.mock) as device:
            for r in samples(device, a.interval, a.count):
                # Format temperature, humidity and data source as four display lines.
                lines = ['ENVIRONMENT', f'Temp: {r.temperature:.1f} C', f'Hum: {r.humidity:.1f} %', r.source.upper()]
                #  '|Mirror the screen contents in the terminal for debugging.
                print(' | '.join(lines), flush=True)
                if oled:
                    # Clear the local pixel framebuffer.
                    oled.fill(0)
                    # Draw each line at a separate vertical position.
                    for i, line in enumerate(lines): oled.text(line, 0, i*15, 1)
                    # Transfer the framebuffer to the physical display.
                    # Send the completed framebuffer to the display over I2C.
                    oled.show()
    # ====================================================================
    # 05 / CLEAR THE DISPLAY ON EXIT
    # ====================================================================
    finally:
        if oled:
            # Clear the local pixel framebuffer.
            oled.fill(0); oled.show()

# ====================================================================
# PROGRAM ENTRY POINT / RUN THE EXPERIMENT
# ====================================================================
if __name__ == '__main__':
    try: main()
    except KeyboardInterrupt: pass
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

X6 · 11 notebook cells · 3 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
# x6 · Lab 6 · DHT22 + SSD1306 OLED **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Render the mock OLED output and inspect the generated result. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Original common sensor model; mock samples and in-memory output. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation Render the mock OLED output and inspect the generated result. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. At matching 0x3C address, inspect formatted temperature and humidity rows. 2. Change configured address to 0x3D and observe no acknowledgment. 3. Restore address and fail sensor read. Compare sensor error with I²C failure. 4. Use the original Wokwi OLED circuit and I²C scan to confirm address and display behavior. **Evidence:** **Boundary:**
03Instructions · Markdown
## 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy. - Distinguish actual local Python execution from mock, physical and external-service observations. ## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# X6 | Code cell 01 | Lab 6 · DHT22 + SSD1306 OLED
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# X6 | Code cell 02 | Lab 6 · DHT22 + SSD1306 OLED
# Purpose: implement only the mechanism named in this laboratory.
# Inputs: the explicit fictional fixture and reference parameters below.
# Output: printed observations and assertions for the controlled trial.
# =====================================================================
import json

import math

import os

import time

from datetime import datetime, timezone

from dataclasses import dataclass, asdict

@dataclass(frozen=True)
# ====================================================================
# 01 / READING DATA MODEL
# ====================================================================
class Reading:
    # Unique identifier distinguishes multiple devices.
    sensor_id: str
    # UTC ISO-8601 time allows consistent comparisons across devices.
    timestamp: str
    temperature: float
    humidity: float
    # Distinguish generated demo readings from physical measurements.
    source: str

    def json(self):
        # Convert the dataclass to JSON; reject NaN values.
        return json.dumps(asdict(self), allow_nan=False)

class Sensor:
    def __init__(self, mock=False):
        self.mock = mock
        self.simulated_driver = False
        self.index = 0
        # Read an optional sensor identifier from the environment.
        self.sensor_id = os.getenv('SENSOR_ID', 'dht22-01')
        self.device = None
        self.last_read = 0.0
        # Load Raspberry Pi hardware libraries only for physical acquisition.
        if not mock:
            import board
            import adafruit_dht
            self.simulated_driver = getattr(adafruit_dht, "SIMULATED", False)
            # GPIO17 is BCM numbering; use the DHT22 single-data-wire protocol.
            self.device = adafruit_dht.DHT22(board.D17, use_pulseio=False)

    # ====================================================================
    # 03 / ACQUIRE AND VALIDATE A SAMPLE
    # ====================================================================
    def read(self):
        # Protect the physical DHT22 against excessively frequent polling.
        # Generate repeatable values for testing without a sensor.
        if self.mock:
            # Produce a slowly varying temperature in degrees Celsius.
            t = round(23 + 3 * math.sin(self.index / 5), 1)
            # Produce a slowly varying relative humidity percentage.
            h = round(55 + 8 * math.cos(self.index / 5), 1)
            self.index += 1
        else:
            # Retry transient DHT timing or checksum failures up to five times.
            for attempt in range(5):
                # Enforce at least 2.1 seconds between real sensor read attempts.
                time.sleep(max(0, 2.1 - (time.monotonic() - self.last_read)))
                self.last_read = time.monotonic()
                try:
                    # Read both quantities from the DHT22 driver.
                    t, h = self.device.temperature, self.device.humidity
                    # Accept only available readings with humidity in its physical range.
                    if t is not None and h is not None and 0 <= h <= 100:
                        break
                except RuntimeError:
                    pass  # DHT checksum/timing error: retry at a safe interval.
            else:
                # Report persistent failures instead of inventing a valid reading.
                raise RuntimeError('DHT22 failed after five attempts; check wiring.')
        # Attach acquisition time, sensor identity and provenance.
        return Reading(self.sensor_id, datetime.now(timezone.utc).isoformat(),
                       float(t), float(h), 'mock' if self.mock else ('fakepi' if self.simulated_driver else 'hardware'))

    # ====================================================================
    # 04 / RELEASE THE SENSOR
    # ====================================================================
    def close(self):
        if self.device is not None:
            # Release the hardware resources allocated by the DHT driver.
            self.device.exit()
Ask Dr. Mohammad about this cell
07Instructions · Markdown
### Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# X6 | Code cell 03 | Lab 6 · DHT22 + SSD1306 OLED
# Purpose: Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Set sensor for the next computation or reference condition.
sensor=Sensor(mock=True)
try: readings=[sensor.read() for _ in range(3)]
finally: sensor.close()
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
print([r.json() for r in readings]);assert len(readings)==3 and all(r.source=='mock' and 0<=r.humidity<=100 for r in readings)
print('OLED console preview:',f'{readings[-1].temperature} C | {readings[-1].humidity}%')
Ask Dr. Mohammad about this cell
09Instructions · 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 source ~/psut-wsl/activate.sh cd ~/psut-wsl/labs/pi-practical python -m labs.exp06.oled --count 3 --interval 3 ``` ```bash python -m labs.exp06.oled --mock --console --count 3 --interval 0.2 ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / OLED # ==================================================================== """Experiment 6: show temperature and humidity on a 128x64 I2C SSD1306.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== from labs.common import parser, sensor, samples # ==================================================================== # 02 / SELECT DISPLAY MODE # ==================================================================== def main(): p = parser(__doc__) # Allow console-only testing without an attached OLED. p.add_argument('--console', action='store_true', help='Display text in terminal rather than OLED') a = p.parse_args() oled = None # ==================================================================== # 03 / INITIALIZE THE I2C DISPLAY # ==================================================================== if not a.console: import board import adafruit_ssd1306 # Create a 128x64 OLED object at I2C address 0x3C. oled = adafruit_ssd1306.SSD1306_I2C(128, 64, board.I2C(), addr=0x3c) # ==================================================================== # 04 / MEASURE AND RENDER THE SCREEN # ==================================================================== try: with sensor(a.mock) as device: for r in samples(device, a.interval, a.count): # Format temperature, humidity and data source as four display lines. lines = ['ENVIRONMENT', f'Temp: {r.temperature:.1f} C', f'Hum: {r.humidity:.1f} %', r.source.upper()] # '|Mirror the screen contents in the terminal for debugging. print(' | '.join(lines), flush=True) if oled: # Clear the local pixel framebuffer. oled.fill(0) # Draw each line at a separate vertical position. for i, line in enumerate(lines): oled.text(line, 0, i*15, 1) # Transfer the framebuffer to the physical display. # Send the completed framebuffer to the display over I2C. oled.show() # ==================================================================== # 05 / CLEAR THE DISPLAY ON EXIT # ==================================================================== finally: if oled: # Clear the local pixel framebuffer. oled.fill(0); oled.show() # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
10Instructions · Markdown
## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Original common sensor model; mock samples and in-memory output. Notebook success does not certify external equipment or services.
11Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Change configured address to 0x3D and observe no acknowledgment. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.