Blog

LightSensor2WWW mit XMLHttpRequest

Die backgroundColor Eigenschaft dynamisch angesteuert über einen Lichtsensor und den ESP8266 :

 

/*
—————————————————————————————————–
Author: BNC
Platforms: ESP8266
Language: C++/Arduino

Thank you:
——————————————————————————————————
https://github.com/acrobotic/Ai_Tips_ESP8266/tree/master/webserver_html_js
——————————————————————————————————
*/

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server;

char* ssid = „XXXXXXXXXXXX“;
char* password = „XXXXXXXXXXXXXX“;

char webpage[] PROGMEM = R“=====(
<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′ />
</head>
<body>
<p> Sensor Status: <span id=“ADCValue“>0</span> </p>
</body>
<script>
setInterval(function() {
// Call a function repetatively with 2 Second interval
getData();
}, 50); //2000mSeconds update rate

function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.body.style.backgroundColor = ‚rgb(‚ + this.responseText + ‚,‘ + this.responseText + ‚,‘ + this.responseText + ‚)‘;
document.getElementById(„ADCValue“).innerHTML = this.responseText;
}
};
xhttp.open(„GET“, „readADC“, true);
xhttp.send();
}
</script>
</html>
)=====“;

void setup()
{
WiFi.begin(ssid,password);
Serial.begin(115200);
while(WiFi.status()!=WL_CONNECTED)
{
Serial.print(„.“);
delay(500);
}
Serial.println(„“);
Serial.print(„IP Address: „);
Serial.println(WiFi.localIP());

server.on(„/“,[](){server.send_P(200,“text/html“, webpage);});
server.on(„/readADC“, handleADC);
server.begin();
}

void loop()
{
server.handleClient();
}

void handleADC() {
int a = (analogRead(A0)/4);
String adcValue = String(a);
server.send(200, „text/plane“, adcValue); //Send ADC value only to client ajax request
}