/*
ESP32 HTTPClient Facts API Example
https://wokwi.com/projects/342032431249883731
Copyright (C) 2022, Uri Shaked
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define BTN_PIN 5
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
const String apiKey = ""; // Enter your API Key here.
const String url = "https://api.api-ninjas.com/v1/facts?X-Api-Key=";
String getFact() {
HTTPClient http;
http.useHTTP10(true);
http.begin(url+apiKey);
http.GET();
String result = http.getString();
result.remove(0, 1); result.remove(result.length() - 1);
DynamicJsonDocument doc(2048);
DeserializationError error = deserializeJson(doc, result);
// Test if parsing succeeds.
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return error.c_str();
}
http.end();
return doc["fact"].as<String>();
}
void nextFact() {
tft.setTextColor(ILI9341_WHITE);
tft.println("\nLoading new fact...");
String fact = getFact();
tft.setTextColor(ILI9341_GREEN);
tft.println(fact);
}
void setup() {
pinMode(BTN_PIN, INPUT_PULLUP);
WiFi.begin(ssid, password, 6);
tft.begin();
tft.setRotation(1);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
tft.print(".");
}
tft.print("\nOK! IP=");
tft.println(WiFi.localIP());
nextFact();
}
void loop() {
if (digitalRead(BTN_PIN) == LOW) {
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(0, 0);
nextFact();
}
delay(10);
}