簡體   English   中英

STM32 - Strstr 函數無法按預期工作(UART)

[英]STM32 - Strstr function does not work as I expected (UART)

我正在嘗試在通過 UART 接收的另一個字符串中查找特定字符串。 但是,我的函數返回 0,盡管字符串不在 uart 接收的字符串中。 這是我的功能:

bool GetCommand(UART_HandleTypeDef *huart, char *command, char *getCommand, uint8_t size) {
    char *ptr;
    if (HAL_UART_Receive_IT(huart,command,size) == HAL_OK) {
        ptr = strstr(command,getCommand);
    }
    if (ptr) {
        return 1;
    } else {
        return 0;
    }
}

程序與 gcc 一起工作,但是當我嘗試使用 Keil 時它沒有按我預期的那樣工作。 你能幫忙解決這個問題嗎?

你的問題不是函數strstr()

這是你收集命令的方式

if(HAL_UART_Receive_IT(huart,command,size) == HAL_OK) {
    ptr = strstr(command,getCommand);
}

HAL_UART_Receive_IT是一個非阻塞函數,所以配置好 USART 后直接返回。 你的命令數組中的這個字符串此時是未定義的。

使用HAL_UART_Receive()HAL_UART_RxCpltCallback()

試試這個:在目標選項中選擇 microlib

看這張圖片

微庫選項

在使用內存之前等待 UART 完成。 不要使用未初始化的變量。 除了其他答案,您還可以輪詢 HAL_UART_State 直到外設停止接收。

bool GetCommand(UART_HandleTypeDef *huart, char *command, char *getCommand, uint8_t size) {
    if (HAL_UART_Receive_IT(huart,command,size) != HAL_OK) {
        // handle error
        return 0;
    }

    // wait until UART stops receiving
    while ((HAL_UART_State(huart) & HAL_UART_STATE_BUSY_RX) == HAL_UART_STATE_BUSY_RX) {
         continue;
    }

    return strstr(command, getCommand) != NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM