---
title: Making sound with PWM
heading: Pitch, notes and timing from a square wave
eyebrow: C12 · Lesson 23 · Making sound with PWM
xp: 40
---

::: hook
A small speaker or piezo buzzer driven by a PWM pin makes a tone whose pitch is the PWM frequency. Change the frequency every few hundred milliseconds and it plays a tune: that's how countless appliances beep and chirp. Doing it well takes a little music theory (each note's frequency), a little arithmetic (how close an integer PERIOD gets to it) and careful timing, because a melody with sloppy rhythm sounds wrong long before a slightly sharp note does.
:::

::: play
- The program plays a C major scale on the speaker on PWM channel 2: each note 200 ms, with a 50 ms gap. Run it, then press **Listen** to hear the run.
- Drag the timeline: the speaker's readout shows each note's frequency as it plays. The notes come from the table at the top.
- Change the duty from 32768 (50%) to 3000 and listen again: the same pitches, thinner and quieter.
:::
:::

```sim board
lang: micropython
attach: speaker PWM2
scope: P2
run: 2.2 s
code:
from machine import Pin, PWM
import time

notes = {'C4': 262, 'D4': 294, 'E4': 330, 'F4': 349,
         'G4': 392, 'A4': 440, 'B4': 494, 'C5': 523}
buzzer = PWM(Pin(2), freq=440, duty_u16=0)

for name in ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5']:
    buzzer.freq(notes[name])
    buzzer.duty_u16(32768)      # 50%: a square wave
    time.sleep_ms(200)
    buzzer.duty_u16(0)           # a short gap between notes
    time.sleep_ms(50)
```

::: predict
## A4 is 440 Hz. What's the A one octave higher?

- [ ] 452 Hz
- [ ] 660 Hz
- [x] 880 Hz
- [ ] 1760 Hz

::: reveal
880 Hz: an octave is a doubling of frequency. Between them lie 12 semitones, each a factor of $2^{1/12} = 1.0595$, so that 12 of them multiply to exactly 2.
:::
:::

::: nameit
## Notes

In equal temperament, the note with MIDI number n (A4 is 69, middle C is 60) has

$$f = 440 \times 2^{(n - 69)/12}\ \text{Hz}$$

Each semitone multiplies the frequency by $2^{1/12}$; each octave doubles it.

## Pitch from PWM

The tone's frequency is the PWM frequency, $f = f_\text{clk}/\text{PERIOD}$, with PERIOD a whole number, so a target pitch is only approximate. Musicians measure small pitch differences in **cents**, hundredths of a semitone:

$$\text{cents} = 1200\log_2\frac{f_\text{actual}}{f_\text{target}}$$

Errors under about 5 cents are inaudible; at 10 MHz, PERIOD values in the tens of thousands keep every note within a few hundredths of a cent.

## Timbre and loudness

A 50% square wave contains the fundamental and the odd harmonics (3f, 5f, 7f...) with amplitudes falling as 1/n. Narrower pulses weaken the fundamental and change the timbre; duty cycle is a crude volume control.

## Rhythm

At a tempo of B beats per minute, a quarter note lasts $60/B$ seconds. A melody is a list of (note, duration) pairs; leaving a short gap between notes keeps repeated notes distinct.
:::

::: example
## What PERIOD plays A4, and how far off is the result?

::: solution
1. **Cycles per period.**
   $$\frac{10^7}{440} = 22\,727.3$$
   so PERIOD = 22,727.
2. **The frequency it plays.**
   $$\frac{10^7}{22\,727} = 440.005\ \text{Hz}$$
3. **How far off, in cents.**
   $$1200\log_2\frac{440.005}{440} = 0.02$$
   cents sharp, far below what anyone can hear.

**Answer:** PERIOD = 22,727, which plays 440.005 Hz, 0.02 cents sharp.
:::
:::

::: example
## A tune is written at 120 beats per minute. How long are a quarter note and an eighth note?

