I use an STM32 microcontroller board and to summarize the question, in the following code inside the if
clause the variable called current_val
does not take the value it is assigned some lines before:
int main(void) {
//initialization code
while (1) {
uint16_t I2C_value = get_data();
float current_val = (I2C_value / 4096.0 - 0.5) * 50 * 1000;
sprintf(msg_int, "%.3f \r\n", current_val);
HAL_UART_Transmit(&huart2, (uint8_t*) msg_int, strlen(msg_int), HAL_MAX_DELAY);
HAL_Delay(250);
if (current_val > 500) {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
}
else {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);
}
}
}
But if I declare current_val
as global it works:
float current_val;
int main(void) {
//initialization code
while (1) {
uint16_t I2C_value = averaging_data();
current_val = (I2C_value / 4096.0 - 0.5) * 50 * 1000;
sprintf(msg_int, "%.3f \r\n", current_val);
HAL_UART_Transmit(&huart2, (uint8_t*) msg_int, strlen(msg_int), HAL_MAX_DELAY);
HAL_Delay(250);
if (current_val > 500) {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
}
else {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);
}
}
}
What could be the reason in the first case current_val
is not remaining the same after it is assigned? I don't understand what makes it change since there is nothing in the code to update its value.