How do i set timer 0 correctly?
Hi. I want to use timer0 to generate ISR with 75392 frequency. It will be used to bit-bang two signals on PB0 and PB1. One will be constant 589 Hz sound and another is 4712Hz PWM signal to generate volume level envelope with simple RC-filter. No matter what i write to OCR0A i only get arount 100Hz on PB0.
Here's my code. What am i doing wrong?
#define INPUT 0
#define OUTPUT 1
#define LOW 0
#define HIGH 1
#define digitalWrite(PIN, DIRECTION) (DIRECTION != 0 ? (PORTB |= (1 << PIN)) : (PORTB &= ~(1 << PIN)))
#define digitalRead(PIN) ((PINB & (1 << PIN)) != 0)
#define pinMode(PIN, MODE) (MODE ? (DDRB |= (1 << PIN)) : (DDRB &= ~(1 << PIN)))
void setup() {
pinMode(PB0, OUTPUT);
TCCR0A = 0; // Set entire TCCR0A register to 0
TCCR0B = 0; // Set entire TCCR0B register to 0
TCCR0B |= (1 << CS00);
OCR0A = 52;
TIMSK0 |= (1 << OCIE0A);
sei();
}
void loop() {
// Your main code here
}
ISR(TIM0_COMPA_vect) {
// Toggle PB0
digitalWrite(PB0, !digitalRead(PB0));
}
Prescaler is set to 1. So, my freq. should be CPUf / (2 x presc x (OCR0A+1) = 8000000/(2 x 1 x (52+1)) = 75392 Hz But it gives me only 58-59Hz pulse on PB0 now. It doesn't matter if i change OCR0A. I set 30000 - it gave me same 59Hz. I enabled CPU frequency output on PB2 - the CPU frequency is 8MHz as it should be. When i set it to 1MHz - PB0 outputs around 7Hz signal. But it should be 75392/2 = 37696Hz.
What am i doing wrong here? How do I set ATTiny10 to generate IRQ at desired frequency?
Hi, I think I've figured it out. You are using the 16-bit Timer/Counter0 in Normal mode, since you have WGM 3:0 set to 0000. To quote the datasheet:
In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the BOTTOM (0x0000).
Each time the counter reaches 52 it causes a compare match interrupt, but it doesn't reset.
So you're dividing the 8MHz clock by 2^16 giving 122Hz, which sounds close to what you're getting (allowing for clock inaccuracy).
I think if you try Clear Timer on Compare Match (CTC) Mode (WGM 3:0 set to 0100) it should all work fine.
technoblogy, thank you, now i understand. Setting TCCR0B to 0b00001001 fixed the output. Also, thank you for this core!
You're welcome.
PS I like your digitalWrite etc macros - can I include them in the article?
Yes, why not? Pretty useful for beginners.