A piezo can make a convincing sound while the microcontroller is running eight times faster than you think. In this experiment the ATtiny85 hardware timer makes two short test bursts, then disconnects its waveform output and holds the pin low. Measure the frequency, compare it with the clock calculation, and inspect what “stop” means at the pin and at the piezo.
Units used below are volts (V), kilohertz (kHz, one thousand cycles per second), millimetres (mm), centimetres (cm), kilohms (kΩ, 1,000 ohms), nanofarads (nF, one billionth of a farad), microfarads (µF, one millionth of a farad), watts (W), milliamperes (mA, one thousandth of an ampere), microseconds (µs, one millionth of a second) and milliseconds (ms, one thousandth of a second).
Preparation status: the supplied control code has host checks using register stand-ins and separate arithmetic checks. It has not been physically assembled, measured, or compiled for the AVR target. A host compiler cannot establish fuse settings, timer edges or sound level.
An exact passive transducer, not an active buzzer
A piezoelectric transducer bends when its applied voltage changes. Our exact part is TDK PS1240P02BT, a PS-series pin-terminal unit without an internal oscillator. An active buzzer includes its own oscillator and can sound from steady power; this part needs an external changing signal. A loudspeaker with a coil is a different load and cannot replace it in this circuit.
The current TDK product page lists PS1240P02BT in production. Its nominal diameter is 12.2 mm, height 6.5 mm, and terminal pitch 5 mm. The catalog specifies its sound test at 4 kHz and 3 V zero-to-peak rectangular drive, with a 10 cm measuring distance. We use an extra series resistor and coupling capacitor, so we do not promise the catalog sound level. The catalog’s 30 V zero-to-peak maximum without direct-current bias is a limit, not our operating target. Our regulated supply is only 3.0 V.
The controller is Microchip ATtiny85-20PU in an eight-pin plastic dual in-line package (PDIP). AVR is the microcontroller architecture family name. The normal ATtiny85 operating range starts at 2.7 V; do not borrow the lower-voltage rating of an ATtiny85V. A general-purpose input/output (GPIO) pin can read or drive a logic level. Here Port B bit 0 (PB0) has a second function: Output Compare A (OC0A), the timer-controlled waveform output.
| Quantity | Part/value | Purpose |
|---|---|---|
| 1 each | ATtiny85-20PU; TDK PS1240P02BT | Timer and exact passive piezo load |
| 1 | R1: 1 kΩ, ±1%, 0.25 W | Limits current into the capacitive branch |
| 1 each | C3: 100 nF nonpolar film, ≥10 V; R3: 100 kΩ, ±5% | Blocks sustained direct-current drive and provides a piezo discharge path |
| 1 each | C1: 100 nF ceramic; C2: 4.7 µF, ≥6.3 V | Local supply decoupling and bulk charge; observe C2 polarity if polarized |
| 1 | R2: 10 kΩ; regulated 3.0 V bench supply | Reset pullup and controlled supply; start with a 20 mA current limit |
| As needed | 3 V compatible programmer, breadboard, short leads; oscilloscope or frequency counter | Program, inspect supply, measure frequency and stop behavior |
Wiring and the load boundary
VCC is the positive power connection; GND is the common voltage reference. Locate the PDIP notch and count pins from the top view. Pin 8 goes to 3.0 V and pin 4 to GND. Place C1 directly beside those connections. Put C2 across the supply, with its positive terminal at VCC if applicable. R2 holds pin 1, RESET, high while allowing the programmer to pull it low.

