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 4 · Digital input: button, IR & LDR
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Pi practical / X4
IoT Programming and Applications

Lab 4 · Digital input: button, IR & LDR

Ask Dr. Mohammad · X4 →

GPIO25 (button) or GPIO22 (IR / LDR module) controls the LED on GPIO24.

Design experiment & verify evidence →
X4 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingX4 · Digital input: button, IR & LDR
Readiness checksRevision deckEngineering workspaceRecord evidence
X4 · Academic orientation

Scope and objectives

Scope of the experiment

Reproduce the --input and --active-low options in exp04.digital_input; mirror one selected logical input to the LED.

The focus of this experiment is to interpret button, IR and light-threshold digital inputs. Students then trace active levels, threshold changes and invalid wiring symptoms, and compare controlled input states and classify the output decision. 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

  • Interpret button, IR and light-threshold digital inputs.
  • Trace active levels, threshold changes and invalid wiring symptoms.
  • Compare controlled input states and classify the output decision.
  • Identify the configured inputs (Input selected; GPIO logic level; Module active-low (IR/LDR only)) 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 interpret button, IR and light-threshold digital inputs, trace active levels, threshold changes and invalid wiring symptoms, and compare controlled input states and classify the output decision.

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 compare controlled input states and classify the output decision. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 5 · DHT22 environmental data logger.

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.

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

Each of the button, IR and LDR commands runs continuously. Stop with Ctrl+C after observing the scheduled transition and before starting the next command.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Single digital input → GPIO24 LED

Digital sensor polarity — Select sensor / button, IR or LDR module; Read digital input / 0 or 1; Apply active-high or active-low rule / normalized detection; GPIO24 LED / output; Observation / compare actual polarity
Scientific concept map: Selected sensor — Button / IR / LDR; Digital threshold — Raw HIGH / LOW; Polarity rule — Active high or low; GPIO24 — LED output; Observation — Truth table.

Scientific foundations and analytical reasoning

A digital sensor reports a binary level; module polarity determines whether LOW or HIGH indicates detection. A pull-up button is active low.

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 · Threshold sensors and polarity

An IR detector or LDR module may expose a comparator output that reports whether a signal crosses an adjustable threshold. A digital result is not a calibrated distance or light intensity. The same voltage level can represent opposite physical meanings depending on the module polarity.

Worked example and engineering interpretation

For a pull-up button, released=HIGH and pressed=LOW. An active-low detector similarly reports LOW on detection, whereas active-high uses HIGH. Build a truth table for each configured sensor before combining them; observe the actual polarity rather than guessing from the sensor name.

Engineering principles · additional worked teaching example

A digital sensor module produces a thresholded logic signal; active-low means a physical detection corresponds to 0. If detection drives LED on, inverse logic is required for active-low, direct for active-high. An LDR module's digital output is not a lux measurement.

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 4 · Digital input: button, IR & LDR

The selected digital input is either button, IR or LDR; each sensor exposes a single digital level. Pull-up buttons are active-low; module polarity may be configurable. Digital LDR output does not measure lux.

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: Observe IR and LDR digital input behavior and stop continuous loops.

  1. Choose button, raw LOW. GPIO25 uses pull-up, so LOW represents pressed. The LED on BCM24 is ON.
  2. Select IR and set GPIO22 HIGH; with --active-low absent, the logical input is active. Toggle --active-low and observe the inverted LED decision.
  3. Select LDR and repeat for raw HIGH and LOW. The physical sensor module sets its digital threshold; no analog lux is inferred.
  4. Run the supplied digital_input.py with exactly one --input selection and the corresponding polarity. The source does not combine the three sensors or use AND/OR logic.

Reference check:

Model boundary:

Independent task and submission evidence

For IR and LDR hold the raw value HIGH and toggle polarity. Record logical LED state, then repeat LOW. Explain why this does not combine three sensors or infer lux.

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: Input selected = button; GPIO logic level = 0; Module active-low (IR/LDR only) = false. In the classroom model, Logical active = Yes; Output = ON. One input at a time; no combined actuator logic. 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 4 · Digital input: button, IR & LDR: independent state notebook12345Calculated state 1StageSelected inputValuebutton

Step 1 of 5 · Calculated state 1

Calculated state 1

Stage
Selected input
Value
button

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

Recall the concept before revealing its explanation.

0 / 3 revealed
X4 · 01 / 08What is a digital sensor output?Reveal explanation
Engineering explanation

A binary logic level; its active polarity depends on module and configuration.

X4 · 02 / 08What does --active-low mean?Reveal explanation
Engineering explanation

The LOW level is interpreted as active.

X4 · 03 / 08What input polarity and virtual sensor conditions must be checked?Reveal explanation
Engineering explanation

Each of the button, IR and LDR commands runs continuously. Stop with Ctrl+C after observing the scheduled transition and before starting the next command.

X4 · 04 / 08Why can LDR module digital output differ from light intensity?Reveal explanation
Engineering reasoning

A comparator threshold converts analog light-dependent voltage to a digital state; the output polarity depends on circuit wiring.

X4 · 05 / 08Why test both input states?Reveal explanation
Engineering reasoning

A single observation cannot distinguish a stuck input from correct transition behavior.

X4 · 06 / 08An IR and LDR module provide digital readings. Select every technically valid statement. A. Check the module's polarity and threshold behavior. B. Digital readings do not directly quantify illumination. C. Digital HIGH always means bright light for every module. D. A digital pin measures calibrated lux without conversion.Reveal explanation
Applied scenario

Correct: A. Check the module's polarity and threshold behavior.; B. Digital readings do not directly quantify illumination.

X4 · 07 / 08In Digital input: button, IR & LDR, which command or code executes LDR module?Reveal explanation
Implementation recall

FAKEPI_HIGH=22@1-2 python -m labs.exp04.digital_input --input ldr

X4 · 08 / 08For Digital input: button, IR & LDR, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run each of the three continuous commands separately and stop it with Ctrl+C before the next. Button uses BCM25; IR/LDR digital signal uses BCM22. For scheduled HIGH from 1 to 2 s, active-low IR is inactive during HIGH, while active-high LDR is active. Record logical state, not a physical optical measurement.

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.
Digital sensor input. Input polarity and output logic.
Digital sensor input. Input polarity and output logic.
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

Observe IR and LDR digital input behavior and stop continuous loops.

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 workbenchX4 · 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
ButtonBCM GPIO25 · physical 22Button to GNDexp04/digital_input.py
IR / LDR digital signalBCM GPIO22 · physical 153.3 V logic; active-low optionexp04/digital_input.py
LEDBCM GPIO24 · physical 18Resistor to GNDexp04/digital_input.py
X4 · 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

X4 · 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 4 · Digital input: button, IR & LDR

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: Source/model reviewed; GPIO Zero runtime pending.

Run each of the three continuous commands separately and stop it with Ctrl+C before the next. Button uses BCM25; IR/LDR digital signal uses BCM22. For scheduled HIGH from 1 to 2 s, active-low IR is inactive during HIGH, while active-high LDR is active. Record logical state, not a physical optical measurement.

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

Build truth tables for a pull-up button and IR/LDR modules configured active-high or active-low. For each input level predict the GPIO24 LED state.

02 · Compare or justify using evidence

Explain why digital LDR threshold status is not a calibrated lux reading; identify a suitable independent measurement.

03 · Truth table

Truth table · Independent work

A button uses pull-up; IR detects an object at LOW; LDR asserts HIGH in bright light. For observed inputs 0,1,1 respectively, determine the semantic states and which LED should light for each asserted condition.

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

Use the reference configuration (Input selected = button; GPIO logic level = 0; Module active-low (IR/LDR only) = false), but change Input selected = ir. The model reports Logical active = No. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · X4-02

The reference model reports Logical active: Yes. Under Input selected = ir it reports No. 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 · X4-03

For GPIO logic level = 1, the model supplies this excerpt from Input decoding: Stage · Value Selected input · button BCM input pin · 25 Raw electrical state · HIGH Logical active · No BCM24 LED · OFF Count rows whose Value value is exactly “button”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · X4-04

An observation is Logical active = No. Candidate A uses Input selected = button; GPIO logic level = 0; Module active-low (IR/LDR only) = false. Candidate B changes the listed settings (GPIO logic level = 1) 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 · X4-05

A student configures Input selected = ir; GPIO logic level = 1; Module active-low (IR/LDR only) = true while preserving all other reference settings, but copies the reference report of Logical active = Yes. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · X4-06

Design a controlled comparison for Lab 4 · Digital input: button, IR & LDR using reference Input selected = button; GPIO logic level = 0; Module active-low (IR/LDR only) = false and test Input selected = ir. Specify the changed setting(s), measured metric Logical active, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Reproduce the --input and --active-low options in exp04.digital_input; mirror one selected logical input to the LED.

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.

