#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
#include <OneWire.h>
#include <DallasTemperature.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "http://esp32-book-2023.000webhostapp.com/esp-get-data.php";
const int oneWireBus = 4;
// Keep this API Key value to be compatible with the PHP code provided in the project page.
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key
String apiKeyValue = "kjsjkhjdhfd";
String sensorName = "temperature";
String sensorLocation = "home";
int sensorPin = A0;
int sensorValue = 0;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
void setup() {
pinMode(16, OUTPUT);
pinMode(2, OUTPUT);
digitalWrite(16, HIGH);
Serial.begin(115200);
// Start the DS18B20 sensor
sensors.begin();
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
digitalWrite(2, LOW);
delay(250);
Serial.print(".");
digitalWrite(2, HIGH);
delay(250);
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
digitalWrite(16, LOW);
HTTPClient http;
sensors.requestTemperatures();
float temperatureC = sensors.getTempCByIndex(0);
// Your Domain name with URL path or IP address with path
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
+ "&location=" + sensorLocation + "&value1=" +temperatureC
+ "&value2=5678"+"";
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
String payload = http.getString();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println(payload);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
//Send an HTTP POST request every 60 seconds
delay(3000);
}
else {
Serial.println("WiFi Disconnected");
digitalWrite(2, LOW);
delay(250);
Serial.print(".");
digitalWrite(2, HIGH);
delay(250);
}
}