8 years, 2 months ago.

Variable not getting updated in code running on mbed board

include the mbed library with this snippet

 #include "mbed.h"
 
DigitalOut myled1(LED1);
DigitalOut myled2(LED2);
DigitalOut myled3(LED3);
DigitalOut myled4(LED4);
Serial pc(USBTX, USBRX);

int main() 
{ int c;
    while(1)
    {
    pc.scanf("%d",&c);
    pc.printf("hey i received %d",c);
    if (c==1050)
    {myled1=1;
    myled2=0;
    myled3=0;
    myled4=0;
    }
    else if (c==2050)
    {   myled1=0;
        myled4=0;
        myled3=0;
        myled2=1;
    }
    else if (c==3050)
    {myled3=1;
    myled4=0;
    myled2=0;
    myled1=0;
    }
    else if (c==4050)
    {myled4=1;
    myled3=0;
    myled2=0;
    myled1=0;
    }
    }
}

The above code receives value of 'c' from terminal and takes decision based on the same. The issue I am facing is that when I use the printf, variabl c gets updated and the code runs properly otherwise not. Please help.

2 Answers

8 years, 2 months ago.

I use an ISR to process input characters from pc.. Here is the loop used while inside the ISR. PcRxChar(char ch) (not shown) is used to process the inputted data. i.e. store in character buffer, handle special chars (CR, LF, BS, ^C, etc.)

    while (pc.readable()) {
        char inchar = pc.getc();             //read data from UART/USB
        PcRxChar(inchar);                    //go process char
    }

Accepted Answer
8 years, 2 months ago.

Hi,
Try to declare the variable 'c' as volatile to prevent the compiler from optimizing the related code.

volatile int c;


Have a look at here for more details.