Hello. I'm trying to use the timer manipulatin the registers, so the first i did was read the datasheet.
However, I have a problem with the time that the ISR function executes.
I'm using the timer0, in CTC mode.
The idea is turn on and off a led every 0.5 second, so im incrementing a variable each time the ISR function executes.
The prescaler is set in 1024, and the output compare register in 249, so interrupt frequency (Hz) = (Arduino clock speed 16MHz) / (prescaler * (compare match register + 1))
interrupt frequency = 16Mhz7(1024*(249+1)) = 62.5 Hz
So if I understund correctly, the ISR function executes 62.5 times per second, and when enter 31 times equals to 0.5 seconds, but the cont variable is changing every 5 seconds.
What is wrong?
thanks!
#define ledPin 8
int cont=0;
bool estado = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
SREG = SREG & ~(1<<7); //desabilitar TODAS las interrupciones -- bit7= Global interupt eneable
TCCR0B |= (1<<2) | (1<<0); //CS02:0 Clock select - clock source -- prescaler=1024
//CTC MODE
TCCR0A |= (1<<1);
//--------
TCNT0 = 0; //Writing to the TCNT0 register blocks (removes) the compare match on the following timer clock.
OCR0A = 249; //Outupt Compare Register A --> frec interrupcion= 62.5Hz
TIMSK0 |= (1<<1); //Bit 1 – OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable
SREG = SREG | (1<<7); //habilito TODAS las interrupciones -- bit7= Global interupt eneable
}
ISR(TIMER0_COMPA_vect)
{
Serial.println(cont);
if(cont==31)
{
cont=0;
}
cont++;
}
void loop() {
// put your main code here, to run repeatedly:
if(cont==31)
{
digitalWrite(ledPin, digitalRead(ledPin)^1);
}
}