ATtiny85 Timer/Counter1 PWM Frequency Formula

I am experimenting with setting the PWM frequency on Timer/Counter1 of the ATtiny85. In section 12.2.2 Timer/Counter1 in PWM Mode, page 87 of the datasheet states:

The frequency of the PWM will be Timer Clock 1 Frequency divided by (OCR1C value + 1). See the following equation:

fPWM = fTCK1 / (OCR1C + 1)

I am running the ATtiny85 at 1MHz, and I've set the Timer/Counter1 prescale to 1 (no prescale). The value of OCR1C is 255. If I'm reading it right, this formula should give me:

fPWM = 100000Hz / (255 + 1) = 3906.25Hz

However, my oscilloscope shows that I'm actually getting a PWM frequency of exactly 4000Hz.

I get consistent results when I try different prescale values. For example, using a prescale of 16, the formula says:

fPWM = (100000Hz / 16) / (255 + 1) = 244.140625Hz

But my scope shows exactly 250Hz.

I feel like I must be missing something obvious. Anyone have an idea what it is?

I suspect either your ATTiny or oscilloscope is not perfect with regards to frequency.

The numbers you quote represent a 0.25% error. I’m not familiar with the ATTiny but check the specifications for oscillator error (either internal or with an external resonator)

You may use CKOUT fuse to measure real clock speed of the ATTiny.

The internal oscillator is not that accurate, and your scope also has a certain error. That you get exactly 4000 Hz is purely by chance.

3906.25 / 4000 = 0.97656 244.140625 / 250 = 0.9756

So the ratios are exactly the same. Perfectly consistent with an oscillator running about 0.25% faster than nominal, and that kind of error in turn is perfectly normal.

The oscillator is only guaranteed to be factory calibrated to within +/- 10% over the whole operating range. It is fairly temperature sensitive, and is voltage sensitive as well. You're very lucky that it's as close as it is.

Thanks for the great info, everyone! I finally got a chance to take another look at this today.

DrAzzy: The oscillator is only guaranteed to be factory calibrated to within +/- 10% over the whole operating range. It is fairly temperature sensitive, and is voltage sensitive as well. You're very lucky that it's as close as it is.

This was the obvious thing I was missing! I was thinking of the CPU clock as exactly 1MHz.

Smajdalf: You may use CKOUT fuse to measure real clock speed of the ATTiny.

This was a great tip -- I enabled CKOUT and then used the scope to compare the clock frequency to the PWM frequency. There are indeed 256 clock pulses per PWM cycle, and the frequencies reported by the scope are consistent with the formula:

fPWM = 1026820Hz / (255 + 1) = 4011.02Hz

(I measured the clock frequency with the scope's hardware frequency counter and the PWM with the software frequency measure, which reported 4.01KHz.)