2016-08-20 616 views
0

我在Keil上使用STM32F微控制器。我在whilefor循环上遇到问题。共享代码是我的错误部分。我for或while循环不起作用。我留下了“step = 2”和“counter = 0”。我尝试了发布和调试模式。调试模式我看到了这个结果手表屏幕; stept = 1(WaitData = 1)在systemtick增加之后,在systemtick = 5000之后,step = 2(systemtick = 0 waitdata = 0),但for循环上的代码堆栈。Keil - 我的while循环不起作用

#include "stm32f4xx_hal.h" 
#include <stdio.h> 
#include <stdlib.h> 

int step = 0; 
int waitdata = 0; 
int systemtick1 = 0; 
int counter = 0; 
void HAL_SYSTICK_Callback(void) 
{ 
    if (WaitData == 1) 
    { 
     systemtick1++; 
     if (systemtick1 == 5000) 
     { 
      step = 2; 
      systemtick1 = 0; 
      WaitData = 0; 
     } 
    } 
} 

int main(void) 
{ 
    HAL_Init(); 
    SystemClock_Config(); 
    MX_GPIO_Init(); 
    HAL_Delay(2000); 
    step = 1; 
    WaitData = 1; 

    for (; WaitData==1 ;) // Or while (WaitData == 1); 
    { 
     asc++; 
    } 

    step = 3; 
    while (1) 
    { 
    } 
} 
+3

http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c – Notlikethat

+1

http://stackoverflow.com/questions/38257618/is-volatile-modifier-really-needed-if -global-variables-are-modified-by-an-interr – Notlikethat

+2

“waitdata”和“WaitData”应该是同一个变量吗?随机格式化的代码很难阅读,但看起来它甚至不会按原样编译。 – Notlikethat

回答

1

你在中断需求正在发生变化的变量被设置为volatile,因为你不知道了编译器优化。

对变量的访问主要以顺序,可预测的方式完成。但中断不可预测;因此您需要使用volatile才能更改正常“程序”流程之外的变量。