I have tried to send all the variables to both the webpage and to myphpadmin. I seperated the code into two functions and put the functions inside the void loop() function under the impression that it will loop both but it seems if I put both then the device will only send data to phpmyadmin. However, if I delete void logs() which is the function that sends data to phpmyadmin then the void page() which sends the data to the webpage starts working. I can't find a solution for these two functions to work together, I really don't understand what I'm doing wrong, your guidance would be much appreciated
this is my code:
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = R"=====(
<!DOCTYPE html>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<meta charset='utf-8'>
<style>
body {font-size:100%;}
#main {display: table; margin: auto; padding: 10px 10px 10px 10px; }
#content { border: 5px solid blue; border-radius: 15px; padding: 10px 0px 10px 0px;}
h2 {text-align:center; margin: 10px 0px 10px 0px;}
p { text-align:center; margin: 5px 0px 10px 0px; font-size: 120%;}
#time_P { margin: 10px 0px 15px 0px;}
</style>
<script>
function updateTime()
{
var d = new Date();
var t = "";
t = d.toLocaleTimeString();
document.getElementById('P_time').innerHTML = t;
}
function updateTemp()
{
ajaxLoad('getTemp');
}
var ajaxRequest = null;
if (window.XMLHttpRequest) {
ajaxRequest =new XMLHttpRequest();
}
else {
ajaxRequest =new ActiveXObject("Microsoft.XMLHTTP");
}
function ajaxLoad(ajaxURL)
{
if(!ajaxRequest){ alert('AJAX is not supported.'); return; }
ajaxRequest.open('GET',ajaxURL,true);
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200)
{
var ajaxResult = ajaxRequest.responseText;
var tmpArray = ajaxResult.split("|");
document.getElementById('Temperature').innerHTML = tmpArray[0];
document.getElementById('Humidity').innerHTML = tmpArray[1];
document.getElementById('Pressure').innerHTML = tmpArray[2];
document.getElementById('Altitude').innerHTML = tmpArray[3];
}
}
ajaxRequest.send();
}
var myVar1 = setInterval(updateTemp, 1000);
var myVar2 = setInterval(updateTime, 1000);
</script>
<title>Temperature & Humidy Monitor</title>
</head>
<body>
<div id='main'>
<h2>Temperature & Humidity Monitor</h2>
<div id='content'>
<p id='P_time'>Time</p>
<h2>Temperature</h2>
<p> <span id='Temperature'>--</span> ℃ </p>
<h2>Humidity</h2>
<p> <span id='Humidity'>--</span> % </p>
<h2>Pressure</h2>
<p> <span id='Pressure'>--</span> hPs </p>
<h2>Altitude</h2>
<p> <span id='Altitude'>--</span> m </p>
</div>
</div>
</body>
</html>
)=====";
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
#include <Wire.h>
#include "HTTPSRedirect.h"
#include "DebugMacros.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#define SEALEVELPRESSURE_HPA (1013.25)
#define DHTPIN 2 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 11
Adafruit_BME280 bme;
const char* ssid = "fl"; // Enter SSID (WiFi Name) here
const char* password = "99110233"; //Enter Password here
const char* serverName = "http://192.168.101.17/sensordata/post-esp-data.php";
ESP8266WebServer server(80);
String apiKeyValue = "tPmAT5Ab3nnn9";
String sensorName = "BME280";
String sensorLocation = "Office";
float Temperature;
float Humidity;
float Pressure;
float Altitude;
String request = "";
int pin = 2;
void setup() {
// initialize GPIO 2 as an output.
pinMode(pin, OUTPUT);
Serial.begin(115200);
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
Serial.println("Connecting to ");
Serial.println(ssid);
//connect to your local wi-fi network
WiFi.begin(ssid, password);
//check wi-fi is connected to wi-fi network
while (WiFi.status() != WL_CONNECTED) {
delay(10);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: "); Serial.println(WiFi.localIP());
server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
page();
logs();
}
void page(){
//sends data to webpage
server.handleClient();
WiFiClient client = server.client(); // Check if a client has connected
if (!client) { return; }
request = client.readStringUntil('\r'); // Read the first line of the request
Serial.println(request);
Serial.println("");
if ( request.indexOf("getTemp") > 0 )
{
Serial.println("getTemp received");
// Reading temperature or humidity takes about 250 milliseconds!
Temperature = bme.readTemperature();
Pressure = bme.readPressure() / 100.0F;
Altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
Humidity = bme.readHumidity(); // Read temperature as Fahrenheit (isFahrenheit = true)
if ( !isnan(Temperature) && !isnan(Humidity) && !isnan(Pressure) && !isnan(Altitude) )
{
client.print( header );
client.print( Temperature ); client.print( "|" );
client.print( Humidity ); client.print( "|" );
client.print( Pressure ); client.print( "|" );
client.print( Altitude ); client.print( "|" );
Serial.println("data sent");
}
else
{
Serial.println("Error reading the sensor");
}
}
else
{
client.flush();
client.print( header );
client.print( html_1 );
Serial.println("New page served");
}
delay(5);
if (Temperature > 20.0){
digitalWrite(pin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(pin, LOW); // turn the LED off by making the voltage LOW
delay(1);
}
}
void logs(){
//sending to database
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
// Takes Domain name with URL path or IP address with path
http.begin(serverName);
// Specifies content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Prepare HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
+ "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())
+ "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);
//String httpRequestData = "api_key=tPmAT5Ab3nnn9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
//Send an HTTP POST request every 30 seconds
delay(30000);
}
void handle_OnConnect(){
Temperature = bme.readTemperature();
Pressure = bme.readPressure() / 100.0F;
Altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
Humidity = bme.readHumidity();
}
void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}