I am not sure why, but the below code is not working.
I have tried to use timer0 of an Arduino Uno to delay time in milliseconds. Any help would be appreciated...
#include <avr/io.h>
//prototypes of functions
void delay_with_timer0();
void delay_generic(unsigned long);
void setup() {
//initializing built in LED as output
pinMode(LED_BUILTIN, OUTPUT);
//enabling serial monitoring for debugging
Serial.begin(9600);
}
void loop(){
//turning built in LED on and off
digitalWrite(LED_BUILTIN, HIGH);
delay_generic(1000);
digitalWrite(LED_BUILTIN, LOW);
delay_generic(1000);
Serial.print("SUCCESS\n");
}
void delay_with_timer0(){
//disable I-Flag
cli();
//initializing clock to zero
TCNT0 = 0;
//sets to normal mode
TCCR0A = (0 << WGM00);
TCCR0A = (0 << WGM01);
TCCR0B = (0 << WGM02);
//sets prescaler
TCCR0B = (0 << CS00);
TCCR0B = (1 << CS01);
TCCR0B = (0 << CS02);
//waiting for the overflow flag to be set
while(true){
if(TIFR0 |= (1 == TOV0)){
break;
}
}
//stops the clock
TCCR0B = (0 << CS00);
TCCR0B = (0 << CS01);
TCCR0B = (0 << CS02);
//clears TOV0 flag
TIFR0 = (0 << TOV0);
//enable I-Flag
sei();
}
void delay_generic(unsigned long ms){
//for loop that uses delay_with_timer0() function
for(int i = 0; i < ms*250; i++){
delay_with_timer0();
}
}