【问题标题】:STM32 - Strstr function does not work as I expected (UART)STM32 - Strstr 函数无法按预期工作(UART)
【发布时间】:2020-03-23 21:11:09
【问题描述】:

我正在尝试在通过 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 尝试它时,它并没有像我预期的那样工作。你能帮忙解决这个问题吗?

【问题讨论】:

标签: c stm32 uart strstr


【解决方案1】:

您的问题不是函数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()

【讨论】:

    【解决方案2】:

    等待 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;
    }
    

    【讨论】:

    • 我很感谢您的回答...它按我之前的计划工作。祝你有美好的一天:)
    【解决方案3】:

    试试这个: 在目标选项中选择 microlib

    看这张图片

    【讨论】:

    • 感谢您的回答。但是 microlib 已经被选中。
    • 一开始,keil默认编译器是armcc,c lib是microlib;你可以通过gcc运行这个程序员,所以我认为c lib会导致这个问题,可能是armcc c lib有bug
    猜你喜欢
    • 2018-04-10
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    相关资源
    最近更新 更多