interrupt - AVR: volatile variable resetting to zero -


i have interrupt service routine contains variable count , variable state changes when count reaches value.

what want code change , maintain state period of time determined value of count in if statements in isr.

e.g. want variable state equal 1 10 counts; want state equal 0 5 counts. similar changing duty cycle of pwm.

the problem having variable state resets 0 around end of isr or end of if statement, i'm not sure.

after searching answers, have found might related gcc compiler's optimisation cannot find fix problem besides declaring volatile variables, have done.

any 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(); }     

first of cli() has no effect in isr. when interrupt happens flag automatically cleared , restored @ end of isr - sei() needless well. there rational case when sei() inserted somewhere in middle of isr service let other isr's interrupt it. though not beginner level build such sophisticated isr system.

second: if set conditional structure elementary conditions should chained double operators. evaluation of (count > 5) & (state < 1) cannot predicted, correctly written (count > 5) && (state < 1). 'or'-ing || used.


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -