I have an interrupt service routine that contains the variable count
and a variable state
that changes when count
reaches a certain value.
What I want my code to do is change and maintain state
for a certain period of time determined by the value of count
in the if statements in the ISR.
e.g. I want the variable state
to equal 1 for 10 counts;
I want state
to equal 0 for 5 counts.
Somewhat similar to changing the duty cycle of a PWM.
The problem I am having is that the variable state
resets to zero around the end of the ISR or the end of the if statement, I'm not sure.
After searching for answers, I have found that it might be related to the gcc compiler's optimisation but I cannot find a fix for this problem besides declaring volatile
variables, which I have already done.
Any help is appreciated thanks.
My code:
#include <avr/io.h>
#include <avr/interrupt.h>
volatile int count = 0;
volatile int state = 0;
int main(void)
{
cli();
DDRB |= (1 << PB2);
TCCR0B |= (1 << CS02)|(0 << CS01)|(1 << CS00);
TIMSK |= (1 << TOIE0);
sei();
while(1) {
...
}
}
ISR(TIM0_OVF_vect)
{
cli();
// user code here
count = count + 1;
if ((count > 5) && (state < 1) && !(PORTB & (1 << PB2))) {
state = 1;
count = 0;
}
else if ((count > 10) && (state > 0) && (PORTB & (1 << PB2))) {
state = 0;
count = 0;
}
sei();
}