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 31 · PWM brightness and alternate functions
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
Python & IoT / P31
IoT Programming and Applications

Lab 31 · PWM brightness and alternate functions

Ask Dr. Mohammad · P31 →

PWMLED on GPIO18: the fake pin prints the duty cycle.

Design experiment & verify evidence →
P31 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Core IoT & programmingP31 · PWM brightness and alternate functions
Readiness checksRevision deckEngineering workspaceRecord evidence
P31 · Academic orientation

Scope and objectives

Scope of the experiment

Calculate timer period, HIGH time and ideal average output voltage.

The focus of this experiment is to relate PWM frequency, period, pulse width and duty ratio. Students then calculate HIGH duration and average voltage under the ideal switching model, and compare duty settings while distinguishing waveform changes from perceived brightness. 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

  • Relate PWM frequency, period, pulse width and duty ratio.
  • Calculate HIGH duration and average voltage under the ideal switching model.
  • Compare duty settings while distinguishing waveform changes from perceived brightness.
  • Identify the configured inputs (PWM frequency (Hz); Duty cycle (%); HIGH voltage (V)) 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 relate PWM frequency, period, pulse width and duty ratio, calculate HIGH duration and average voltage under the ideal switching model, and compare duty settings while distinguishing waveform changes from perceived brightness.

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 duty settings while distinguishing waveform changes from perceived brightness. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to Lab 32 · DHT22 temperature and humidity.

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.

P31 / 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 finite fade sequence to finish; inspect cleanup LOW. The printed pin map is a reference, not board discovery.

CONCEPTS / ACTIVE RECALL

Understand the experiment

PWM duty cycle and average output

100 Hz reference: 10 ms per period, ideal 3.3 V output
100 Hz reference: 10 ms per period, ideal 3.3 V output

Scientific architecture · PWM duty cycle and waveform

PWM duty cycle — Period / 10 ms at 100 Hz; HIGH / 6 ms at 60%; LOW / 4 ms; Mean / 1.98 V at 3.3 V; LED / duty-cycle control
Scientific concept map: Duty cycle D — HIGH fraction; PWM generator — Period \(T=\frac{1}{f}\); GPIO waveform — HIGH / LOW; LED load — Average V≈D·Vcc; Timing — Ton=D·T.

Scientific foundations and analytical reasoning

PWM changes the time fraction at HIGH, not the high-state voltage. \(T=\frac{1}{f}\), ton=D*T and ideal average voltage=D*Vhigh.

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 · Pulse-width modulation

PWM switches between two voltage levels with period \(T=\frac{1}{f}\). The duty factor D is the fraction of the period spent HIGH, so \(t_{\mathrm{on}}=DT\) and \(t_{\mathrm{off}}=(1-D)T\). Average voltage equals DVhigh for ideal zero-low switching; RMS voltage equals \(V_{\mathrm{high}}\sqrt D\). Perceived LED brightness is not necessarily linear in either value.

Worked example and engineering interpretation

For 500 Hz and 60% duty, T=2 ms, ton=1.2 ms and average voltage=1.98 V at 3.3 V HIGH. The peak voltage remains 3.3 V. Compare waveforms at fixed frequency while varying duty; an oscilloscope can distinguish PWM from a constant analog voltage.

Engineering principles · additional worked teaching example

PWM switches a digital output; duty D=tHIGH/T and f=1/T. At 250 Hz, T=4 ms; D=.30 gives 1.2 ms high and 0.99 V mean for ideal 3.3 V switching. A scope reveals pulses, not a continuous 0.99 V source; LED perception is nonlinear.

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 31 · PWM brightness and alternate functions

PWM alternates HIGH and LOW. \(T=\frac{1}{f}\); HIGH time = duty × T; ideal average voltage = 3.3 × duty. Real LED brightness is not necessarily linear with duty.

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: Change PWM duty cycle and explain its relationship to LED brightness.

  1. Start at 100 Hz / 50%. Confirm 10 ms period and 5 ms HIGH time.
  2. Set duty to 25%, 100% and 0%; compare waveform and average voltage.
  3. Double frequency with duty fixed and explain why ideal average voltage is unchanged.
  4. Run the original PWM example; compare the duty commands and measured or virtual waveform.

Reference check:

Model boundary:

Independent task and submission evidence

At 100 Hz vary duty from 25% to 75%; record period, HIGH duration and mean voltage. Then hold duty at 50% and double frequency; explain which measurements change.

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

PWM duty D=t_high/T, frequency f=1/T. For 1 kHz and 25%, T=1 ms and high=0.25 ms. Ideal mean of 0/3.3 V is 0.825 V, not a constant analog output. Quantized duty with N discrete ticks uses k/N.

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

PWM timing

f is in hertz, T and t_HIGH are in seconds, D is a dimensionless duty ratio. The ideal average voltage is not a universal model of perceived brightness or motor speed.

