ESP8266 Projects

A news ticker with API Call, JSON and an ESP32

Newsticker with an ESP32

You want to read the latest headlines directly in your Serial Monitor? Then it’s time for your own news ticker!

In this project you connect your ESP32 to the internet, retrieve the latest news via an API call, parse JSON data and display the headlines in your Serial Monitor.

In this project, we are initially concentrating on the software. As soon as your news ticker works, you can add a display to show the news there.

Note: For this project you need an ESP32. A board from the Arduino or ESP8266 family probably has too little memory for the news ticker. If you haven’t used this controller before, follow this tutorial – here you will learn how to prepare your Arduino IDE.

The code for your news ticker

First of all you need three libraries, which you load as usual in your sketch right at the beginning:

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

The first two libraries should be pre-installed in your Arduino IDE. If not, you can add them under Tools -> Manage Libraries.

You can find the library ArduinoJson.h from the developer Benoit Blanchon in your Library Manager by simply searching for “ArduinoJson” and installing it.

Library ArduinoJson.h

Before you can start, enter your Wi-Fi access data into the sketch:

const char* ssid = "Name deines WLAN-Netzwerks";
const char* password =  "Dein WLAN-Passwort";

The setup function

In the void setup() function, you use code to connect your ESP32 to the Internet:

void setup() {
 
  Serial.begin(115200);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Ich verbinde mich mit dem Netzwerk...");
  }
 
  Serial.println("Ich bin mit dem Netzwerk verbunden!");
}

Here you start your Serial Monitor and call the function WiFi.begin(), which connects you to your Wi-Fi network using your credentials. As soon as the connection is established, your controller will inform you about this in the Serial Monitor.

Retrieve, process and output the news

Now it will be exciting! In the void loop() function, you call a function every 10 seconds that retrieves the current headlines from an API as JSON, processes them and outputs them to your Serial Monitor:

void loop() {
  apiCall();
  delay(10000);
}

Of course you can also write the content of the function apiCall()directly in your loop. For more clarity, however, it is created independently in this project.

Connect to the Internet and retrieve the JSON data via API call

So let’s look at this function step by step.

void apiCall(){

  if ((WiFi.status() == WL_CONNECTED)) {

You define the function yourself, of course. Then you start with an If Statement to find out whether your ESP32 is actually connected to your Wi-Fi network. If this is the case, the process continues.

HTTPClient http;
 
http.begin("https://newsapi.org/v2/top-headlines?country=de&apiKey=API_KEY");

First you create an instance of HTTPClient with the name http. In the following code you use this name as prefix for all functions you use.

Da wäre als erstes http.begin(). Als Parameter gibst du dieser Funktion die URL zur API mit, von der du die News abrufen möchtest. Und an dieser Stelle müssen wir einen kurzen Abstecher machen.

Beim Anbieter News API kannst du dich als Privatperson kostenlos registrieren, um dort aktuelle Schlagzeilen aus aller Welt abzurufen.

Website News API

Registration is quick and uncomplicated. You will then get your own API key that you need to retrieve the messages.

Important:On newsapi.org you can find your API Key by clicking on your email address in the upper right corner. You have to add this key to the URL in line 14 of the sketch by replacing API_KEY with your key:


https://newsapi.org/v2/top-headlines?country=de&apiKey=API_KEY


Be careful not to overwrite other characters when inserting your key. Without an API key or with an incorrect URL the request will not work.

Then click on the menu itemGet started and then on Top headlines in the left menu. On the tiles you see now, you can find several examples of API requests:

API Calls Examples

Next to the green label GET you already see the ready URL for the function http.begin() in your sketch. Practical: Your API key is already integrated.

Click through the offer of the service and try out different URLs! In the code above there is a URL for the top headlines from German media, but you can swap them as you like. For example, you can retrieve pure business news or just headlines for a specific search term.

But back to the code: To execute the API call you first need the function http.GET(). This function returns a status code which you store in a variable. And here we go on:

int httpCode = http.GET();

if (httpCode == 200) {
    Serial.println(httpCode);

If you get a valid response from the News API server, the status is code 200, only then the sketch can continue. You can learn more about status codes on Wikipedia.

If the request is successful (i.e. with status 200), you will receive JSON data containing the news and other metadata. You can find out what this data looks like in its raw form by calling the URL from your code in a browser. 🙂

Of course, you can’t do much with it at first, because reading the news like this is no fun. So you have to process – or parse – this JSON data. What does all this mean? Wikipedia also helps you with JSON and parsing.

First you store the raw data in a variable of type string to process it afterwards:

String payload = http.getString();

Parsing the JSON data

Now things are getting serious – and a bit tricky, too. In order not to make it too complicated, simple explanations should be sufficient for the time being. In the documentation of the ArduinoJson library you can find out all the details, if you like.

So in all brevity: In order for your ESP32 to be able to process the data, we first have to calculate the amount of memory required. The easiest way to do this is to use the official Arduino Assistant.

To do this, call up the URL you entered in the sketch above in a browser. Then select all the text, copy it and paste it into the left field Input. In the field Parsing program below you will find the line of code you need for your sketch:

Memory requirements ArduinoJson

In this project this is:

const size_t capacity = JSON_ARRAY_SIZE(20) + 20*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + 20*JSON_OBJECT_SIZE(8) + 19020;

This is followed by some functions and requests to process the JSON data and stop this processing if an error occurs:

DynamicJsonDocument doc(capacity);

DeserializationError error = deserializeJson(doc, payload);
        
if (error) {
   Serial.print(F("deserializeJson() hat nicht funktioniert: "));
   Serial.println(error.c_str());
   return;
   }

Now you are almost there! In the background your sketch has already structured the JSON data and assigned the different contents to several constants (const). You only have to pick out the raisins.

In this project this is the title of the latest news. First you select the array articles from the raw data. From this again the first, i.e. newest article articles[0] and from this again the title [“title”]. Finally, you display this title, i.e. your headline, in the Serial Monitor:

JsonArray articles = doc["articles"];

JsonObject articles_0 = articles[0];

const char* articles_0_title = articles_0["title"];

Serial.println(articles_0_title);
}

What’s missing now is an else{} for a status code not equal to 200 – you remember this request above? And a function to end the API call again:

else {
  Serial.println("Fehlerhafter HTTP-Request");
  }
 
http.end(); //Free the resources
}
}

