简体   繁体   中英

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

I am trying to find specific string in another string which is received via UART. However, my function returns 0, although string is not inside uart received string. Here is my function:

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

Program works with gcc, but it is not working as I expected when I try it with Keil. Can you help related this issue?

Your Problem is not the function strstr() .

It is the way you are collecting your command

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

HAL_UART_Receive_IT is a non blocking function, so it returns directly after the USART is configured. This string in your command array is something undefined at this time.

Use HAL_UART_Receive() or the HAL_UART_RxCpltCallback()

Try this: choose microlib in target option

look this image

微库选项

Wait for the UART to complete before using memory. Do not use uninitialized variables. In addition to the other answer, you can also poll HAL_UART_State until the peripheral stops receiving.

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

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