#include <WiFi.h>;
#include <HTTPClient.h>;
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define api "sal"
#define WIFI_CHANNEL 6
const int LED2 = 27;
// we need this library to serialize the data
//come from api in Json format
#include <ArduinoJson.h>;
void setup() {
Serial.begin(115200);
pinMode(LED2, OUTPUT);
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
while(WiFi.status() != WL_CONNECTED){
Serial.println("loading.");
Serial.println("loading..");
Serial.println("loading...");
delay(300);
}
Serial.println(".");
Serial.println("Wifi connected!");
Serial.println("IP Address: ");
// print board ip
IPAddress ipadress = WiFi.localIP();
Serial.println(ipadress);
//settinh the dns to use it in link instead of 192 ip
// access point: http://esp32.local
// here we do fetch the api by begin method
}
void loop() {
while(WiFi.status() == WL_CONNECTED){
HTTPClient client;
client.begin("https://zfive.000webhostapp.com/api/esp32");
// here we define the method wich return status code
int HttpCode = client.GET();
if(HttpCode > 0){
Serial.println(HttpCode);
}
if(HttpCode == 200){
//here we get the data from api
String Response = client.getString();
// Serial.println("The Data: " + Response);
Serial.println("\n" + Response);
char json[500];
// replace any space
// Response.replace(" ","");
Response.trim();
// u can remove specific charictir by using remove method
// Response.remove(0,1);
// convert to char array
Response.toCharArray(json , 500);
// Serial.println(json);
// here we create Json object contain data come from api
StaticJsonDocument<200> doc;
// by using this we can access data by giving the key
// to get a value
deserializeJson(doc , json);
// here we save data from doc by giving key to get a value
// const int item = doc["item"];
const bool status = doc["status"];
switch (status) {
case 0:
digitalWrite(LED2, LOW);
break;
case 1:
digitalWrite(LED2, HIGH);
break;
}
// Serial.println(item);
Serial.println(status);
}
if(HttpCode != 200){Serial.println("error fetching data...!");
client.end();
}
}
delay(10000);
}