I am trying to write a delay function in C, which should take 0.5 seonds then carry on. I am aware that there are libraries for this purpouse, I want to make it myself.
#include <avr/interrupt.h>
#include <avr/io.h>
#define bitset(var,bitno) ((var) |= (1 << (bitno)))
int volatile time_unit;
ISR(TIMER0_COMPA_vect) {
time_unit += 1;
}
void wait_func(){
TCNT0 = 0;
time_unit = 0;
while (time_unit < 31);
}
int main(void){
DDRD = 1;
cli();
bitset(TCCR0A, WGM01);
bitset(TCCR0B, CS00);
bitset(TCCR0B, CS02);
OCR0A = 0xFF;
bitset(TIMSK0, OCIE0A);
sei();
while(1){
PIND = 0;
wait_func();
PIND = 1;
wait_func();
};
}
The timer is in CTC- Mode 1024 prescaler, counting 31*255 (OCR0A = 0xFF) times should give about 0.5 seconds at a base clockrate of 16MHz of the Arduino Atmega328p. The code works, but it turns the LED on and of at a rate of 1 second, (1 sec on 1 sec off). I do not understand why.