swapan
Full Member level 4

Hi guys,
Somewhere I have seen that 'variable shared between ISR and main code should be declared volatile'. Accordingly, I took up the following code to make a practical test. But it is noticed that control passes to 2nd loop without performing the task of 1st loop. After trying it various ways and failing every time, I changed the declaration of "duty" from Unsigned Volatile short int to Unsigned int. Interestingly it is seen that the code works well as desired.
Please see the code and offer your valued comments on importance and use of Volatile declaration of variable.
Somewhere I have seen that 'variable shared between ISR and main code should be declared volatile'. Accordingly, I took up the following code to make a practical test. But it is noticed that control passes to 2nd loop without performing the task of 1st loop. After trying it various ways and failing every time, I changed the declaration of "duty" from Unsigned Volatile short int to Unsigned int. Interestingly it is seen that the code works well as desired.
Please see the code and offer your valued comments on importance and use of Volatile declaration of variable.
Code:
sbit blink_led at RC4_bit;
sbit led at RC5_bit;
sbit rly at RB3_bit;
unsigned int count, blink_cnt;
volatile short int duty, blink_flag, count_flag;
void interrupt ()
{
if (INTF_bit == 1) {
PR2 = duty;
count++;
if (count > 5) {
count_flag = 1;
count = 0;
blink_cnt++;
}
if (blink_cnt > 10)
{
blink_flag =1;
blink_cnt = 0;
}
TMR2IF_bit = 0;
TMR2IE_bit =1;
INTF_bit = 0;
INTE_bit = 0;
TMR2ON_bit = 1;
}
if (TMR2IF_bit == 1) {
blink_led =1;
delay_MS(1000);
blink_led=0;
TMR2ON_bit = 0;
INTE_bit = 1;
TMR2IE_bit =0;
TMR2IF_bit = 0;
}
}
void main() {
GIE_bit = 1;
PEIE_bit = 1;
INTEDG_bit = 1;
INTE_bit = 1;
duty = 250;
T2CON = 0x3E;
count_flag = 0;
do {
if (count_flag == 1) {
duty --;
count_flag = 0;
}
if (blink_flag==1)
{
led = ~led;
blink_flag = 0;
}
}while ( duty >=50); // LOOP No.1
led = 1;
do {
if (count_flag == 1)
count_flag = 0;
if (blink_flag == 1) {
rly = ~rly;
blink_flag = 0;
}
} while (1); // LOOP No.2
}