::: solution
1. **Quarter note.** A quarter note is one beat:
   $$\frac{60\ \text{s}}{120} = 0.5\ \text{s}$$
2. **Eighth note.** It's half that, 250 ms.
3. **Fill it.** A 200 ms note with a 50 ms gap fills an eighth exactly.

**Answer:** a quarter note lasts 0.5 s and an eighth note 250 ms.
:::
:::

::: example
## What TOP plays C5 (523.25 Hz), toggling the pin on each wrap, and how close is it?

::: solution
1. **Cycles per wrap.** Each wrap is half a cycle:
   $$\frac{10^7}{2 \times 523.25} = 9555.7$$
2. **Round to a whole TOP.** TOP = 9555 gives 9556 cycles per wrap.
3. **The tone.**
   $$\begin{aligned} f &= \frac{10^7}{2 \times 9556}\ \text{Hz} \\ &= 523.23\ \text{Hz} \end{aligned}$$
4. **How close.** That's 0.004% flat, about 0.06 cents.

**Answer:** TOP = 9555, which plays 523.23 Hz, 0.004% flat.
:::
:::

::: check
given: n = 57 | 60 | 64 | 76 | 81
answer: 440*2^((n - 69)/12)
unit: Hz
tolerance: 0.1%

## What's the frequency of MIDI note {n}?

::: right
Right. $440 \times 2^{(n - 69)/12}$ = {answer} Hz.
:::

::: misses
- [440*(n - 69)/12] Semitones multiply the frequency; they don't add to it.
- [any] Not yet. $440 \times 2^{(n - 69)/12}$.
:::
:::

::: check
given: f = 262 | 523 | 880 | 2093
answer: round(1e7/f)
tolerance: 0

## What PWM PERIOD comes closest to {f} Hz on the 10 MHz board?

::: right
Right. {answer}.
:::

::: misses
- [any] Not yet. $f_\text{clk}/f$, rounded.
:::
:::

::: check
given: P = 2389 | 22727 | 38223
answer: 1e7/P
unit: Hz
tolerance: 0.01%

## What frequency does PERIOD = {P} make?

::: right
Right. {answer} Hz.
:::

::: misses
- [any] Not yet. $f_\text{clk}/\text{PERIOD}$.
:::
:::

::: check
given: a = 440.5 | 445 | 438; t = 440
answer: 1200*log(a/t)/log(2)
unit: cents
tolerance: 1%

## A note meant to be {t} Hz plays at {a} Hz. How many cents off is it?

::: right
Right. $1200\log_2(f_a/f_t)$ = {answer} cents.
:::

::: misses
- [1200*log(a/t)] That's $\log_{10}$; cents use $\log_2$.
- [any] Not yet. $1200\log_2$ of the ratio.
:::
:::

::: check
given: B = 60 | 90 | 120 | 150; k = 1 | 0.5 | 0.25
answer: 60/B*k*1000
unit: ms
tolerance: 0.5%

## At {B} beats per minute, how long is a note of {k} beats?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. One beat is $60/B$ s.
:::
:::

::: check
given: f = 262 | 440 | 1000; h = 3 | 5
answer: h*f
unit: Hz
tolerance: 0.5%

## A {f} Hz square wave: at what frequency is its harmonic number {h}?

::: right
Right. {answer} Hz, at 1/{h} of the fundamental's amplitude.
:::

::: misses
- [any] Not yet. Harmonic n is at n times the fundamental.
:::
:::

::: check
kind: choice

## Which change makes a PWM tone quieter without changing its pitch?

- [ ] Doubling PERIOD
- [x] Lowering the duty cycle well below 50%
- [ ] Halving PERIOD
- [ ] Raising the duty cycle above 50%

::: misses
- [1] That halves the frequency: an octave lower.
- [3] That doubles the frequency: an octave higher.
- [4] Above 50% is the mirror image of below 50%: the fundamental weakens the same way, but it's no quieter than the same distance below.
:::
:::