That’s it! Your Serial Monitor should now display the latest headline from the news source you defined via URL every 10 seconds. Here is the complete sketch:

#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>

// WLAN-Daten
const char* ssid = "WLAN-NETZWERK";
const char* password =  "PASSWORT";

void apiCall(){
  if ((WiFi.status() == WL_CONNECTED)) {
 
    HTTPClient http;
 
    http.begin("https://newsapi.org/v2/top-headlines?country=de&apiKey=API_KEY");
    
    int httpCode = http.GET();
 
    if (httpCode == 200) {

        Serial.println(httpCode);
 
        String payload = http.getString();
        
        const size_t capacity = JSON_ARRAY_SIZE(20) + 20*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + 20*JSON_OBJECT_SIZE(8) + 19020;
        
        DynamicJsonDocument doc(capacity);

        DeserializationError error = deserializeJson(doc, payload);
        
        if (error) {
           Serial.print(F("deserializeJson() hat nicht funktioniert: "));
           Serial.println(error.c_str());
           return;
           }

        JsonArray articles = doc["articles"];

        JsonObject articles_0 = articles[0];

        const char* articles_0_title = articles_0["title"];

        Serial.println(articles_0_title);
        }
 
        else {
          Serial.println("Fehlerhafter HTTP-Request");
          }
 
        http.end();
        }
  }

void setup() {
 
  Serial.begin(115200);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Ich verbinde mich mit dem Netzwerk...");
  }
 
  Serial.println("Ich bin mit dem Netzwerk verbunden!");
}
 
void loop() {
  apiCall();
  delay(10000);
}

Not working?

If no messages appear in your Serial Monitor, please check the following error sources:

  • Did you enter your Wi-Fi data in lines 6 and 7?
  • Did you enter your API key from newsapi.org in the URL in line 14?
  • Are all used libraries up to date?

What’s next?

Make your new news ticker smart and create a sound sensor to retrieve the news whenever you clap your hands. Learn here how to use a sound sensor on your Arduino (or ESP32).

Of course you can also install a display and display the headlines on it so you don’t have to rely on your Serial Monitor. Surely you can think of many more optimizations! 🙂

You may also like

Comments are closed.