Sabtu, 18 April 2020

Arduino IOT Mengambil data lewat API (COVID-19)

Halo Sobat Arduino, Barusan saya post di video tentang bagaimana cara mengambil data dari website penyedia API untuk sebaran pasien COVID-19 di Indonesia.

Kalau belum lihat videonya, berikut videonya






Oke bahan yang di butuhkan adalah sebagai berikut :
  • ESP8266 Modul IOT
  • OLED 1.3"
  • Kabel Jumper
  • Projectboard
Susun Seperti berikut ini




Dengan susunan pin sebagai berikut :
OLED -->  ESP8266
GND    --   GND
VCC    --    3V3
SCL     --    D1
SDA    --    D2

Untuk API nya bisa registrasi dahulu du web berikut

http://covid.vinteq.in/api/

Silahkan registrasi untuk mendapatkan AUTH nya

Library yang di perlukan adalah sebagai berikut :

  1. ESP8266WiFi (https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi)
  2. ESP8266HTTPClient (https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPClient)
  3. WiFiUdp (sama seperti library nomor 2)
  4. NTPClient(https://github.com/arduino-libraries/NTPClient)
  5. ArduinoJson(https://github.com/bblanchon/ArduinoJson)
  6. Adafruit_GFX(https://github.com/adafruit/Adafruit-GFX-Library)
  7. Adafruit_SSD130(https://github.com/adafruit/Adafruit_SSD1306
Untuk programnya adalah sebagai berikut :


/*
   Project Name: COVID-19 DASHBOARD
   Components Used: ESP32, OLED Display

   Author: Vinod Mandavkar
   Instagram: https://www.instagram.com/maker.vinod/
   Instructables: https://www.instructables.com/member/makervinod/
   Youtube: https://www.youtube.com/c/VinodMandavkar
   Modified : Sekolah Robot Indonesia
   YOutube : http://youtube.com/sekolahrobotindonesia
*/

//Use this if you are using ESP32
//#include <WiFi.h>
//#include <HTTPClient.h>

//Use this if you are using ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

#include "ArduinoJson.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 display(128, 64, &Wire); //Using the Adafruit Library

const char* ssid = "********";  //Di Isi SSID koneksi wifi
const char* password =  "sadapsadap";  //Di Isi Password wifi

// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");

//Week Days
String weekDays[7]={"Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"};

//Month names
String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

String currentDate;

void setup() {

  Serial.begin(115200);  //Starting Serial Communication
  WiFi.disconnect(true); //Disconecting the WiFi if we are previouly connected.

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64  |  You can change this to 0x3C if your display doesn't work
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); // Don't proceed, loop forever
  }

  //Intro Page - Change according to your needs
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(40, 0);
  display.println("DATA");
  display.setCursor(20, 20);
  display.println("SEBARAN");
  display.setTextSize(2);
  display.setCursor(5, 40);
  display.println("INDONESIA"); // display Country name
  display.display();
  delay(2000);

  WiFi.begin(ssid, password); // Connecting to the WiFi

  while (WiFi.status() != WL_CONNECTED) { //Wait till we are connected
    animate_oled_wifi();  // Animate it on the Screen
  }
  display.clearDisplay();
  display.display(); //update the display


  Serial.println("Connected to the WiFi network");
  // Initialize a NTPClient to get time
  timeClient.begin();
  // Set offset time in seconds to adjust for your timezone, for example:
  // GMT +1 = 3600
  // GMT +8 = 28800
  // GMT -1 = -3600
  // GMT 0 = 0
  timeClient.setTimeOffset(0);
}

//This is what we do repeatedly !!
void loop()
{
 
  JsonObject root;
  String ACTIVE_CASES = "", TOTAL_CASES = "", RECOVERED_CASES = "", DEATHS = "", HISTORY = ""; //some data storage strings

  if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
    HTTPClient http;
    http.begin("http://covid.vinteq.in/api/get_data/?country=Indonesia"); //Specify the URL - You can change th country name as per your need to get the country specific data
    http.addHeader("auth-key", "authnya dimasukkin sini");   //Insert your Auth-key here in quotes (as String)
    int httpCode = http.GET();                       //Make the request

    if (httpCode > 0) { //Check for the returning code

      String payload = http.getString();
      // Serial.println(payload);   //Print the Payload received

      DynamicJsonDocument doc(2 * payload.length());  //Flexible size

      // Parse JSON object
      DeserializationError error = deserializeJson(doc, payload);
      if (error)
      {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.c_str());
        return;
      }
      root = doc.as<JsonObject>(); //Mapping the data to Json Object
    }
    http.end(); //Free the resources
  }

  //  Handle the Data
  for (JsonPair kv : root) {
    if (String(kv.key().c_str()) == "history")
    {
      HISTORY = kv.value().as<String>();
    }
  }

  //Removing Brackets
  HISTORY = HISTORY.substring(0, HISTORY.length() - 1);
  HISTORY = HISTORY.substring(1);
  //  Serial.println(HISTORY);

  //We need the latest data - the first one
  String DATA = HISTORY.substring(0, HISTORY.indexOf('}') + 1);
  //    Serial.println(DATA);

  DynamicJsonDocument sub_doc(DATA.length() * 2);
  DeserializationError error = deserializeJson(sub_doc, DATA); //Converting the Extracted Nested Data from String to Json
  root = sub_doc.as<JsonObject>();
  for (JsonPair kv : root)
  {
    //Finding specific keys and extracting their values in varibales
    if (String(kv.key().c_str()) == "active_cases")
    {
      ACTIVE_CASES = kv.value().as<String>() ;
    }
    if (String(kv.key().c_str()) == "recovered_cases")
    {
      RECOVERED_CASES = kv.value().as<String>() ;
    }
    if (String(kv.key().c_str()) == "total_cases")
    {
      TOTAL_CASES = kv.value().as<String>() ;
    }
    if (String(kv.key().c_str()) == "deaths")
    {
      DEATHS = kv.value().as<String>();
    }
  }
  getdate();
  /*
     This is the display rountine
     What it does:
     Shows the above extracted data on the OLED Display
     Loops again as we need ot to display the same data for 1 minute before new data is fetched (You can change it according to your need)
     dealy of 5 seconds x 4 display values = 20 seconds per loop  - Repeating for 3 Times = 60 Seconds ~ 1 Minute
  */
  for (byte i = 0; i < 3; i++)
  {
    display.clearDisplay();
    display.setTextSize(2);
    display.setCursor(8, 0);
    display.println("INDONESIA");
    display.setCursor(15, 25);
    display.setTextSize(2);
    display.println("COVID-19");
    display.setCursor(30, 50);
    display.setTextSize(1);
    display.println(currentDate);
    display.display();
    delay(5000);
    //    Serial.println(ACTIVE_CASES);
//    display.clearDisplay();
//    display.setTextSize(2);
//    display.setCursor(0, 0);
//    display.println("ACTIVE:");
//    display.setCursor(0, 30);
//    display.setTextSize(3);
//    display.println(ACTIVE_CASES);
//    display.display();
//    delay(5000);
    //    Serial.println(RECOVERED_CASES);
    display.clearDisplay();
    display.setTextSize(2);
    display.setCursor(0, 0);
    display.println("SEMBUH:");
    display.setCursor(0, 30);
    display.setTextSize(3);
    display.println(RECOVERED_CASES);
    display.display();
    delay(5000);
    //    Serial.println(DEATHS);
    display.clearDisplay();
    display.setTextSize(2);
    display.setCursor(0, 0);
    display.println("MENINGGAL:");
    display.setCursor(0, 30);
    display.setTextSize(3);
    display.println(DEATHS);
    display.display();
    delay(5000);
    //    Serial.println(TOTAL_CASES);
    display.clearDisplay();
    display.setTextSize(2);
    display.setCursor(0, 0);
    display.println("POSITIF:");
    display.setCursor(0, 30);
    display.setTextSize(3);
    display.println(TOTAL_CASES);
    display.display();
    delay(5000);
  }
}

