Volatile problems

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

Hello All,

I've got some troubles using volatile variables:

while(!wakeup)
		{	// executes every 30.5ms
			//read button states
			if((u8_cycles==0) && (!BUTTON_RELEASED)) u8_cycles=1; //START CYCLES

			/*if(!FEEDER_SW_RELEASED && u8_motor==ON && u8_timeout<25) // STOP MOTOR
			{
				u8_timeout=0;
				u8_motor=OFF;
				CLEAR_MOTOR;
			}*/

			// go back to sleep
			sei();			// enable interrupts
			set_sleep_mode(SLEEP_MODE_PWR_DOWN);
			sleep_mode();
		}

this does not work, but the folowing does:

while(1)
		{	// executes every 30.5ms
			//read button states
			if((u8_cycles==0) && (!BUTTON_RELEASED)) u8_cycles=1; //START CYCLES

			/*if(!FEEDER_SW_RELEASED && u8_motor==ON && u8_timeout<25) // STOP MOTOR
			{
				u8_timeout=0;
				u8_motor=OFF;
				CLEAR_MOTOR;
			}*/

			if(wakeup==TRUE) break;
			// go back to sleep
			sei();			// enable interrupts
			set_sleep_mode(SLEEP_MODE_PWR_DOWN);
			sleep_mode();
		}

the wakeup is global declared as volatile unsigned char and modified inside a ISR. Any ideas?

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

The two programs are not equivalent... consider your order of evaluation.

In the first case the contents of the loop are run only as long as wakeup is false. wakeup is evaluated BEFORE any operations are performed.

In the second case the contents of the loop are run, and you only break out, just before the sleep of wakeup is true. wakeup is evaluated AFTER your button/motor code.

I imagine you'll get the same "not working" condition if you placed the if/break immediately after teh while(1)

Writing code is like having sex.... make one little mistake, and you're supporting it for life.

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

maybe it should be

do
{

} while(!wakeup)

KISS - Keep It Simple Stupid!