问题
I was trying UART using STM32F407V6T6 and CubeMx.
My UART is working fine. The problem I'm getting while comparing the buffer: I am using strstr() to check that my buffer contains valid substring or not.
Here is the code:
uint8_t buff[10];
int main(void) {
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
Green_Blink(100);
Orange_Blink(100);
Blue_Blink(100);
Red_Blink(100);
__HAL_UART_ENABLE_IT(&huart2, UART_IT_TC);
__HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE);
HAL_Delay(1000);
while (1) {
HAL_UART_Transmit_IT(&huart2, (uint8_t *)"AT\r\n", 5);
Orange_Blink(100);
HAL_Delay(1000);
HAL_UART_Receive_IT(&huart2, buff, 10);
buff[9] = '\0';
if (buff[6] == 'O' && buff[7] == 'K') {
Green_Blink(1000); //Blinks
}
if (strstr((char*)buff, "OK")) {
Red_Blink(1000); //Doesn't blink
}
Clear_Buffer((char*)buff);
}
}
Here what I am doing is I have connect my GSM Module Sim800 and I send AT. After debugging my code I found that buff[6] = 'O' and buff[7] = 'K'. And while checking that I could blink the led.
if (buff[6] == 'O' && buff[7] == 'K') {
Green_Blink(1000); //Blinks
}
But when I try function strstr() It doesn't return anything.
if (strstr((char*)buff, "OK")) {
Red_Blink(1000); //RED LED DOENS'T Blink
}
At first I thought my array buff is not ending with \0. So I did this
buff[9] = '\0';
But nothing changed.
Any suggestions why it's not working with strstr().
Thanks in advance.
回答1:
From your observations and analysis, buff does contain OK at offset 6 and is null terminated at offset 9.
If strstr does not find OK in buff, a possible explanation is buff may contain another null terminator before offset 6 and OK is not present before this null terminator.
buff is initialized to all bits 0, so any element that is not changed is a null terminator. Is it also possible that HAL_UART_Receive_IT store null bytes into buff? null bytes are sometimes used as padding in serial transmissions.
It is also possible that the C library function strstr does not work on your target platform. I once had an inexplicable streak of bugs from faulty string functions on embedded ST platforms with their toolset.
来源:https://stackoverflow.com/questions/51829039/strstr-cannot-find-substring-but-buffer-contains-the-value