I noticed such an interesting feature; in interrupts, global variables change, but these changes are not available for main; let's say there is a frequency counter program

#define F_CPU 3686400LU #include <avr/io.h> #include <stdlib.h> #include <util/delay.h> #include "LCD.h" #include <string.h> #include <avr/interrupt.h> char buffer[10]; unsigned long c=0; void eraseBuf(char *buf){ for (int i=0; i<10; i++){ buf[i]=0; } } void initt0(void){ TCCR0|=1<<CS00|1<<CS01|1<<CS02;//внСшний источник тактирования TIMSK|=1<<TOIE0; TCNT0=0; } void initPWM(void){ DDRD|=1<<7;//oc2 OCR2=170; TCCR2|=(1<<WGM20)|(1<<WGM21)|(1<<COM21)|(0<<CS22)|(1<<CS21)|(0<<CS20); //fastPWM; 1/64 TCNT2=0; } ISR(TIMER0_OVF_vect){ c=c+1; } int main(){ initPWM(); LCDinit(); LCDclear(); initt0(); sei(); while(1){ _delay_ms(1000); LCDclear(); c=c*256+TCNT0; LCDstring(itoa(c,buffer,10),0,0); eraseBuf(buffer); TCNT0=0; c=0; } return 0; } 

the display will show the nonsense that remained in TCNT0, without optimizing the code, the global variable is available, but the program does not work properly.

  • And actually your question is what? - AivanF.

1 answer 1

Add the keyword volatile to the definition.

 volatile unsigned long c=0; 

This will let the compiler know not to optimize the variable c . It is used in a loop in main and is 100% likely to be loaded into registers once before the loop, and not re-read from memory. With volatile compiler will always load a value from memory into a register each time this variable is accessed.

  • thank! helped - WurZ