Scope of variable declaration

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hey friends,
I have a problem with understanding the scope of a variable in AVR-GCC. I use avr-gcc in Windows (WinAVR), I wrote a simple example using the Timer0 as a counter, overflow interrupt mode. This is my code:

#include 
#include 

uint8_t val; // I declared a variable as a counter
void main(void){
	val=0;	
	DDRB=0xFF;  //PORTB la output PORT, I connect PORTB to a 7_seg LED
	PORTB=0x00;
	
	DDRD=0x00; 
	PORTD=0xFF; 	
	
	TCCR0=(1<<CS02)|(1<<CS01); 
	TCNT0=0xFF;        
	TIMSK=(1<<TOIE0); 
	sei(); 		
	
	while (1){ 		
		if (bit_is_clear(PIND,7)) { 
		   val=0; 	
		   PORTB=val;     
		}
	}
	return 0;
}

ISR(TIMER0_OVF_vect ){
	val++;
	if (val==10) val=0;
	PORTB=val; 
	TCNT0=0xFF; 
};

This is the simulation circuit

The idea is that when I press the upper button (connected to T0 pin)the Counter works,variable val is increased 1 unit (happen in ISR of Timer0). When the lower button is pressed,variable val is reset to 0(see code in while loop). My problem is here: for example I press the upper button 4 times, the displayed value is 4, then I press the lower button the displayed value is 0 (correct). However, if I press the upper button 1 more time, the displayed value is 5, it is not 1. Seems that the variable val declared at the top of my code is not global? is it my mistake?
Your ideas will be the great helps for me, thanks all.

Last Edited: Tue. Sep 2, 2008 - 12:49 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Declare val as volatile.

Edit:
The compiler does not know that there is some asynchronous event (the ISR) overwriting tahe variable 'val'.

If you look at the compiler output, then you will see that the main() function is not accessing the variable location in SRAM, but rather a copy of the value in a register.
So the ISR overwrites the value in SRAM, but the main function carries on to use the register instead the updated value in SRAM.

The keyword 'volatile' tells the compiler that the variable might be modified by some external entity (such as ISRs, hardware, or alien technology). That means the value is always fetched from SRAM on a read operation and always written back on a write.

HTH,
Thomas

pycrc -- a free CRC calculator and C source code generator

Last Edited: Tue. Sep 2, 2008 - 01:07 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Then read the FAQ in the user manual - point 1 will be familiar:

http://www.nongnu.org/avr-libc/u...

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

yah, it has been solved, thanks tpircher and clawson for your hints