I am trying to create a sub-routine that is functionally identical to _delay_ms(). I am already using Timer0 for switch debouncing and it seems to interfere with _delay_ms().
Since I am using Timer2 to track a time interval for another purpose I want to employ it to create a delay sub-routine. I've set the timer2 interrupt to track time in seconds. getTimeOfTimer2() will return the total time in seconds since the AVR was turned on. pauseTheSystem() is intended to take a number in milliseconds and pause the MCU for that duration of time.
In this example I am trying to use my delay sub-routine to blink an LED.
My problem is once the program enters the do while loop the MCU hangs (LEDs won't blink). For some reason that I just don't understand it is unable to make the while comparison (I think). To make things even more mysterious if I add either a UART or LCD printf statement inside the do while loop the program will execute properly.
Does anyone have an idea as to what the problem might be? I've been staring at this for days and I am out of ideas. Thanks.
#define F_CPU 1000000 #include#include #include #define TIMER2_COUNTER_LIMIT 250 void pauseTheSystem(float); float getTimeOfTimer2(void); volatile unsigned int timeUnit = 0; volatile unsigned int milliSeconds = 0; volatile unsigned int seconds = 0; ISR(TIMER2_OVF_vect) { ++timeUnit; if(timeUnit >= 4){ milliSeconds++; timeUnit = 0; if(milliSeconds >= 1000) { seconds++; milliSeconds = 0; } } } int main(void) { TIMSK |= (1 << TOIE2); OCR2 = TIMER2_COUNTER_LIMIT; TCNT2 = 0; TCCR2 |= (1 << CS20); sei(); DDRB = 0xff; PORTB = 0xff; while (1) { PORTB &= ~(1<<PORTB0); pauseTheSystem(500); PORTB = 0xff; pauseTheSystem(500); } } float getTimeOfTimer2(void) { return (float)seconds + (float)milliSeconds/1000; } void pauseTheSystem(float pauseMilliSeconds) { float stopTime = getTimeOfTimer2() + pauseMilliSeconds/1000; float currentTime = 0; do { currentTime = getTimeOfTimer2(); //For some reason this will only work if there is a printf statment here }while(stopTime > currentTime); }
Using:
ATmega16
AVR Studio 4.14
GCC Compiler
STK500
Windows 2000