Reputation: 77
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?
Upvotes: 0
Views: 834
Reputation: 141698
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;
}
Upvotes: 0
Reputation: 1102
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()
Upvotes: 2