Arduino打印的东西,我';我不会让它打印的
我编写了一个程序(很糟糕,因为这是我的第一个arduino项目之一),它侦听tcp端口,如果它接收到某些字节,它就会响应 这是可行的,但发生这种情况时,我会将“活动”打印到串行监视器上。问题是,它以活动方式打印,然后打印我正在比较的char变量的值Arduino打印的东西,我';我不会让它打印的,arduino,esp8266,Arduino,Esp8266,我编写了一个程序(很糟糕,因为这是我的第一个arduino项目之一),它侦听tcp端口,如果它接收到某些字节,它就会响应 这是可行的,但发生这种情况时,我会将“活动”打印到串行监视器上。问题是,它以活动方式打印,然后打印我正在比较的char变量的值 byte responseBytes[8]; char* alive = "ABCD000000000112"; char* clientAlive = "ABCD000000000113"; void loop() {
byte responseBytes[8];
char* alive = "ABCD000000000112";
char* clientAlive = "ABCD000000000113";
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
for (byte n = 0; n < 8; n++) {
responseBytes[n] = client.read();
}
char* response = "";
array_to_string(responseBytes, 8, response);
if (strcasecmp(response, alive) == 0){
Serial.println("ALIVE"); //<-- This prints ALIVE and ABCD000000000112
client.write(clientAlive); //<-- This was added after the issue occured, it is not the issue.
}
for (byte n = 0; n < 8; n++) {
responseBytes[n] = 0;
}
}
}
void array_to_string(byte array[], unsigned int len, char buffer[])
{
for (unsigned int i = 0; i < len; i++)
{
byte nib1 = (array[i] >> 4) & 0x0F;
byte nib2 = (array[i] >> 0) & 0x0F;
buffer[i*2+0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA;
buffer[i*2+1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA;
}
buffer[len*2] = '\0';
}
您的变量
响应溢出了。通过将其初始化为空字符串,您只分配了一个字节的存储空间。您将其传递给array\u to_string()
,它将len*2+1
字节存储在此单字节数组中
此时,您已经在数组末尾之外写入了数据,其结果是不可预测和未定义的
您需要确保response
足够大,可以包含正在构建的字符串
因为您知道响应是8个字节,所以这样会更好:
#define RESPONSE_LENGTH 8
char response[RESPONSE_LENGTH*2+1];
array_to_string(responseBytes, RESPONSE_LENGTH, response);
如果在代码的其他地方修改变量alive
或clientAlive
,它们也可能容易溢出。这是有效的。但我不明白为什么响应是“8*2+1”?看看你的array\u to\u string
函数,看看那里的i*2+1
。也许这表明您应该以某种方式重新设计此函数。@Mattigins您正在其中存储以null结尾的字符串;+1表示最后的\0字节。
#define RESPONSE_LENGTH 8
char response[RESPONSE_LENGTH*2+1];
array_to_string(responseBytes, RESPONSE_LENGTH, response);