#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* url = "https://api.openweathermap.org/data/2.5/weather?q=Tozeur&appid=904f05c2f80aff859fbacf58e5c2fabc";
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define DHTPIN 13 // Broche de signal du capteur DHT
#define DHTTYPE DHT22 // Type de capteur DHT
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
WiFiClient client;
int t_dht;
int h_dht;
int temperature_api ;
int temperature_API ;
int humidity_API;
int fahrenheitToCelsius(int fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
int calculMOY(int a,int b){
return((a+b)/2);
}
void setup() {
Serial.begin(115200); // Démarre la communication série
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("CONNECTED");
lcd.init();
lcd.backlight();
}
void loop() {
t_dht = dht.readTemperature();
h_dht = dht.readHumidity();
if (isnan(h_dht) || isnan(t_dht))
{
Serial.println("ERROR !!! ");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("ERROR !!! ");
delay(2000);
}
else
{
getWeatherData();
lcd.setCursor(0, 0);
lcd.print("t:" + String(t_dht) + "C");
lcd.setCursor(0, 1);
lcd.print("h:" + String(h_dht) + "%");
Serial.print("Température DHT:");
Serial.print(t_dht);
Serial.println("C"); // Use println to print on a new line
Serial.print("Humidity DHT: ");
Serial.print(h_dht);
Serial.println("%"); // Use println to print on a new line
}
double Moyenne_temp=calculMOY(t_dht,temperature_API);
double Moyenne_hum=calculMOY(h_dht,humidity_API);
Serial.print("Moyenne temperature: ");
Serial.println(Moyenne_temp);
Serial.print("Moyenne humidity: ");
Serial.println(Moyenne_hum);
}
void getWeatherData(){
HTTPClient http;
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
// Parse the JSON response
DynamicJsonDocument jsonDoc(1024); // Adjust the size according to your JSON response
DeserializationError error = deserializeJson(jsonDoc, payload);
if (error) {
Serial.print("JSON parsing failed: ");
Serial.println(error.c_str());
}
else {
// Extract weather information from JSON
JsonObject main = jsonDoc["main"];
temperature_api = main["temp"];
humidity_API = main["humidity"];
temperature_API=fahrenheitToCelsius(temperature_api);
Serial.print("Temperature_API: ");
Serial.print(temperature_API);
Serial.println("°C");
Serial.print("Humidity_API :");
Serial.print(humidity_API);
Serial.println("%"); // Use println to print on a new line
lcd.setCursor(8, 0);
lcd.print("T:"+ String(temperature_API) +"C");
lcd.setCursor(8, 1);
lcd.print("H:" + String(humidity_API) + "%");
}
}
else {
Serial.print("HTTP request failed with error code: ");
Serial.println(httpCode);
}
http.end();
}
}