| Physical pin | Function in this experiment | Connection |
|---|---|---|
| 1 | PB5 / RESET | 10 kΩ to 3.0 V; programmer reset connection |
| 2, 3 | PB3, PB4 | Unused; no external clock or clock-output connection |
| 4, 8 | GND, VCC | Common ground and 3.0 V with decoupling |
| 5 | PB0 / OC0A | R1 → C3 → piezo terminal; other piezo terminal to GND |
| 6, 7 | PB1, PB2 | Programming signals only; otherwise unused |
Put R3 across the two piezo terminals. The PS catalog drawing shows the two-terminal package, not a three-pin buzzer module; use those leads, with no assumed module pin order. The functional drawing does not assign an unsupported positive-terminal marking. Keep all leads short. In-system programming (ISP) programs the installed chip through its programming pins; it uses the Serial Peripheral Interface (SPI) signal pins, including PB0. Disconnect the piezo branch with power off before programming, then reconnect it after the programmer is removed. Do not connect a 5 V programmer supply to this 3.0 V experiment.
Direct current (DC) means a steady component of voltage or current. C3 blocks sustained DC through the driven branch; R3 allows stored charge to decay. It does not make the piezo an ideal resistor. With a nominal 3.0 V source and R1 at its 990 Ω tolerance minimum, an ideal initially uncharged or shorted branch gives I ≤ 3.0 / 990 ≈ 3.03 mA; the corresponding resistor power is about 9.09 mW. This is a conservative source-step calculation, not a measured piezo current or a guarantee against externally generated transients. The microcontroller’s ordinary 3 V pin drive is characterized at 5 mA in its electrical table; its 40 mA absolute pin limit is not a design current.
The public PS1240P02BT catalog does not specify a capacitance or a current guarantee for this complete resistor/capacitor network. Do not invent one or treat 100 nF as the piezo capacitance. The actual waveform amplitude, mechanical ringing and decay must be measured. This modest drive deliberately favors a small current budget over maximum loudness.
The clock contract comes before the frequency
The central processing unit (CPU) clock supplies the timer clock. This source assumes a nominal 1 MHz CPU clock: the internal nominal 8 MHz oscillator divided by eight. A fuse is a nonvolatile configuration bit; it is separate from the application program. Read and save the actual fuse settings and chip marking before any change. Review oscillator selection, CKDIV8 division, RESET enabled, debugWIRE debugging disabled, clock output CKOUT disabled, watchdog-always-on WDTON unprogrammed, and a brown-out reset threshold compatible with 3.0 V. Brown-out reset holds the controller in reset when its supply is too low. No blind fuse-write command belongs in this lesson.
F_CPU=1000000UL tells the compiler what clock to assume; it does not set fuses, calibrate the oscillator or measure the board. The internal oscillator also varies with supply and temperature. Check the actual clock basis in your bench notes. If an already-configured chip runs at 8 MHz while this program assumes 1 MHz, the waveform is eight times faster and the intended delays eight times shorter. A weak or inaudible result can therefore be a clock error rather than a broken piezo.
Count to a comparison, then toggle
Clear Timer on Compare Match (CTC) means the counter returns to its starting count when it matches the programmed comparison value. Timer0 is an eight-bit counter. Output Compare Register A (OCR0A) stores the comparison; counting zero through that value takes OCR0A + 1 timer ticks. The output toggles once per match, so a complete square-wave cycle needs two matches. A prescaler divides the clock before it reaches the counter.
fout = fCPU / [2 × N × (OCR0A + 1)], with prescaler N = 8. At a nominal 1 MHz CPU clock, requesting 4,000 Hz gives ideal counts 15.625. The delivered planner rounds counts to the nearest integer, with ties upward: 16 counts, OCR0A = 15, and 3,906.25 Hz. That is a −2.34375% quantization difference before oscillator error. The 2,000 Hz request gives 31 counts, OCR0A = 30, and approximately 2,016.129 Hz. This rounding rule is explicit; it is not a general search for the smallest frequency error.