::: check
kind: c
given: N = 60 | 64 | 67 | 72
attach: speaker PWM2
run: 0.05
expect: pwmfreq = 440*2^((N - 69)/12) Hz ± 0.01%; pwmduty(2) = 50 % ± 0.5

## Play MIDI note `N` ({N}) on the speaker on PWM channel 2, as a 50% square wave. (The frequency table is up to you: compute it, or hard-code it.)

```c starter
#include "board.h"

int main(void) {
    PWM_PERIOD = 22727;
    PWM_DUTY(2) = 11363;
    PWM_CTRL |= 1 << 2;
    return 0;
}
```

```c solution
#include "board.h"

// PERIOD for MIDI notes 60 (C4) to 72 (C5) on a 10 MHz clock
const uint32_t periods[13] = {38223, 36077, 34052, 32141, 30337, 28635, 27027,
                              25511, 24079, 22727, 21452, 20248, 19111};

int main(void) {
    uint32_t p = periods[N - 60];
    PWM_PERIOD = p;
    PWM_DUTY(2) = p / 2;
    PWM_CTRL |= 1 << 2;
    return 0;
}
```

::: right
Right. A table of periods computed once is the usual way: no floating point, no logarithms at run time.
:::
:::

::: check
kind: parts
given: f = 262 | 440 | 880 | 1047

## A timer toggles a buzzer pin on each wrap to play {f} Hz.

::: part
answer: floor(1e7/(2*f) + 0.5) - 1
tolerance: 0

### What TOP (with PRESCALE = 0, nearest)?

::: misses
- [any] Half a cycle per wrap: $10^7/(2f)$ cycles, minus 1.
:::
:::

::: part
answer: 1e7/(2*floor(1e7/(2*f) + 0.5))
unit: Hz
tolerance: 0.001%

### What frequency actually plays?

::: misses
- [any] $10^7/(2(\text{TOP} + 1))$.
:::
:::
:::

::: check
kind: parts
given: B = 60 | 96 | 144

## A tune is written at {B} beats per minute, a quarter note per beat.

::: part
answer: 60/B*1000
unit: ms
tolerance: 0.5%

### How long is a quarter note?

::: misses
- [any] 60 s over the tempo.
:::
:::

::: part
answer: 60/B*1000*1.5
unit: ms
tolerance: 0.5%

### How long is a dotted quarter (one and a half beats)?

::: misses
- [any] 1.5 beats.
:::
:::
:::

::: explain
## Why is a lookup table of PWM periods the usual way to play notes on a microcontroller?

::: model
Computing a note's frequency needs a power of two with a fractional exponent, $2^{(n-69)/12}$, and then a division to turn it into a period: floating-point work that's slow, or unavailable, on a small chip. But only a few dozen notes are ever used, and each one's period never changes, so they can all be computed once, on a computer, and stored as integers. Playing a note is then a single array read and a register write. The table takes a few bytes per note, and it can be checked against the formula before it's ever compiled in.
:::
:::

::: practice

::: check
given: n = 48 | 57 | 60 | 62 | 64 | 69 | 72 | 79 | 81
answer: 440*2^((n - 69)/12)
unit: Hz
tolerance: 0.1%

## Frequency of MIDI note {n}?

::: misses
- [any] $440 \times 2^{(n-69)/12}$.
:::
:::

::: check
given: f = 262 | 330 | 440 | 523 | 784 | 1047 | 1567
answer: round(1e7/f)
tolerance: 0

## PERIOD for {f} Hz?

::: misses
- [any] $f_\text{clk}/f$, rounded.
:::
:::

::: check
given: B = 100 | 140; k = 0.5 | 2
answer: 60/B*k*1000
unit: ms
tolerance: 0.5%

## Length of a {k}-beat note at {B} BPM?

::: misses
- [any] $60k/B$ s.
:::
:::
:::
