strstr找不到子字符串,但缓冲区包含该值 [英] strstr cannot find substring but buffer contains the value
问题描述
我正在尝试使用STM32F407V6T6
和CubeMx
进行UART
.
I was trying UART
using STM32F407V6T6
and CubeMx
.
我的UART
工作正常.比较缓冲区时遇到的问题:我正在使用strstr()
检查缓冲区是否包含有效的子字符串.
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.
这是代码:
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);
}
}
这里我正在做的是我已连接我的GSM Module Sim800
并发送了AT
.调试我的代码后,我发现buff[6] = 'O'
和buff[7] = 'K'
.并且在检查我可以使LED闪烁的同时.
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
}
但是当我尝试使用功能strstr()
时,它不会返回任何内容.
But when I try function strstr()
It doesn't return anything.
if (strstr((char*)buff, "OK")) {
Red_Blink(1000); //RED LED DOENS'T Blink
}
起初我以为我的数组buff
没有以\0
结尾.所以我做到了
At first I thought my array buff
is not ending with \0
. So I did this
buff[9] = '\0';
但是什么都没有改变.
关于为什么它不能与strstr()
一起使用的任何建议.
Any suggestions why it's not working with strstr()
.
谢谢.
推荐答案
从您的观察和分析来看,buff
确实在偏移量6
包含OK
,并且在偏移量9处为空终止.
From your observations and analysis, buff
does contain OK
at offset 6
and is null terminated at offset 9.
如果strstr
在buff
中找不到OK
,则可能的解释是buff
可能在偏移6之前包含另一个空终止符,并且OK
在该空终止符之前不存在.
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
被初始化为所有位0,因此任何未更改的元素都是空终止符. HAL_UART_Receive_IT
是否还可能将空字节存储到buff
中?空字节有时在串行传输中用作填充.
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.
C库函数strstr
也有可能在您的目标平台上不起作用.以前,我的嵌入式ST平台上的错误字符串功能及其工具集产生了无法解释的错误.
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.
这篇关于strstr找不到子字符串,但缓冲区包含该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!