Input selectedbutton
GPIO logic level0
Module active-low (IR/LDR only)No

2 · Perform the investigation in order

  1. Choose button, raw LOW. GPIO25 uses pull-up, so LOW represents pressed. The LED on BCM24 is ON.
  2. Select IR and set GPIO22 HIGH; with --active-low absent, the logical input is active. Toggle --active-low and observe the inverted LED decision.
  3. Select LDR and repeat for raw HIGH and LOW. The physical sensor module sets its digital threshold; no analog lux is inferred.
  4. Run the supplied digital_input.py with exactly one --input selection and the corresponding polarity. The source does not combine the three sensors or use AND/OR logic.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Pressed buttonUse reference inputs aboveOutput: ON; Logical active: YesRecord actual result
Released buttonGPIO logic level = 1Output: OFFRecord actual result
IR active-highInput selected = ir; GPIO logic level = 1Output: ONRecord actual result
IR active-lowInput selected = ir; GPIO logic level = 1; Module active-low (IR/LDR only) = YesOutput: OFFRecord actual result

4 · Analyze and report

Distinguish electrical level and logical activity.

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
Pressed buttonUse reference inputs aboveRecord actual outcome and units
Released buttonGPIO logic level = 1Record actual outcome and units
IR active-highInput selected = ir; GPIO logic level = 1Record actual outcome and units
IR active-lowInput selected = ir; GPIO logic level = 1; Module active-low (IR/LDR only) = YesRecord 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

Stateful virtual GPIO with explicit direction, input stimulation, PWM and verification; optional real MQTT telemetry exercise. Default profile executed in an isolated local Python kernel. Live services and physical hardware are separate acceptance tasks.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. Open a terminal in the project root
  2. Button
  3. IR module (active-low output)
  4. LDR module
02 / Implement

Step-by-step instructions

Before you run / verification gate

Each of the button, IR and LDR commands runs continuously. Stop with Ctrl+C after observing the scheduled transition and before starting the next command.

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 in the project root

WSL · Bash
source ~/psut-wsl/activate.sh
cd ~/psut-wsl/labs/pi-practical
✓ Expected: Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
Expected result for each action (2)
  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.
Checkpoint you are in the folder that contains labs/ ; every command is python -m labs.expNN.… as on the page.
02

Button

WSL · Bash
FAKEPI_PRESS=25@1 python -m labs.exp04.digital_input --input button    # Ctrl+C
✓ Expected: button: active=False , then active=True, LED=True with GPIO24 = HIGH , then back to False.
Checkpoint button: active=False , then active=True, LED=True with GPIO24 = HIGH , then back to False.

After the scheduled transition (about 3 seconds), press Ctrl+C. Wait for the shell prompt before running the next variant.

03

IR module (active-low output)

WSL · Bash
FAKEPI_HIGH=22@1-2 python -m labs.exp04.digital_input --input ir --active-low
✓ Expected: ir: active=True while the line is LOW, active=False from 1 to 2 s (line HIGH = nothing detected).
Checkpoint ir: active=True while the line is LOW, active=False from 1 to 2 s (line HIGH = nothing detected).

After the scheduled transition (about 3 seconds), press Ctrl+C. Wait for the shell prompt before running the next variant.

04

LDR module

WSL · Bash
FAKEPI_HIGH=22@1-2 python -m labs.exp04.digital_input --input ldr
✓ Expected: ldr: active=True, LED=True only between 1 and 2 s.
Checkpoint ldr: active=True, LED=True only between 1 and 2 s.

After the scheduled transition (about 3 seconds), press Ctrl+C. Wait for the shell prompt before running the next variant.

Experimental notebook

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

03 / Inspect

Source code and method

labs/pi-practical/labs/exp04/digital_input.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ====================================================================
# LAB PURPOSE / DIGITAL INPUT
# ====================================================================
"""Experiment 4: a button or digital IR/LDR module controls GPIO24 LED."""

# ====================================================================
# 01 / IMPORT REQUIRED LIBRARIES
# ====================================================================
import argparse
from time import sleep

