Dear all,
I am trying to create a web server with photon and DHT11 to get local informations.
The program generates the page but cannot update the temperature and humidity data. I've tried several small modifications but nothing has worked so far. I haven't found anything like this that works this way. So I would be grateful if anyone could give me some advice. To see the page I justo put the IP of Photon in the address bar.
#include <PietteTech_DHT.h>
#define DHTTYPE DHT11
#define DHTPIN D6
PietteTech_DHT DHT(DHTPIN, DHTTYPE);
TCPServer server = TCPServer(80);
void setup() {
Serial.begin(9600);
server.begin();
}
void loop() {
TCPClient client = server.available();
if (client) {
float humidity = DHT.getHumidity();
float temperature = DHT.getCelsius();
String webpage = generateWebpage(DHT.getCelsius(), humidity);
client.print("HTTP/1.1 200 OK\r\n");
client.print("Content-Type: text/html\r\n");
client.print("Connection: close\r\n");
client.print("Content-Length: ");
client.print(webpage.length());
client.print("\r\n\r\n");
client.print(webpage);
delay(10);
client.stop();
}
int result = DHT.acquireAndWait(2000);
Serial.print("Humidade: ");
Serial.print(DHT.getHumidity());
Serial.print("%\t");
Serial.print("Temperatura: ");
Serial.print(DHT.getCelsius());
Serial.println("°C");
delay(2000); // Aguarda 2 segundos antes de ler novamente
}
String generateWebpage(float temperature, float humidity) {
String webpage = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=no'><title>Boletim meteorológico Particle Photon</title><style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;}p {font-size: 24px;color: #444444;margin-bottom: 10px;}</style><script>function atualizarDados() {var xhttp = new XMLHttpRequest();xhttp.onreadystatechange = function() {if (this.readyState == 4 && this.status == 200) {var dados = JSON.parse(this.responseText);document.getElementById('temperatura').innerHTML = 'Temperatura: ' + dados.temperatura + '°C';document.getElementById('umidade').innerHTML = 'Umidade: ' + dados.umidade + '%';}};xhttp.open('GET', '/dados', true);xhttp.send();}function piscarValores() {setInterval(function() {var temperatura = document.getElementById('temperatura');var umidade = document.getElementById('umidade');temperatura.style.visibility = (temperatura.style.visibility == 'visible') ? 'hidden' : 'visible';umidade.style.visibility = (umidade.style.visibility == 'visible') ? 'hidden' : 'visible';}, 1000);}setInterval(atualizarDados, 5000);window.onload = piscarValores;</script></head><body><div id='webpage'><h1>Boletim meteorológico Particle Photon</h1><p id='temperatura'>Temperatura: " + String(temperature) + "°C</p><p id='umidade'>Umidade: " + String(humidity) + "%</p></div></body></html>";
return webpage;
}