#include "DHTesp32.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String payload;
const char* server = "http://api.thingspeak.com/update?";
String myApikey = "RF2I2DP1SBD6GP5U";
const int DHT_PIN = 23;
float temperature;
float humidity;
DHTesp capteur;
void setup() {
Serial.begin(115200);
capteur.setup(DHT_PIN, DHTesp::DHT22);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("OK! IP=");
Serial.println(WiFi.localIP());
Serial.print("Fetching ");
Serial.println(server);
}
void loop() {
WiFiClient client;
HTTPClient http;
String jsonfile;
temperature = capteur.getTempAndHumidity().temperature;
humidity = capteur.getTempAndHumidity().humidity;
Serial.print("temperature=");
Serial.println(temperature);
Serial.print("humidity=");
Serial.println(humidity);
//
DynamicJsonDocument doc(128);
doc["api_key"] = myApikey;
doc["field1"] = String(temperature);
doc["field2"] = String(humidity);
serializeJson(doc, jsonfile);
Serial.println(jsonfile);
Serial.print("[HTTP] begin...\n");
http.begin(client, server); // HTTP
Serial.print("[HTTP] POST...\n");
//http.addHeader("Accept", "application/json");
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(jsonfile);
// httpCode will be negative on error
if (httpResponseCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] POST... code: %d\n", httpResponseCode);
// file found at server
if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_MOVED_PERMANENTLY) {
//String payload = http.getString();
// Serial.println(payload);
}
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpResponseCode).c_str());
}
http.end();
delay(10000);
}