Reputation: 13
I'm using STM32F303 MCU. I used STM32CubeIDE to generated a simple project. In the project, it increases an int data by 1 in main() -> while() loop.
int data = 0;
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
while (1)
{
// HAL_Delay(20);
data++;
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
If I run in debug mode and add a breakpoint at data++ line, everything is fine. I can see that the int data increases in Live Expressions.
However, if I remove the breakpoint, the int data will be 3145848 (always this same number) immediately and the firmware stops.
Also, the HAL_Delay() will cause firmware fails. So I commented it out.
The firmware works well in NUCLEO development board.
I also checked:
Upvotes: 0
Views: 161
Reputation: 5510
The compiler knows that after you have incremented the value once, the only thing you are going to do next is increment it again. It is being helpful by saving time incrementing it all in one go rather than a little at a time.
If you don't want the compiler to be helpful like this, then you need to declare your counter volatile:
volatile int data = 0;
This tells the compiler to carry out each access to the variable one at a time in the exact order specified.
Upvotes: 1