我正在使用NodeMCU V3模块。每当我尝试向服务器发出http请求时,模块就会崩溃。
这是代码:
void setup() {
WiFi.begin("wifi-name", "wifi-password");
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI to connect }
}
void loop() {
HTTPClient http;
WiFiClient client;
http.begin( client, "server-address" );
int httpCode = http.GET();
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
delay( 1000 );
}
这是结果,如串行监视器中所示:
200
["JSON response from the server"]
Exception (28):
epc1=0x40212e82 epc2=0x00000000 epc3=0x00000000 excvaddr=0x000001b6 depc=0x00000000
>>>stack>>>
ctx: cont
sp: 3ffffc90 end: 3fffffc0 offset: 01a0
3ffffe30: 00000000 4bc6a7f0 0000333f 3ffee5f8
3ffffe40: 00000000 00000000 4bc6a7f0 00000000
[...]
3fffffb0: feefeffe feefeffe 3ffe84e8 40100c41
<<<stack<<<
奇怪的是,它正确地从服务器检索了响应,但是大约一秒钟后,它向串行监视器吐出了异常并复位。起初我以为可能是因为我同时在运行ESP8266WebServer,但是即使运行了我在互联网上可以找到的最基本的示例,它仍然崩溃。我试图在Arduino IDE而不是PlatformIO上甚至是使用不同的NodeMCU上编译相同的代码,都无济于事。
编辑:经过更多的播放后,将延迟设置为至少10秒似乎会使NodeMCU在3个请求之后而不是在第一个请求之后崩溃。可能是几次请求后内存溢出?我是否缺少为ESP8266准备新请求的关键部分?
答案 0 :(得分:6)
无需一次又一次在loop()
中重新创建WiFi和HTTP客户端。您可以全局声明一次。这是此简单草图的稳定版本:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPHTTPClient.h>
HTTPClient http;
WiFiClient client;
void setup() {
Serial.begin(115200);
Serial.println();
WiFi.begin("****", "****");
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("done.");
}
void loop() {
http.begin(client, "http://httpbin.org/get"); // <1KB payload
// http.begin(client, "http://www.geekstips.com/esp8266-arduino-tutorial-iot-code-example/"); // 30KB payload
int httpCode = http.GET();
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
Serial.printf("Free heap: %d\n", ESP.getFreeHeap());
delay(1000);
}
报告的可用堆随着时间的推移非常稳定。
请注意在注释行中添加的用于测试的第二个URL。 http.getString()
很方便,并且对于较小的资源很有效,但是会产生意外的结果,即对于较大的资源会产生错误的结果-您只能看到打印到控制台的主体的一小部分。
对于较大的有效负载,您应该直接使用低级WiFiClient,并逐行或逐字符读取/解析响应。有关模板,请参见https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-examples.html上的文档。
void loop()
{
WiFiClient client;
Serial.printf("\n[Connecting to %s ... ", host);
if (client.connect(host, 80))
{
Serial.println("connected]");
Serial.println("[Sending a request]");
client.print(String("GET /") + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n" +
"\r\n"
);
Serial.println("[Response:]");
while (client.connected() || client.available())
{
if (client.available())
{
String line = client.readStringUntil('\n');
Serial.println(line);
}
}
client.stop();
Serial.println("\n[Disconnected]");
}
else
{
Serial.println("connection failed!]");
client.stop();
}
delay(5000);
}