I am running the following code on my ESP8266 (AI-Thinker ESP8266MOD).
I send an HTTP GET request and a pin is set to high for a 1/2 second.
However, after some time (sometimes 1hr, 2hrs, 12hrs, totally random), it stops responding to HTTP requests. I think it might be because of heap fragmentation due to the String objects I'm using.
Questions:
How can I replace the request
(in loop()
) and s
and text
(in GenerateResponse()
) objects with char arrays?
After I replace the String objects with char arrays, how can I use the indexOf()
method and +
operator on the char arrays?
Will this approach help with heap fragmentation?
Is it possible to find out if heap fragmentation is the problem?
#include <ESP8266WiFi.h>
const char* ssid = "myWifi";
const char* wifiPassword = "y76ggS";
const char* passwordToOpenDoor = "/81"; //password should begin with a slash
const int doorPin = 5;
WiFiServer server(301); //Pick any port number you like
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(10);
Serial.println(WiFi.localIP());
pinMode(doorPin, OUTPUT);
digitalWrite(doorPin, 0);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, wifiPassword);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
server.begin();
Serial.println("Server started. Diagnostics info:");
Serial.println(WiFi.localIP());
}
void loop() {
client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
String request = client.readStringUntil('\r');
client.flush();
Serial.println(request);
if (request.indexOf(passwordToOpenDoor) != -1) { //Is password correct?
GenerateResponse("Password is correct");
OpenDoor();
}
//Got a GET request and it wasn't the favicon.ico request, must have been a bad password:
else if (request.indexOf("favicon.ico") == -1) {
GenerateResponse("Password is incorrect.");
}
}
void OpenDoor() {
digitalWrite(doorPin, 1);
delay(500);
digitalWrite(doorPin, 0);
}
void GenerateResponse(String text) {
Serial.println(text);
String s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: text/html\r\n\r\n";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";
s += "<br><h1><b>" + text + "</b></h1>";
s += "</html>\n";
client.flush();
client.print(s);
delay(1);
}
String.indexOf()
can be replaced bystrstr(str1, str2)
. It return position number when str2 match part of the str1.