Square wave 40kHz with ATtiny10

attiny

I'm using a 12 MHz ATtiny10 and I would like to generate a square wave on PB0 at 40 kHz. I think that I need CTC. What should be the values of TCCR0A, TCCR0B, OCR0A and OCR0B?

Best Answer

Square wave at 40 kHz toggles every 12.5 us, which is exactly 150 oscillator clock periods. The code is:

TCCR0A = COM0A(0x01); //Toggle OC0A on compare match
TCCR0B = WGM0_32(0x01) | CS0(1); //clear on compare with OCR0A, use unscaled system clock
OCR0A = (12000000ul/40000u/2u)-1u; //overflow twice per 40kHz period