Project 4: PWM Workshop - Motor and LED Control Lab

Use PWM to control LED brightness and motor speed while measuring duty cycle, frequency, and electrical effects.

Quick Reference

Attribute Value
Difficulty Level 2: Intermediate
Time Estimate 10-15 hours
Main Programming Language C++
Alternative Programming Languages C
Coolness Level Level 3: Genuinely Clever
Business Potential 2. The “Component” Business
Prerequisites C/C++ basics, Teensyduino setup, basic electronics, ability to use a multimeter/logic analyzer
Key Topics PWM timers, duty cycle, motor drivers, filtering

1. Learning Objectives

By completing this project, you will:

  1. Explain the core question for this project in your own words.
  2. Implement the main workflow and validate it with measurements.
  3. Handle at least two failure modes and document recovery.
  4. Produce a deterministic report that matches hardware behavior.

2. All Theory Needed (Per-Concept Breakdown)

PWM Generation and Power Stage Interaction

Fundamentals PWM encodes an analog value as the duty cycle of a digital signal. A PWM output is produced by a timer compare unit, and the load sees a square wave whose average voltage depends on duty. Electrical constraints matter: LED current needs a resistor and motors need driver transistors and flyback protection. This project makes PWM timing and electrical behavior observable.

Deep Dive into the concept PWM frequency and resolution are linked. Higher frequency reduces audible noise and flicker, but fewer timer counts mean coarser duty steps. The correct choice depends on the load. LEDs tolerate lower frequency but may flicker if too low; motors may whine at audible frequencies; high-frequency PWM can increase switching losses and EMI. The power stage is part of the system. LED brightness is a function of current, not voltage, so a resistor or constant-current driver is required. Motors are inductive and produce voltage spikes when switched off, which must be clamped with a diode or driver. A scope shows ringing, overshoot, and rise time that are invisible in code. If you drive loads directly from a pin, you risk damaging the MCU. Filtering turns PWM into a quasi-analog signal. An RC low-pass can smooth the waveform, but it adds latency and ripple. The filter cutoff must be well below the PWM frequency to reduce ripple. This project forces you to measure duty, frequency, and load response to understand the tradeoffs.

How this fit on projects This concept directly powers the implementation choices and validation steps in this project.

Definitions & key terms

  • PWM: Pulse-width modulation used to encode values as duty cycle.
  • Duty cycle: Fraction of a period the signal is HIGH.
  • H-bridge: Circuit that can drive a motor in both directions.
  • Flyback diode: Diode that clamps inductive voltage spikes.

Mental model diagram (ASCII)

Timer -> PWM pin -> Driver -> Load

How it works (step-by-step)

  1. Configure timer frequency and duty cycle.
  2. Measure PWM on a scope and confirm duty accuracy.
  3. Drive LED or motor through proper driver circuit.
  4. Record temperature, noise, and stability under load.

Minimal concrete example

analogWriteFrequency(5, 20000);
analogWrite(5, 128); // 50% duty

Common misconceptions

  • PWM creates a real analog voltage without filtering.
  • Any pin can drive a motor directly.
  • Higher frequency is always better.

Check-your-understanding questions

  • How does PWM resolution change with frequency?
  • Why do motors need flyback protection?
  • What causes audible PWM whine?

Check-your-understanding answers

  • Higher frequency reduces available timer counts and resolution.
  • Inductive loads generate voltage spikes when switched off.
  • Low PWM frequency falls into the audible range and excites vibration.

Real-world applications

  • LED dimming
  • Motor speed control
  • Class-D audio amplifiers

Where you’ll apply it

References

  • Microcontroller timer documentation
  • Power electronics basics

Key insights

PWM is a system of timing plus power electronics, not just a timer register.

Summary

You master PWM when you can predict duty, frequency, and load behavior together.

Homework/Exercises to practice the concept

  • Measure PWM duty at three frequencies and compare resolution.
  • Drive a DC motor through a transistor and log current draw.

Solutions to the homework/exercises

  • Compute timer counts from clock and validate with a scope.
  • Use a low-side MOSFET with a diode and record current with a meter.

3. Project Specification

3.1 What You Will Build

Use PWM to control LED brightness and motor speed while measuring duty cycle, frequency, and electrical effects.

3.2 Functional Requirements

  1. Generate PWM at multiple frequencies.
  2. Control LED brightness with measurable duty steps.
  3. Drive a motor via transistor and measure current.
  4. Record PWM timing and electrical behavior.

3.3 Non-Functional Requirements

  • Performance: Meet the target timing/throughput for the project.
  • Reliability: Detect errors and recover without undefined behavior.
  • Usability: Provide clear logs and a repeatable workflow.

3.4 Example Usage / Output

./P04-pwm-workshop-motor-and-led-control-lab --run

3.5 Data Formats / Schemas / Protocols

CSV with columns: freq_hz, duty_pct, load_ma, notes

3.6 Edge Cases

  • Motor stalls at low duty
  • PWM frequency too low causing audible noise
  • Overcurrent on LED without resistor

3.7 Real World Outcome

You will run the project and see deterministic logs and measurements that match physical hardware behavior.

3.7.1 How to Run (Copy/Paste)

cd project-root
make
./P04-pwm-workshop-motor-and-led-control-lab --run

3.7.2 Golden Path Demo (Deterministic)

Use a fixed input configuration and a known test signal. Capture output for 60 seconds and verify it matches expected values.

3.7.3 If CLI: exact terminal transcript

$ ./P04-pwm-workshop-motor-and-led-control-lab --run --seed 42
[INFO] PWM Workshop - Motor and LED Control Lab starting
[INFO] Report saved to data/report.csv
[INFO] Status: OK
$ echo $?
0

Failure Demo (Deterministic)

$ ./P04-pwm-workshop-motor-and-led-control-lab --run --missing-device
[ERROR] Device not detected
$ echo $?
2

4. Solution Architecture

4.1 High-Level Design

Inputs -> Acquisition -> Processing -> Output/Log

4.2 Key Components

Component Responsibility Key Decisions
Acquisition Configure peripherals and capture data Use stable clock settings
Processing Convert raw data to meaningful values Apply calibration/filters
Output/Log Emit reports and logs CSV for reproducibility

4.3 Data Structures (No Full Code)

struct Sample {
    uint32_t timestamp_us;
    uint32_t value;
    uint32_t flags;
};

4.4 Algorithm Overview

Key Algorithm: Measurement + Report

  1. Initialize hardware and verify configuration.
  2. Capture data and record timestamps.
  3. Compute metrics and write report.

Complexity Analysis:

  • Time: O(n) in samples
  • Space: O(n) for log storage

5. Implementation Guide

5.1 Development Environment Setup

# Arduino IDE + Teensyduino must be installed
# Optional CLI workflow
arduino-cli core update-index
arduino-cli core install teensy:avr

5.2 Project Structure

project-root/
├── src/
│   ├── main.ino
│   ├── hw_config.h
│   └── measurements.cpp
├── tools/
│   └── analyze.py
├── data/
│   └── samples.csv
└── README.md

5.3 The Core Question You’re Answering

“How does PWM translate into real-world control signals?”

5.4 Concepts You Must Understand First

Stop and research these before coding:

  1. PWM timers, duty cycle, motor drivers, filtering
  2. Data logging and measurement techniques
  3. Basic timing math and error analysis

5.5 Questions to Guide Your Design

  1. What PWM frequency avoids flicker or audible noise?
  2. How will you limit current to protect the MCU?
  3. How will you measure duty cycle accurately?

5.6 Thinking Exercise

Predict LED brightness at 25/50/75% duty and compare to measurements.

5.7 The Interview Questions They’ll Ask

  1. Why does PWM resolution depend on frequency?
  2. What is the purpose of a flyback diode?
  3. When would you use an RC filter on PWM?

5.8 Hints in Layers

  • Start with LED only before adding a motor.
  • Use a transistor driver for anything beyond small LEDs.
  • Measure duty cycle with a logic analyzer.

5.9 Books That Will Help

| Topic | Book | Chapter | |——-|——|———| | PWM basics | Arduino Workshop | Ch. 8 | | Embedded timing | Making Embedded Systems | Ch. 4 | | Power electronics | Practical Electronics for Inventors | Ch. 14 |

5.10 Implementation Phases

Phase 1: Foundation (4 hours)

Goals:

  • Configure PWM outputs
  • Measure duty cycle

Tasks:

  1. Configure PWM outputs
  2. Measure duty cycle

Checkpoint: PWM verified on scope

Phase 2: Core Functionality (6 hours)

Goals:

  • Drive LED and motor
  • Log current

Tasks:

  1. Drive LED and motor
  2. Log current

Checkpoint: Control effects observed

Phase 3: Polish (3 hours)

Goals:

  • Compare frequencies
  • Document best settings

Tasks:

  1. Compare frequencies
  2. Document best settings

Checkpoint: PWM lab report

5.11 Key Implementation Decisions

| Decision | Options | Recommendation | Rationale | |———-|———|—————-|———–| | Buffering | Single buffer, double buffer | Double buffer | Avoids data loss during processing | | Logging format | CSV, binary | CSV | Human-readable while still scriptable | | Clock speed | Default, overclock | Default | Keeps peripherals in spec |


6. Testing Strategy

6.1 Test Categories

| Category | Purpose | Examples | |———-|———|———-| | Unit Tests | Validate math, parsing, and conversions | Timer math, CRC checks | | Integration Tests | Verify peripherals and pipelines | DMA -> buffer -> log | | Edge Case Tests | Handle boundary conditions | Brownout, missing sensor |

6.2 Critical Test Cases

{test_cases}

6.3 Test Data

Use a fixed test input pattern and record outputs to data/report.csv

7. Common Pitfalls & Debugging

7.1 Frequent Mistakes

| Pitfall | Symptom | Solution | |———|———|———-| {pitfalls}

7.2 Debugging Strategies

{debug_strats}

7.3 Performance Traps

Large buffers improve stability but increase latency. Measure both throughput and jitter to choose the right size.


8. Extensions & Challenges

8.1 Beginner Extensions

{ex_begin}

8.2 Intermediate Extensions

{ex_inter}

8.3 Advanced Extensions

{ex_adv}


9. Real-World Connections

9.1 Industry Applications

{industry_apps}

{open_source}

9.3 Interview Relevance

{interview_rel}


10. Resources

10.1 Essential Reading

{resources}

10.2 Video Resources

  • Embedded systems timing walkthrough (YouTube)
  • Teensy hardware deep dive (Conference talk)

10.3 Tools & Documentation

  • Teensyduino: Toolchain for Teensy boards
  • Logic Analyzer: Timing verification
  • Multimeter: Voltage and current measurement

{related_projects}


11. Self-Assessment Checklist

11.1 Understanding

  • I can explain the main concept without notes.
  • I can explain why the measurements match (or do not match) expectations.
  • I understand at least one tradeoff made in this project.

11.2 Implementation

  • All functional requirements are met.
  • All critical test cases pass.
  • Logs and reports are reproducible.
  • Edge cases are handled.

11.3 Growth

  • I documented lessons learned.
  • I can explain this project in a job interview.
  • I identified one improvement for next iteration.

12. Submission / Completion Criteria

Minimum Viable Completion: {comp_min}

Full Completion: {comp_full}

Excellence (Going Above & Beyond): {comp_ex}