Part 4: Controlling a Buzzer with PWM¶
PWM produces a repeating digital pulse, not a continuously variable analogue voltage. For a passive piezo transducer, the repetition frequency influences the tone. Use the kernel PWM subsystem so hardware generates those pulses rather than a userspace sleep loop.
Sample code on GitHub
Sample and README · C++ source · CMake build instructions
The repository's CMake target is pwm_pulse; its source file is named main.cpp. The direct-build instructions below remain available.
Before you start¶
Complete LED and Button. This lesson's configuration example is for a Pi 4B, GPIO12 on physical pin 32, with Raspberry Pi OS. Do not apply its alternate-function settings blindly to Pi 5/RP1 or another board.
You need a passive piezo transducer explicitly suitable for a 3.3 V signal and low-current drive, a 1 kΩ series resistor, wires and a breadboard. An active buzzer has its own oscillator; a magnetic buzzer or speaker may require a transistor/amplifier and protection. An unknown “buzzer” is not an interchangeable component.
All commands and C++ builds run on the Pi. Planning mode is available without a PWM device or connected circuit.
1. Understand period and duty¶
For a 440 Hz tone, an illustrative integer period is 2,272,727 ns. Half that period is approximately 1,136,363 ns, giving about 50% duty. The driver can round to its supported resolution.
Duty changes the high-time ratio, not a guaranteed loudness percentage. Acoustic output depends on the actual transducer and circuit. The Linux PWM interface documentation explains the control files.
2. Check hardware PWM configuration before wiring¶
Inspect without changing settings:
No pwmchip entries means the tutorial cannot yet address an exposed PWM controller. It does not prove the board lacks PWM hardware.
Optional Pi 4B configuration¶
This changes boot configuration and can affect audio and pin routing. Keep a local/recovery login, and use the settings lesson to create a unique backup first.
On a standard Pi 4B, the installed pwm overlay documents GPIO12 with function 4 for PWM0. Analogue audio can compete for PWM resources; decide whether disabling that audio is acceptable rather than silently changing it.
In /boot/firmware/config.txt, review existing sections and declarations. Disable the existing dtparam=audio=on declaration if it would conflict, and configure the PWM overlay in a Pi 4-specific section, for example:
Do not simply accumulate duplicate settings or remove unrelated configuration. Follow the installed overlay help and relevant kernel/firmware requirements. Reboot only once the edit is understood and recoverable, then repeat the inspection commands.
For another model or a different installed overlay, use its own documented routing. If the driver or controller still does not appear, stop and diagnose that configuration; do not continue with a guessed sysfs path.
Identify the exposed controller and channel¶
Match the controller's device/Device Tree identity to the overlay, and GPIO12's route to the proper channel. The numeric suffix of pwmchipN is enumeration, not a guaranteed “channel 0”. For the Pi 4 overlay above, GPIO12 routes PWM0; verify that the exposed controller actually corresponds to that hardware.
This site's Pi has no exposed PWM controller before configuration, so no live controller/channel route or waveform is claimed as tested in this revision.
3. Wire only the verified passive piezo circuit¶
With all power disconnected:
Use the component's specifications, not just lead colours. Keep GPIO12 free of LED/button or other peripheral connections. Start with a quiet, brief test; avoid headphones or close ear placement.
The resistor limits drive and may reduce sound. If the transducer needs more current, use a designed driver circuit rather than reducing resistance at random.
The earlier buzzer demonstration video is not a verification of the revised circuit or program.
4. Save the shared finite-pulse program¶
Save the following as pwm_pulse.cpp in a new project directory. It is also available as a source download. The servo lessons reuse this same tool instead of copying slightly different cleanup code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
Build:
Arguments are chip path, channel, period in nanoseconds, high time in nanoseconds, and hold time in milliseconds. Replace pwmchipN and the channel with the confirmed values:
Check: it describes a 500 ms hold and says Dry run only. Without --apply it does not open or export any PWM device.
5. Apply a short tone deliberately¶
After verifying configuration, component and wiring:
Root is used here for protected PWM sysfs writes, not for compilation. Read the error and exit status if it fails.
The program refuses a channel already exported, checks the actual number of channels, exports only the selected one, disables output and clears duty before choosing a new period, sets duty, then enables output for the finite hold.
On ordinary completion, handled signals or caught errors, it attempts disable, zero duty and unexport only for its own successful export. It does not take over an existing channel. Sysfs export is not an exclusive application lock: coordinate with other software instead of treating this as protection against concurrent controllers.
Success: the sound lasts briefly and stops; the selected pwm0 child should no longer be present after successful unexport. If cleanup reports an error, inspect the state from the local console and remove circuit power safely. Ctrl+C is a software convenience, not an emergency stop or protection against SIGKILL, kernel failure or power faults.
Troubleshooting¶
| Symptom | Check |
|---|---|
| No PWM controller | Overlay, driver, model, pin route and conflicts |
| Channel already exported | Identify its owner; do not unexport another application's channel |
| Write/period error | Driver-supported values, current state, permissions and complete error |
| No sound | Confirm passive piezo type, wiring and real signal using suitable test equipment |
| Fixed tone regardless of requested frequency | Possible active buzzer with its own oscillator |
| Sound continues after an error | Inspect enable state; disconnect circuit power and investigate cleanup |
Compilation, argument validation and a simulated file backend are separate from actual waveform/acoustic tests. No new PWM configuration or buzzer circuit was applied on the Pi for this revision.
Practice before the next lesson¶
Plan a 1 kHz, 50% PWM signal held for 250 ms. Calculate the period and duty in nanoseconds, then pass those values to pwm_pulse without --apply, using an unverified placeholder controller path. Predict why duty equal to period is rejected by this exercise.
Hint and expected result
The period is 1000000 ns and duty is 500000 ns; hold time is 250 ms. Planning mode should say no PWM files were opened. This program deliberately requires 0 < duty < period; it is a bounded exercise interface, not a statement that the kernel cannot represent other duty ratios. No tone or waveform has been verified.
Check your understanding and continue¶
Can you calculate period and high time for a chosen frequency? Why does sleep_for here choose the duration of the tone, not generate individual waveform edges? Why should an already-exported channel be refused?
Next, use Positional Servo Control. Servo pulse width represents a command, not an audio frequency or motor supply voltage.