# ====================================================================
# 02 / SELECT THE INPUT DEVICE
# ====================================================================
def main():
    p = argparse.ArgumentParser(description=__doc__)
    # Choose the push-button, IR detector or LDR digital module.
    p.add_argument('--input', choices=['button','ir','ldr'], default='button')
    # Invert sensor polarity when its digital output is active-low.
    p.add_argument('--active-low', action='store_true', help='For sensor modules with active-low DO')
    a = p.parse_args()
    from gpiozero import Button, DigitalInputDevice, LED
    # Button uses GPIO25; a 3.3 V digital module uses GPIO22.
    # ====================================================================
    # 03 / INITIALIZE GPIO INPUT AND LED
    # ====================================================================
    inp = Button(25, pull_up=True, bounce_time=0.05) if a.input == 'button' else DigitalInputDevice(22, pull_up=None, active_state=not a.active_low)
    # Open the selected input and start GPIO24 with the LED off.
    with inp, LED(24, initial_value=False) as led:
        previous = None
        # ====================================================================
        # 04 / READ INPUT AND UPDATE THE OUTPUT
        # ====================================================================
        while True:
            # Read the logical state using the selected active polarity.
            active = inp.is_active
            # Only react to a state transition.
            if active != previous:
                # Mirror the logical sensor state on the LED.
                led.value = active
                print(f'{a.input}: active={active}, LED={active}', flush=True)
                previous = active
            # Poll the digital input every 50 ms.
            sleep(0.05)

# ====================================================================
# 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

X4 · 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
# X4 · Lab 4 · Digital input: button, IR & LDR **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose The selected digital input is either button, IR or LDR; each sensor exposes a single digital level. Pull-up buttons are active-low; module polarity may be configurable. Digital LDR output does not measure lux. **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
# =====================================================================
# X4 | Code cell 01 | Lab 4 · Digital input: button, IR & LDR
# 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.
# =====================================================================
# Define the reusable operation led state; keep its logic separate from the trial.
def led_state(sensor, raw, active_low=False):
    if sensor not in ('button','ir','ldr') or raw not in (0,1): raise ValueError('Choose one digital input')
    return bool(1-raw if sensor=='button' or active_low else raw)
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# X4 | Code cell 02 | Lab 4 · Digital input: button, IR & LDR
# 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 sensor in ('button','ir','ldr'):
    for raw in (0,1): print(sensor,raw,led_state(sensor,raw))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert led_state('button',0) and not led_state('button',1)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert not led_state('ir',1,True)
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_PRESS=25@1 python -m labs.exp04.digital_input --input button # Ctrl+C ``` ```bash FAKEPI_HIGH=22@1-2 python -m labs.exp04.digital_input --input ir --active-low ``` ```bash FAKEPI_HIGH=22@1-2 python -m labs.exp04.digital_input --input ldr ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ # ==================================================================== # LAB PURPOSE / DIGITAL INPUT # ==================================================================== """Experiment 4: a button or digital IR/LDR module controls GPIO24 LED.""" # ==================================================================== # 01 / IMPORT REQUIRED LIBRARIES # ==================================================================== import argparse from time import sleep # ==================================================================== # 02 / SELECT THE INPUT DEVICE # ==================================================================== def main(): p = argparse.ArgumentParser(description=__doc__) # Choose the push-button, IR detector or LDR digital module. p.add_argument('--input', choices=['button','ir','ldr'], default='button') # Invert sensor polarity when its digital output is active-low. p.add_argument('--active-low', action='store_true', help='For sensor modules with active-low DO') a = p.parse_args() from gpiozero import Button, DigitalInputDevice, LED # Button uses GPIO25; a 3.3 V digital module uses GPIO22. # ==================================================================== # 03 / INITIALIZE GPIO INPUT AND LED # ==================================================================== inp = Button(25, pull_up=True, bounce_time=0.05) if a.input == 'button' else DigitalInputDevice(22, pull_up=None, active_state=not a.active_low) # Open the selected input and start GPIO24 with the LED off. with inp, LED(24, initial_value=False) as led: previous = None # ==================================================================== # 04 / READ INPUT AND UPDATE THE OUTPUT # ==================================================================== while True: # Read the logical state using the selected active polarity. active = inp.is_active # Only react to a state transition. if active != previous: # Mirror the logical sensor state on the LED. led.value = active print(f'{a.input}: active={active}, LED={active}', flush=True) previous = active # Poll the digital input every 50 ms. sleep(0.05) # ==================================================================== # PROGRAM ENTRY POINT / RUN THE EXPERIMENT # ==================================================================== if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ```
07Instructions · Markdown
## Independent investigation and submission For IR and LDR hold the raw value HIGH and toggle polarity. Record logical LED state, then repeat LOW. Explain why this does not combine three sensors or infer lux. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.