//WiFi Connection Animation
void animate_oled_wifi()
{
  display.clearDisplay();
  display.setCursor(0, 20);
  display.println("Connecting");
  display.println("to WiFi...");
  display.setCursor(10, 0);
  display.println("   {-}   ");
  display.display();
  delay(500);
  display.clearDisplay();
  display.setCursor(0, 20);
  display.println("Connecting");
  display.println("to WiFi...");
  display.setCursor(10, 0);
  display.println("  { - }  ");
  display.display();
  delay(500);
  display.clearDisplay();
  display.setCursor(0, 20);
  display.println("Connecting");
  display.println("to WiFi...");
  display.setCursor(10, 0);
  display.println(" {  -  } ");
  display.display();
  delay(500);
  display.clearDisplay();
  display.setCursor(0, 20);
  display.println("Connecting");
  display.println("to WiFi...");
  display.setCursor(10, 0);
  display.println("{   -   }");
  display.display();
  delay(500);
}

void getdate()
{
  timeClient.update();

  unsigned long epochTime = timeClient.getEpochTime();
  Serial.print("Epoch Time: ");
  Serial.println(epochTime);
 
  String formattedTime = timeClient.getFormattedTime();
  Serial.print("Formatted Time: ");
  Serial.println(formattedTime);

  int currentHour = timeClient.getHours();
  Serial.print("Hour: ");
  Serial.println(currentHour);

  int currentMinute = timeClient.getMinutes();
  Serial.print("Minutes: ");
  Serial.println(currentMinute);
 
  int currentSecond = timeClient.getSeconds();
  Serial.print("Seconds: ");
  Serial.println(currentSecond);

  String weekDay = weekDays[timeClient.getDay()];
  Serial.print("Week Day: ");
  Serial.println(weekDay);  

  //Get a time structure
  struct tm *ptm = gmtime ((time_t *)&epochTime);

  int monthDay = ptm->tm_mday;
  Serial.print("Month day: ");
  Serial.println(monthDay);

  int currentMonth = ptm->tm_mon+1;
  Serial.print("Month: ");
  Serial.println(currentMonth);

  String currentMonthName = months[currentMonth-1];
  Serial.print("Month name: ");
  Serial.println(currentMonthName);

  int currentYear = ptm->tm_year+1900;
  Serial.print("Year: ");
  Serial.println(currentYear);

  //Print complete date:
  currentDate = String(monthDay) + "/" + String(currentMonth) + "/" + String(currentYear);
  Serial.print("Current date: ");
  Serial.println(currentDate);

  Serial.println("");
}
Data berhasil di ambil, selamat belajar arduino

1 komentar:

  1. Like the colours, the numbers are blended up as much as potential, but look nearer and you'll find some patterns that guarantee each odd/even numbers and high/low numbers are evenly distributed. Another Roulette recreation technique highlights betting high when you win, and betting low when you lose. Regardless, for the next three years, Magic City will be the solely on line casino allowed to supply 메리트카지노 the game inMiami-Dade County.

    BalasHapus