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.
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.
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
Scientific architecture · PWM duty cycle and waveform
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.
Start at 100 Hz / 50%. Confirm 10 ms period and 5 ms HIGH time.
Set duty to 25%, 100% and 0%; compare waveform and average voltage.
Double frequency with duty fixed and explain why ideal average voltage is unchanged.
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.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.
Worked engineering reasoning and boundary conditions
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.
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.
Step 1 of 4 · Period from frequency
Period from frequency
f
1 kHz
T
1 ms
HIGH interval
Duty
25%
HIGH
0.25 ms
LOW interval
LOW
0.75 ms
Ideal average
Mean voltage
0.825 V
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.
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.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery researchLoading experiment-specific apparatus…Previous model / additional reference tools
Simulation task
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
Original virtual instrument; model signals and execution trace.
Loading instrument…
Awaiting model display.
Experimental instrumentation · A/B
Compare two model conditions
Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.
Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.
Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.
Prepare a contextual AI prompt
0 characters
Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.
Prepare → review → copy & open your selected provider → paste and submit there.
Run & verify — acceptance checklist
Build verification: 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.
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%.
Engineering method — 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. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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.
Engineering method — 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. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
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.
Reverse calculation — 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. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.
Expanded independent theoretical exercise bank
Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.
Foundational · Apply the principle
Independent theoretical exercise · 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
Start at 100 Hz / 50%. Confirm 10 ms period and 5 ms HIGH time.
Set duty to 25%, 100% and 0%; compare waveform and average voltage.
Double frequency with duty fixed and explain why ideal average voltage is unchanged.
Run the original PWM example; compare the duty commands and measured or virtual waveform.
3 · Compare controlled trials
Trial
Independent change
Expected check
Observation
Half duty
Use reference inputs above
Average voltage: 1.65
Record actual result
Quarter duty
Duty cycle (%) = 25
Average voltage: 0.825
Record actual result
Constant low
Duty cycle (%) = 0
HIGH time: 0
Record 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.
Trial
Independent change
Dependent observation
Half duty
Use reference inputs above
Record actual outcome and units
Quarter duty
Duty cycle (%) = 25
Record actual outcome and units
Constant low
Duty cycle (%) = 0
Record actual outcome and units
Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.
Loading laboratory-specific procedure…
Python / Google Colab notebook
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.
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)
source ~/psut-wsl/activate.shThe toolkit virtual environment is selected in this terminal, usually with (.venv) in the prompt. Verify which python points into ~/psut-wsl/.venv.
cd ~/psut-wsl/labs/python/lab31Normally no output. pwd should show the requested directory. A missing path produces an error; do not continue until corrected.
lsThe requested files/directories are listed; compare names and permissions with the guide. An empty directory can produce no output.
Checkpoint the lab’s programs are listed.
02
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.
Within tolerance requires every absolute error plus declared uncertainty to lie within tolerance. If any interval is entirely outside, the result is outside; overlap is inconclusive. User-attested evidence is not independent hardware validation.
Save the actual terminal output from the checkpoints above. For simulated inputs explicitly record browser model, fakepi, mock or Wokwi. Never present those data as physical measurements. If a checkpoint fails, see the troubleshooting guide.
Inspect source-aligned signals, make a prediction, compare the idealized readings and export model evidence. This is supplementary to the practical procedure.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# 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
## 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]
## 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.