\[T=\frac1f,\quad D=\frac{t_{\mathrm{HIGH}}}{T},\qquad \bar V=D V_H+(1-D)V_L\]

At 500 Hz, T=2 ms. A 25% duty cycle gives 0.5 ms HIGH and 1.5 ms LOW.

Concept animation · PWM timing waveform

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 31 · PWM brightness and alternate functions: PWM timing waveform3.3 V0 V0–1 ms1–2 ms2–3 msT = 1 ms

Step 1 of 4 · Period from frequency

Period from frequency

f
1 kHz
T
1 ms

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

Recall the concept before revealing its explanation.

0 / 3 revealed
P31 · 01 / 08What is duty cycle?Reveal explanation
Engineering explanation

The fraction of each PWM period that the output is HIGH.

P31 · 02 / 08How does PWM control brightness?Reveal explanation
Engineering explanation

Average LED energy changes with duty cycle; GPIO voltage is not continuously adjusted.

P31 · 03 / 08What evidence distinguishes a completed PWM fade and cleanup from physical board discovery?Reveal explanation
Engineering explanation

Wait for the finite fade sequence to finish; inspect cleanup LOW. The printed pin map is a reference, not board discovery.

P31 · 04 / 08What is the ideal average of a 3.3 V PWM output at 25% duty?Reveal explanation
Engineering reasoning

0.825 V; the peak remains 3.3 V, so PWM is not the same as a true constant analog voltage.

P31 · 05 / 08What changes when duty changes but period stays fixed?Reveal explanation
Engineering reasoning

The high time changes in proportion to duty; frequency remains the reciprocal of the period.

P31 · 06 / 08An ideal PWM signal drives an LED. Select every technically valid statement. A. Duty cycle is the fraction of time spent HIGH. B. At a fixed peak current, mean current scales with duty cycle. C. Duty cycle is the same quantity as frequency. D. A 50% duty cycle necessarily halves the HIGH voltage.Reveal explanation
Applied scenario

Correct: A. Duty cycle is the fraction of time spent HIGH.; B. At a fixed peak current, mean current scales with duty cycle.

P31 · 07 / 08In PWM brightness and alternate functions, which command or code executes Alternate functions?Reveal explanation
Implementation recall

pinout -r d03114 --monochrome | sed -n "/J8:/,/40)/p"

P31 · 08 / 08For PWM brightness and alternate functions, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

BCM18 is physical pin 12. Run the finite PWM program to completion. Expected duty sequence 0,25,50,75,100%; a 100% duty is shown as HIGH, not necessarily PWM 100%. The device may switch off during cleanup. Duty-cycle traces do not measure physical PWM frequency.

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.
Pulse-width modulation. Duty cycle controls ideal average output.
Pulse-width modulation. Duty cycle controls ideal average output.
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

Change PWM duty cycle and explain its relationship to LED brightness.

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 workbenchP31 · 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
PWM LEDBCM GPIO18 · physical 12LED via current-limiting resistor to GNDlab31/pwm_fade.py
P31 · 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

P31 · 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 31 · PWM brightness and alternate functions

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

BCM18 is physical pin 12. Run the finite PWM program to completion. Expected duty sequence 0,25,50,75,100%; a 100% duty is shown as HIGH, not necessarily PWM 100%. The device may switch off during cleanup. Duty-cycle traces do not measure physical PWM frequency.

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

Calculate period, HIGH time and mean voltage at 100 Hz, 50% duty and 3.3 V. Repeat for 25% and 75%.

02 · Compare or justify using evidence

Sketch two periods for each duty cycle. Explain why average voltage is not a direct measurement of perceived LED brightness.

03 · Reverse calculation

Reverse calculation · Independent work

A 200 Hz signal is HIGH for 3.5 ms each period. Derive duty and mean at 3.3 V. Predict the effect of doubling frequency at constant duty.

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

At 400 Hz, duty 35%, calculate period and high time.

Intermediate · Calculate or trace

Independent theoretical exercise · P31-02

At 3.3 V ideal PWM and 65% duty, calculate mean.

Intermediate · Interpret the result

Independent theoretical exercise · P31-03

A 10-bit timer uses 1024 ticks per period. Choose k nearest 30% and compute achieved duty.

Advanced · Analyze a condition

Independent theoretical exercise · P31-04

At constant duty 40%, frequency doubles from 250 to 500 Hz. Compare high time and ideal mean.

Advanced · Diagnose or compare

Independent theoretical exercise · P31-05

An LED seems equally bright at 70 and 90% duty. Does that disprove PWM timing?

Challenging · Engineering verification

Independent theoretical exercise · P31-06

Design a three-duty comparison at fixed frequency.

Challenging numerical variant 1

Calculation · Independent work

An ideal 3.3 V PWM output has 40% duty at period 700 µs. It starts HIGH. Over 125 whole periods followed by an extra half-period, what is cumulative HIGH time in µs?