The code chooses waveform-generation mode 2: WGM01 set, WGM00 and WGM02 clear. COM0A = 01 selects toggling on a match, while CS0 = 010 selects divide-by-eight. These are control-register fields, not interchangeable pin numbers. No software interrupt is needed for each edge. The program exclusively owns Timer0; an Arduino core or another timing library must not also configure it.
A fresh start first stops the timer and clears the count. While stopped, a forced compare in clear-output mode clears the internal OC0A output latch; then toggle mode is selected and the clock starts last. Changing output ownership can itself create a brief transition, so measure frequency after steady cycles begin. Stop first removes the timer clock, preloads the ordinary PB0 port latch low, disconnects compare output and clears the counter. It can truncate the final half-period. It is a defined low pin state after the sequence, not a phase-aligned or click-free audio envelope. The coupling network and piezo can still have a decaying transient.
Complete bare AVR-C program
This is C language source for the exact AVR chip, using AVR-LibC’s register, watchdog and delay facilities. The watchdog is a reset timer; its early startup sequence records the reset cause, clears the reset flags and disables the watchdog when the reviewed fuse allows that. The two bursts last a requested 250 ms each, separated by a requested second of quiet. Afterward the application remains low until deliberate reset or power restart. These delays assume the actual clock matches the compiler declaration.
/* ATtiny85-20PU, 3.0 V, actual clock nominally 1 MHz.
* Dedicated bare AVR-C application: owns Timer0 and PB0/OC0A.
* HOST_TEST exercises this same planner/control code using register stand-ins.
* It does not compile or emulate the AVR target or measure a piezo.
*/
#include <stdint.h>
#include <stddef.h>
#ifndef F_CPU
#define F_CPU 1000000UL
#endif
#if F_CPU != 1000000UL
#error "This lesson requires a verified nominal 1 MHz CPU clock."
#endif
#ifndef HOST_TEST
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/delay.h>
uint8_t reset_cause __attribute__((section(".noinit")));
void early_watchdog_off(void) __attribute__((naked, used, section(".init3")));
void early_watchdog_off(void) {
reset_cause = MCUSR;
MCUSR = 0;
wdt_disable(); /* Requires WDTON fuse unprogrammed. */
}
#endif
enum { REG_A, REG_B, REG_COUNT, REG_COMPARE, REG_PORT, REG_DDR, REG_COUNT_TOTAL };
enum { MASK_PIN = 1, MASK_CTC = 2, MASK_TOGGLE = 64,
MASK_CLEAR = 128, MASK_FORCE_A = 128, MASK_DIV8 = 2 };
#ifdef HOST_TEST
static uint8_t host_regs[REG_COUNT_TOTAL];
static uint8_t trace_reg[64], trace_value[64], trace_count;
static uint8_t read_reg(uint8_t r) { return host_regs[r]; }
static void write_reg(uint8_t r, uint8_t v) {
host_regs[r] = v;
if (trace_count < 64) {
trace_reg[trace_count] = r; trace_value[trace_count++] = v;
}
}
#else
static uint8_t read_reg(uint8_t r) {
switch (r) {
case REG_A: return TCCR0A; case REG_B: return TCCR0B;
case REG_COUNT: return TCNT0; case REG_COMPARE: return OCR0A;
case REG_PORT: return PORTB; case REG_DDR: return DDRB;
default: return 0;
}
}
static void write_reg(uint8_t r, uint8_t v) {
switch (r) {
case REG_A: TCCR0A=v; break; case REG_B: TCCR0B=v; break;
case REG_COUNT: TCNT0=v; break; case REG_COMPARE: OCR0A=v; break;
case REG_PORT: PORTB=v; break; case REG_DDR: DDRB=v; break;
default: break;
}
}
#endif
typedef struct { uint8_t compare; uint16_t counts; } TimerPlan;
/* Round ideal timer counts to nearest integer, ties upward.
* Fixed divide-by-8 prescaler. This is not a global frequency-error optimizer.
*/
static uint8_t plan_tone(uint32_t cpu_hz, uint32_t requested_hz, TimerPlan *out) {
if (!out || !cpu_hz || !requested_hz) return 0;
uint64_t denominator = (uint64_t)16 * requested_hz;
uint64_t counts = ((uint64_t)cpu_hz + denominator/2) / denominator;
if (counts < 1 || counts > 256) return 0;
out->counts = (uint16_t)counts;
out->compare = (uint8_t)(counts-1);
return 1;
}
/* Stops the clock, preloads the ordinary port latch low, disconnects compare
* output, then clears the counter. May truncate the final half-period.
* The external coupling capacitor/piezo can still have a decaying transient.
*/
static void timer_stop(void) {
write_reg(REG_B, 0);
write_reg(REG_PORT, read_reg(REG_PORT) & (uint8_t)~MASK_PIN);
write_reg(REG_A, 0);
write_reg(REG_COUNT, 0);
}
static uint8_t timer_start_compare(uint16_t compare) {
timer_stop(); /* Every invalid request also leaves PB0's latch low. */
write_reg(REG_DDR, read_reg(REG_DDR) | MASK_PIN);
if (compare > 255) return 0;
write_reg(REG_COMPARE, (uint8_t)compare);
/* Clear the internal OC0A latch with a forced match while clock stopped.
* COM0A=10 clears output; FOC0A does not advance/reset the timer count.
* Then use COM0A=01 for toggle in CTC mode and start divide-by-8 last.
*/
write_reg(REG_A, MASK_CTC | MASK_CLEAR);
write_reg(REG_B, MASK_FORCE_A);
write_reg(REG_A, MASK_CTC | MASK_TOGGLE);
write_reg(REG_B, MASK_DIV8);
return 1;
}
static uint8_t start_tone(uint32_t requested_hz) {
TimerPlan plan;
if (!plan_tone(F_CPU, requested_hz, &plan)) {
timer_stop();
write_reg(REG_DDR, read_reg(REG_DDR) | MASK_PIN);
return 0;
}
return timer_start_compare(plan.compare);
}
#ifndef HOST_TEST
int main(void) {
cli(); /* No interrupt-driven library or Arduino core owns Timer0. */
timer_stop();
DDRB |= MASK_PIN;
_delay_ms(1000.0); /* Timing assumes actual clock matches F_CPU. */
if (!start_tone(2000)) goto quiet;
_delay_ms(250.0);
timer_stop();
_delay_ms(1000.0);
if (!start_tone(4000)) goto quiet;
_delay_ms(250.0);
quiet:
timer_stop();
for (;;) { /* Stay electrically quiet until explicit reset/power restart. */ }
}
#endif
Download the complete C source (ZIP; file: tricky-circuit-batch-006/code/attiny-passive-buzzer.c) · Blank observation sheet (ZIP; file: tricky-circuit-batch-006/code/attiny-passive-buzzer-observations-blank.csv)
The intended target toolchain is the AVR version of the GNU Compiler Collection (GCC) with AVR-LibC; the current referenced library manual is version 2.3.0. A starting build command is avr-gcc -mmcu=attiny85 -Os -std=gnu11 -DF_CPU=1000000UL attiny-passive-buzzer.c -o piezo.elf. The -Os option enables optimization, required for the library’s constant delay calculations. Record your actual compiler/library versions and inspect the target output before flashing through your established programmer workflow. No target binary, successful AVR build or flashed device is supplied here.
The host checks compile the same planner, start and stop functions with register stand-ins. They check zero/overflowing requests, counter endpoints, rounding, forcing the internal latch while the timer clock is stopped, clock-start ordering, invalid-request quiet state, preserving other port bits and repeated stop calls. They do not emulate comparator hardware or validate the AVR-only startup and delay path. Invalid runtime frequency requests leave the output stopped; they cannot detect an incorrect physical clock or an open transducer.
A measurement procedure with an honest quiet state
- With power off, verify the chip and exact piezo, PDIP orientation, ground, reset pullup, series branch and capacitor polarities. Disconnect the piezo branch for programming. Record the fuse readback and clock basis; complete and record an actual target build before loading it.
- After disconnecting the programmer, reconnect the branch and set the bench supply to 3.0 V with the stated current limit. Check the rail first. A supply in current limit or repeated reset is a fault to investigate, not a frequency measurement.
- Use an oscilloscope probe at PB0 with its ground at the circuit reference. Capture the two bursts after reset. Compare steady frequency with 2,016.129 Hz and 3,906.25 Hz under the nominal clock assumption. Save the actual trace and timebase settings.
- Measure both sides of the coupling network relative to ground with two ordinary probes and subtraction if the instrument supports it. Keep both ground clips at GND; do not attach a grounded clip to the driven node. Record peak voltages and the decay after stop rather than assuming it is instant.
- Check PB0 stays low after the second burst. If it keeps toggling, inspect timer ownership, firmware and wiring. A piezo click at stop is not evidence of continued timer operation. A counter that reports a late spurious edge is also different from sustained oscillation.
- Compare a recorded incorrect-clock calculation with the observed trace; do not change fuses merely to force a fault. At 8 MHz and OCR0A = 15, the prediction is 31,250 Hz. Investigate frequency ratios before changing OCR values to hide the clock mismatch.
An open piezo can leave the PB0 waveform apparently correct but silent. A short in the branch can change loading while the timer continues. Software has no acoustic or current feedback here, so neither condition produces a meaningful automatic “passed” result. Power off before changing wiring. Use the blank sheet for real measurements; its empty rows are intentional.
Challenge and answer
Challenge: Your nominal 4 kHz request measures close to 31.25 kHz, and the 250 ms burst is about 31 ms long. Should you change OCR0A until the tone sounds right?
Show the reasoning
Both frequency and duration point to an approximately eight-times clock mismatch. Inspect the actual oscillator/prescaler configuration and compiler clock assumption first. With OCR0A = 15 and N = 8, 31,250 Hz implies an 8 MHz CPU clock. Changing OCR alone would hide one symptom while leaving every software delay wrong. Measurements are still needed to separate that large ratio error from ordinary oscillator tolerance.
Sources, errata and related experiments
The current Microchip-hosted complete ATtiny25/45/85 datasheet is revision 2586Q (August 2013). Its ATtiny85 errata section distinguishes revisions B–C from A; the A issue concerns low-voltage/low-clock reads of electrically erasable memory, which this application does not use. Record the actual silicon revision; “-20PU” is an ordering suffix, not proof of revision. TDK’s current product status and February 2022 PS catalog were checked together. The public catalog asks for detailed delivery specifications; no undocumented capacitance, acoustic guarantee or later revision is invented.
- Microchip complete datasheet: pinout, clock, Timer0, electrical limits and section 27.3 errata
- TDK PS1240P02BT exact current product and PS-series catalog, especially page 4
- AVR-LibC constant delay and F_CPU requirements and early watchdog handling
- Earlier ATtiny music-code introduction and earlier melody experiment. This lesson adds hardware comparison, load limits and measurable stopping behavior.



