虽然在条件满足后循环不会中断,但是如果我在while循环中使用“printf”,则相同的代码开始工作

时间:2018-02-25 03:55:38

标签: c embedded atmel atmelstudio

我将首先解释一下情况:

  1. 这是一个菜单驱动的程序,其中所选的选项继续执行,直到其他选项被送入
  2. 该选项通过USB端口馈送到微控制器,ISR调用处理输入命令解析的功能
  3. 只要输入进入无限循环的选项
  4. ,程序就会运行得很好
  5. 进入无限循环后,即使输入了停止程序的命令,也无法从中断。
  6. 即使正在执行while循环,程序也会输入ISR,因为已经使用ISR中的printf进行了检查。
  7. 当在ISR中遇到停止程序的命令时,它设置由while循环检查的标志。
  8. 现在为奇怪的部分。如果我在while循环中插入printf(“%u”,命令),则相同的代码开始工作。
  9. sudo代码如下:

    ISR_USB()
    {
        char command=read_from_buffer();
        printf("Entered ISR and command = %c",command); // Prints on serial port and confirms the program entered ISR 
        if(command==STOP_DEMO)
            FLAG_TO_BREAK_WHILE=true;
        printf("%u",FLAG_TO_BREAK_WHILE); // Confirms correct value of flag is set
        command_parser(command);
     }
    
     command_parser(command)
    {
        if(command=='1')
             printf("HELLO WORLD");
        else if(command=='2')
        {
            printf("While started");
            while(!FLAG_TO_BREAK_WHILE); // Gets stuck here 
            /*
             starts working if the above while is replaced by :
             while(!FLAG_TO_BREAK_WHILE)
             {
              printf("%u",FLAG_TO_BREAK_WHILE);
              }
            */
        }
        else if (command=='3')
            printf("stop command executed");
    }
    

    请帮助我了解这里的情况和这种行为。

    注意:PARSER在另一个文件中并且变量是异常的。

1 个答案:

答案 0 :(得分:5)

正在发生的事情是while(!FLAG)正在优化

if(!FLAG)
{
    while(true)
    {
         //do stuff
    }
}

要解决此问题,请将标志定义为volatile,并且每次代码访问时,编译器都将被强制从内存中读取标志。