Challenging numerical variant 2

Calculation · Independent work

An ideal 3.3 V PWM output has 40% duty at period 800 µs. It starts HIGH. Over 125 whole periods followed by an extra half-period, what is cumulative HIGH time in µs?

Challenging numerical variant 3

Calculation · Independent work

An ideal 3.3 V PWM output has 40% duty at period 900 µs. It starts HIGH. Over 125 whole periods followed by an extra half-period, what is cumulative HIGH time in µs?

Step-by-step experimental procedure

Calculate timer period, HIGH time and ideal average output voltage.

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.

PWM frequency (Hz)100
Duty cycle (%)50
HIGH voltage (V)3.3

2 · Perform the investigation in order

  1. Start at 100 Hz / 50%. Confirm 10 ms period and 5 ms HIGH time.
  2. Set duty to 25%, 100% and 0%; compare waveform and average voltage.
  3. Double frequency with duty fixed and explain why ideal average voltage is unchanged.
  4. Run the original PWM example; compare the duty commands and measured or virtual waveform.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Half dutyUse reference inputs aboveAverage voltage: 1.65Record actual result
Quarter dutyDuty cycle (%) = 25Average voltage: 0.825Record actual result
Constant lowDuty cycle (%) = 0HIGH time: 0Record actual result

4 · Analyze and report

PWM is switching, not a true variable DC output; brightness may be nonlinear.

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
Half dutyUse reference inputs aboveRecord actual outcome and units
Quarter dutyDuty cycle (%) = 25Record actual outcome and units
Constant lowDuty cycle (%) = 0Record 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
  2. pwm_fade.py
  3. Alternate functions
02 / Implement

Step-by-step instructions

Before you run / verification gate

Wait for the finite fade sequence to finish; inspect cleanup LOW. The printed pin map is a reference, not board discovery.

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/lab31
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/lab31Normally 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

pwm_fade.py

WSL · Bash
python pwm_fade.py
✓ Expected: The mocked GPIO18 output steps through PWM 25%, 50%, 75%, HIGH and LOW on cleanup.
Checkpoint GPIO18 = PWM 25 % , 50 % , 75 % , GPIO18 = HIGH (100 %), then LOW when the program closes the LED.
03

Alternate functions

WSL · Bash
pinout -r d03114 --monochrome | sed -n "/J8:/,/40)/p"
✓ Expected: A Pi 4 reference pin map is printed. Physical pin 11 is BCM17 and physical pin 12 is BCM18; this is a reference, not hardware detection.
Checkpoint the 40-pin header: GPIO18 is physical pin 12, one of the Pi’s hardware-PWM pins.

Experimental notebook

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

Optional physical acceptance · supervised low-voltage work

PWM timing 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 BCM18 (physical pin 12), LED with 330 Ω series resistor to ground. Use a high-impedance oscilloscope input with a common ground and appropriate probe. Disconnect power before wiring.

Procedure: Run a fixed duty condition using the documented PWM settings. Measure duty cycle at the GPIO pin, not visual brightness; enter the actual configured duty as the target.

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/lab31/pwm_fade.pyDownload source
PY · source file
# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
from gpiozero import PWMLED
from time import sleep
with PWMLED(18) as led:
    for duty in range(0, 101, 25):
        led.value = duty / 100
        sleep(0.5)
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

P31 · 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
# P31 · Lab 31 · PWM brightness and alternate functions **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose PWM alternates HIGH and LOW. \(T=\frac{1}{f}\); HIGH time = duty × T; ideal average voltage = 3.3 × duty. Real LED brightness is not necessarily linear with duty. **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
# =====================================================================
# P31 | Code cell 01 | Lab 31 · PWM brightness and alternate functions
# 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 pwm; keep its logic separate from the trial.
def pwm(frequency, duty):
    if frequency <= 0 or not 0 <= duty <= 1:
        raise ValueError('Positive Hz and duty fraction 0–1 required')
    period_ms=1000/frequency
    return period_ms, period_ms*duty, 3.3*duty
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# P31 | Code cell 02 | Lab 31 · PWM brightness and alternate functions
# 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 duty in (0,.25,.5,.75,1):
    print(duty, pwm(100,duty))
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert pwm(100,.5)==(10,5,1.65)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert pwm(200,.5)[2]==pwm(100,.5)[2]
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 python pwm_fade.py ``` ```python # ------------------------------------------------------------ # Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved. # PSUT IoT Engineering Learning Platform # ------------------------------------------------------------ from gpiozero import PWMLED from time import sleep with PWMLED(18) as led: for duty in range(0, 101, 25): led.value = duty / 100 sleep(0.5) ```
07Instructions · Markdown
## Independent investigation and submission At 100 Hz vary duty from 25% to 75%; record period, HIGH duration and mean voltage. Then hold duty at 50% and double frequency; explain which measurements change. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.