Arduino打印我不告诉它打印的东西

时间:2019-10-14 01:04:19

标签: arduino esp8266

我已经编写了一个程序(很可惜,因为这是我的第一个arduino项目之一),该程序侦听tcp端口,如果接收到某些字节,它就会响应。

这有效,但是,发生这种情况时,我正在向串行监视器打印“ ALIVE”。问题是它先打印ALIVE,然后再打印我正在比较的char变量的值。

#000000

删除

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");

1 个答案:

答案 0 :(得分:0)

您正在溢出变量undefined。通过将其初始化为空字符串,您仅分配了一个字节的存储空间。您将其传递到POST,并在此单字节数组中存储response个字节。

此时,您已将数据写入数组末尾之外,其结果是不可预测的且不确定的。

您需要确保array_to_string()的大小足以容纳要在其中构建的字符串。

由于您知道响应为8个字节,因此效果更好:

len*2+1

如果您在代码的其他位置修改变量response#define RESPONSE_LENGTH 8 char response[RESPONSE_LENGTH*2+1]; array_to_string(responseBytes, RESPONSE_LENGTH, response); ,它们也很容易溢出。