我使用WiFiClient连接到外部主机并读取负载。这部分代码运行良好,直到我尝试将字符收集到一个字符串中进行解析。
有代码
#include <ESP8266WiFi.h>
const char* ssid = "***";
const char* password = "***";
const char* host = "host.com";
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
pinMode(D5, OUTPUT);
}
void runBullshit()
{
digitalWrite(D5, true);
delay(500);
digitalWrite(D5, false);
}
void loop()
{
WiFiClient client;
if (client.connect(host, 80))
{
client.print(String("GET /path") + " HTTP/1.1rn" +
"Host: " + host + "rn" +
"Connection: closern" +
"rn"
);
char payload[] = "";
int size = 0;
while (client.connected())
{
if (client.available())
{
char data = client.read();
payload[size] = data;
}
size++;
}
payload[sizeof(payload)] = ' ';
Serial.println(payload);
client.stop();
}
else
{
Serial.println("connection failed!]");
client.stop();
}
delay(3000);
}
还有错误
Connecting to MikroTik-35C8D8 . connected
Exception (3):
epc1=0x40202611 epc2=0x00000000 epc3=0x00000000 excvaddr=0x40016d7f depc=0x00000000
ctx: cont
sp: 3ffffd80 end: 3fffffd0 offset: 01a0
>>>stack>>>
3fffff20: 00000000 40203ce8 3ffe8510 00000000
3fffff30: 3fffdad0 3ffeeab4 40203e0c 3fffefb0
3fffff40: 3fffdad0 00000000 00000064 40203ec6
3fffff50: 3fffdad0 00000000 3fffff98 40203f09
3fffff60: 3fffdad0 00000000 00000048 40203482
3fffff70: 3ffe88b9 00000000 40016d7f 40202611
3fffff80: 40204348 00000000 00001388 40203908
3fffff90: 00000000 3ffef77c 00000000 00000000
3fffffa0: 00000000 00000000 00000000 00000000
3fffffb0: 3fffdad0 00000000 3ffeeaac 40203e98
3fffffc0: feefeffe feefeffe 3ffe8510 40100739
<<<stack<<<
ets Jan 8 2013,rst cause:2, boot mode:(3,7)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld
因此,如果我只将data
放入Serial中,我将看到整个有效负载没有错误,但在这种情况下,在上面我捕获了异常3并导致2。
PS是的,在我的代码中,我有digitalWrite等等,因为我将使用响应来决定是否将引脚设置为HIGH
问题是将payload
定义为大小为1
的数组。您不能将数据存储到其中。
在Arduino上,您可以使用String
类型:
String payload;
while (client.connected())
{
if (client.available())
{
char data = client.read();
payload += data;
}
}
Serial.println(payload);
client.stop();