Title here
Summary here
To fetch data from a 3rd party endpoint over HTTP, we recommend the HTTPClient
library that comes automatically bundled with Arduino.
Include this header in your main.cpp
file:
#include <HTTPClient.h>
To parse JSON we will use the ArduinoJSON
library. Include this header in your main.cpp
file:
#include <ArduinoJSON.h>
We will fetch data from the following endpoint, https://www.boredapi.com/api/activity, which returns:
{
"activity":"Make bread from scratch",
"type":"cooking",
"participants":1,
"price":0.2,
"link":"",
"key":"4809815",
"accessibility":0.2
}
Our goal is to take the value of activity
every 10 minutes and display it on kublet.
Your code should look like this:
#include <Arduino.h>
#include <otaserver.h>
#include <kgfx.h>
#include <HTTPClient.h>
#include <ArduinoJSON.h>
#include <TFT_eSPI.h>
OTAServer otaserver;
KGFX ui;
Preferences preferences;
JsonDocument doc;
const char *endpoint = "https://www.boredapi.com/api/activity";
unsigned long lastTime = 0;
unsigned long timerDelay = 600000;
TFT_eSprite textSpr = ui.createSprite(240, 150);
void setup() {
Serial.begin(460800);
Serial.println("Starting app");
otaserver.connectWiFi(); // DO NOT EDIT.
otaserver.run(); // DO NOT EDIT
ui.init();
ui.clear();
}
void loop() {
if((WiFi.status() == WL_CONNECTED)) {
otaserver.handle(); // DO NOT EDIT
if (((millis() - lastTime) > timerDelay) || lastTime == (unsigned long)(0)) {
HTTPClient http;
http.begin(endpoint);
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
deserializeJson(doc, payload);
const char* activity = doc["activity"];
ui.drawText(textSpr, activity, Arial_24, TFT_YELLOW, 0, 0);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
lastTime = millis();
}
}
delay(1);
}
There may be cases where the size of the response payload is too large. To manage this, use a HTTP stream instead. We recommend the following library:
lib_deps =
squix78/JsonStreamingParser@^1.0.5