i want to know how we can run a loop for specified time and then after the time ends it show us the result.
e.g = we have two variables “a=0” and “b=0” and i want to run program for 5 minutes and when someone press 1 it increments in “a” and when someone press 2 it increments in “b” and then after 5 minutes the loop ends and it print out us value of “a” and “b”. this way we will know how many times 1 is pressed and how may time 2 is pressed.
For measuring seconds I have created an ISR interrupt routine at 50 Hz running on a 8mHz processor ATMega328p
void setupTimer()
{
// Timer 1 is se to CTC mode, 16-bit timer
TCCR1B = (1<<WGM12) | (1<<CS11); // prescaler 8 for Timer
OCR1A = 20000; // Timer 20.000 = 20ms repeat time
TIMSK1 = (1<<OCIE1A); // Enable interrupt on compare
}
Now we can use this to count time:
ISR(TIMER1_COMPA_vect)
{
count = (count + 1); // prescaler from 20ms to seconds
if (count >= 50)
{
time = (time + run); count = 0; // counts seconds when running, resets counter
}
}
In the main program you can change the value of run and time depending what you want to do.
run = 1; starts counting time in seconds
run = 0; stops counting time in seconds
time = 0; count = 0; resets time
Be aware that interrupts have priority so before using the variables used in the interrupt routine you should stop the interrupts and allow interrupts after you used this variable