[我编写了一个(可怜的,因为这是我的第一个arduino项目之一)一个程序,该程序侦听tcp端口,如果接收到某些字节,它就会响应。
这可以,但是在发生这种情况时,我正在向串行监视器打印“ ALIVE”。问题是它先打印ALIVE,然后再打印我正在比较的char变量的值。
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';
}
正在删除
Serial.println("ALIVE");
停止打印任何内容。不只是活着
我不知道这里发生了什么。
串行监视器输出,如果有关系的话
ALIVE
ABCD000000000112ALIVE
ABCD000000000112ALIVE
ABCD000000000112
您正在溢出变量response
。通过将其初始化为空字符串,您仅分配了一个字节的存储空间。您将其传递给array_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
,它们也可能容易溢出。