简体   繁体   中英

STM32 usart interrupt cannot translate correct data to other functions

I have some problem when I use a stm32 discovery board send data to another one and it can get correct data and print in callback function, but cannot print correctly in other function.

void UART7_IRQHandler()
{
    HAL_UART_IRQHandler(&huart7);
    HAL_UART_Receive_IT(&huart7, (uint8_t *)UART7RxBuffer, 16);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef* huart)  
{   
    if(huart->Instance == UART7) {
        X = (UART7RxBuffer[1]-48) + (UART7RxBuffer[3]-48)*0.1 + (UART7RxBuffer[4]-48)*0.01 + (UART7RxBuffer[5]-48)*0.001;           
    }
}

But I receive wrong data like this

void controller(){
    printf("%.3f\t\n", X);
}

It should be 0.012, and it correct in HAL_UART_RxCpltCallback(), I receive -38.02, -0.009, 0.512, 0.012, -1.948 and so on in controller. How should I do to prevent this situation?

Without knowing if your MCU actually supports floating point etc, I would probably do something like this in order to diagnose/debug what is happening:

void UART7_IRQHandler()
{
    HAL_UART_IRQHandler(&huart7);
    HAL_UART_Receive_IT(&huart7, (uint8_t *)UART7RxBuffer, 16);
}

char d1;
char d2;
char d3;
char d4;
float X1;
float X2;
float X3;
float X4;
float X;

void HAL_UART_RxCpltCallback(UART_HandleTypeDef* huart)  
{   
    if(huart->Instance == UART7) {
        d1 = UART7RxBuffer[1]-48;  /* add breakpoint here, and single step from here while inspecting variables */
        d2 = UART7RxBuffer[3]-48;
        d2 = UART7RxBuffer[4]-48;
        d3 = UART7RxBuffer[5]-48;
        X1 = d1;
        X2 = d2 * 0.1;
        X3 = d3 * 0.01;
        X4 = d4 * 0.001;
        X = X1 + X2 + X3 + X4;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM