ESP8266 Projects

Remind yourself of your umbrella with an ESP8266

Reminder of the umbrella

Have you ever left your apartment and then stood on the street in the rain? With this project you will make sure that this does not happen again.

With an ESP8266, you retrieve the current weather situation via an API and show on an OLED display whether it is raining, snowing or the sun is shining. If you need an umbrella outside, the display and an LED will remind you to take it with you.

And by the way: to prevent your ESP8266 from spending the whole day on the internet and constantly retrieving weather data, you can also integrate a radar module. So you can place your project on your front door, for example, and only activate it when you approach it. So you will be reminded at exactly the right time. ­čÖé

Beginner

1 – 2 hours

approx. $15

For this project you need (quantities see description):

The set up

The finished project should look something like this:

First, place your ESP8266 on your breadboard. I recommend a NodeMCU Lua Amica for this, because it is narrow enough that you can still plug in cables at the pinouts. The newer version called Lolin is at a disadvantage and therefore not suitable for projects on breadboards. Afterwards you connect your microcontroller with this 3 parts:

OLED Display

In this project you use a small OLD display with I┬▓C connector. Place your display on the breadbaord and connect it first to one of the GND pins and a 3.3V output on the microcontroller. Then connect the display pin SCL to D1 and the pin SDA to D2. With the two pins D1 and D2 you can communicate with your display via I┬▓C.

Radar Module RCWL-0516

This sensor is a perfect motion sensor with a range of 5 to 7 meters. The great thing about this module is that it can even detect movement through an obstacle (for example a box).

The connection is very easy: Besides the usual connection of GND and 3.3V, you connect pin OUT to pin D7 on your ESP8266.

The LED

Now for the very easiest exercise, the LED. Connect the anode (long leg) to pin D6 and the cathode (short leg) to ground. Do not forget to connect a resistor between them!

The code for your project

It gets a bit more complex now, because first you have to register for a -free- API, from which you can retrieve the current weather situation at your location (or any other place on earth).

First register at https://openweathermap.org. For an account you only need a username, an email address and a password. In your personal area you have the possibility to create an API key under the menu item API keys. You will need this key later in your Arduino sketch to request the weather data. Once you have done this, you can continue with the code.

The required libraries

For this project you need 6 libraries. If you haven’t installed them in your Arduino IDE yet, it’s best to do so now. Click on the menu item Tools and then on Manage libraries. The Library Manager will open and you can search for the libraries you need. Always install the latest version.

When you are done with it, you include it before the void setup()function at the beginning of your sketch:

#include <Wire.h> //I2C-Verbindung
#include <Adafruit_GFX.h> //OLED-Display
#include <Adafruit_SSD1306.h> //OLED-Display

#include <ESP8266WiFi.h> //WiFI
#include <ArduinoJson.h> //JSON
#include <ESP8266HTTPClient.h> //API-Abfrage

Internet access data and OLED display

To enable your ESP8266 to connect to the Internet, you must enter your credentials. Right after this, you will find some code for communicating with your display:

// WIFI-Zugangsdaten
const char* ssid = "Dein Netzwerkname";
const char* password =  "Dein Passwort";


//OLED-Display
#define SCREEN_WIDTH 128 // Breite des Displays in Pixeln
#define SCREEN_HEIGHT 64 // H├Âhe des Displays in Pixeln

//Angaben zum OLED-Display und der Kommunikation per I2C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

Icons for all (important) weather conditions

Later on your display should show icons that symbolize the current weather: Clear sky, clouds, snow, fog – and an umbrella for rain and thunderstorms. The declarations of these icons in the code are very long. Therefore you won’t find them here, but in the whole Arduino sketch below.

The setup function

In the void setup() function you define the two pins for the LED and the radar sensor, prepare the connection to the serial monitor, specify the address of your display and set the font size and color. ­čÖé

void setup() {

  pinMode (12, OUTPUT); //LED Pin (am ESP8266 D6)
  pinMode (13, INPUT); //Radar Pin (am ESP8266 D7)

  Serial.begin(115200); //Verbindung zum Seriellen Monitor

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Display-Addresse: 0x3C
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }

  display.setTextSize(1); //Schriftgr├Â├če
  display.setTextColor(WHITE); //Schriftfarbe
}

The Loop

In the void loop() function your radar module works. Every 100 milliseconds it checks if something is moving nearby. If so, your ESP8266 will connect to the internet and request the weather data from Openweather. As long as this is not the case, the loop continues to run and the OLED display remains dark.

void loop() {

  delay(100); //100 Millisekunden warten

  if (digitalRead(13) == 1) { //Sobald das Radar eine Bewegung registriert, startet die Internet-Verbindung
    WiFi.begin(ssid, password); //Internet-Verbindung starten

    while (WiFi.status() != WL_CONNECTED) { //Statusnachricht "Verbindung herstellen" solange nicht verbunden
      delay(1000);
      display.clearDisplay();
      display.setCursor(0, 10);
      display.println("Connecting to WiFi...");
      display.display();

    }

    delay(1000);
    display.clearDisplay();
    display.setCursor(0, 10);
    display.println("Hello, world!"); //Ausgabe, sobald die Verbindung zum Internet steht
    display.display();

    apiCall(); //Aufruf der Funktion f├╝r Abruf und Ausgabe der Wetterdaten
    
  } else {
    WiFi.disconnect(); //Wenn keine Bewegung registriert wird Internet-Verbindung beenden...
    digitalWrite(12, LOW); //...und die LED ausschalten
  }
}

The function apiCall()

This function is the heart of your code! This is where you request the API (a so-called API call), process the data coming into your ESP8266 and, depending on the weather, show a corresponding icon on your display. In addition, you can display the current temperature and let the LED light up when it rains.

This code is not very simple. Therefore we will look at it step by step:

First of all you define the function itself and write an If Statement, within which all the following code will be executed. With this request you make sure that it will only be executed when you are connected to the internet. Because without internet there is no weather data. ­čÖé

void apiCall() {

  if ((WiFi.status() == WL_CONNECTED)) { //Netzwerkstatus checken

Retrieve and process weather data

Next you create an instance of the HTTPClient class called http. After that comes the request at Openweather. For this you use a URL, in which the type of request (current weather) and the desired location are defined. At the end of the URL is your API key, which you created at the beginning. For more information please refer to the documentation of Openweather.


    HTTPClient http; //Instanz von HTTPClient starten

    http.begin("http://api.openweathermap.org/data/2.5/weather?q=Berlin,de&units=metric&appid=DEIN API KEY"); //URL f├╝r die Abfrage

    int httpCode = http.GET(); //Antwort des Servers abrufen
    Serial.println(httpCode); //Antwort im Seriellen Monitor ausgeben

Now follows a check if the request worked. In this case you will get the answer 200 from the server, so you write an If Statement, which will execute all following code only if the server answer is positive and you got the requested data.

Then you store this data in the variable payload and process it with the library ArduinoJson. To explain how this works exactly would go beyond the scope of this article. You can find further explanations in the project A news ticker via API Call & JSON and on the website of the developer of this library.

    if (httpCode == 200) { //Die Antwort des Servers checken

      String payload = http.getString(); //Daten in eine Variable speichern

      const size_t capacity = JSON_ARRAY_SIZE(1) + 2 * JSON_OBJECT_SIZE(1) + 2 * JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(14) + 290;
      
      DynamicJsonDocument doc(capacity); //Gr├Â├če des Speichers zur JSON-Verarbeitung festlegen

      DeserializationError error = deserializeJson(doc, payload); //JSON parsen

      http.end(); //Die Verbindung zum Server beenden

      if (error) { //Fehlermeldung bei fehlerhafter Verarbeitung
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.c_str());
        return;
      }

The variable payload now contains the weather data in JSON format. You can see how they look like if you call the URL to request from your sketch in your browser. Here is an example for Berlin in the evening of January 13, 2020:

{"coord":{"lon":13.41,"lat":52.52},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":3.2,"feels_like":-1.49,"temp_min":1.11,"temp_max":5,"pressure":1017,"humidity":86},"visibility":10000,"wind":{"speed":4.1,"deg":180},"clouds":{"all":40},"dt":1578947701,"sys":{"type":1,"id":1275,"country":"DE","sunrise":1578899517,"sunset":1578928632},"timezone":3600,"id":2950159,"name":"Berlin","cod":200}

A little hard to read, isn’t it? ­čśë But for your ESP8266, this is no problem. The ArduinoJson library provides you with everything you need for this. In short, with a few lines of code, you can extract exactly the data you need. On top of it all, there is a for-loop that makes sure that the upcoming displays and animations are shown three times until the display goes out again:

      //Wetterlage und Temperatur ausgeben
      for (int j = 0; j < 3; j++) { // 3x Animation durchlaufen lassen bis zur n├Ąchsten Messung
        //Wetterdaten auslesen anhand von ID
        JsonObject weather_0 = doc["weather"][0];
        int weather_0_id = weather_0["id"]; // Wetter-ID
        Serial.println(weather_0_id);

Now you have read the ID of the current weather from the data. Openweather gives every weather condition its own three digit ID. For example, light rain has the ID 500, while trickling volcanic ash has the ID 762! You can find all IDs here.

Show weather data on the display

Now follow a series of If Statements, which show and animate the icon matching the weather on your display. Here is an example of the ID range “Clouds” – these are all IDs between 801 and 804. You can find further explanations in the comments in the code. Interesting is the For-Loop: Here you move the icon to the left by displaying it 128 times (the width of the icon) always one pixel to the left. This creates the impression of an animation.

        if (weather_0_id > 800 && weather_0_id < 900) {
          //Cloud anzeigen und wegschieben
          display.clearDisplay(); //Display l├Âschen
          display.drawBitmap(0, 0, clouds, 128, 64, WHITE); //Icon zeichnen...
          display.display(); //...und anzeigen
          digitalWrite(12, LOW); //LED ausschalten, da kein Regen
          delay(2000);
          for (int i = 0; i > -128; i--) { //Das Icon aus dem Display "schieben"
            display.clearDisplay();
            display.drawBitmap(i, 0, clouds, 128, 64, WHITE);
            display.display();
            delay(1);
          }

Following are more requests per else if{} for the other weather conditions, which you find at the bottom of the whole sketch.

The temperature display is still missing. You can also read this from the JSON data and bring it animated on your display:

//Temperatur anzeigen und animieren
        JsonObject main = doc["main"];
        int main_temp = (int)main["temp"]; // Daten in ein INT umwandeln und in Variable speichern
        String temp = String(main_temp) + " C"; //C f├╝r Celsius anh├Ąngen
        display.setTextSize(3); //Schriftgr├Â├če erh├Âhen
        display.setCursor(25, 20);
        display.println(temp);
        display.display();
        delay(2000);
        for (int i = 25; i > -144; i--) { //Animation
          display.clearDisplay();
          display.setCursor(i, 20);
          display.println(temp);
          display.display();
          delay(1);
        }

Finally, set the font size back to 1 and close all open brackets. The very last else refers to the request if the server’s answer was positive (i.e. 200) and returns an error message if it was not.

Here is the complete sketch. If you copy and use it, make sure to enter your own Wi-Fi data and your API key from Openweather in the highlighted places.

What’s next?

You have now created a device that reminds you of your umbrella. Integrate it into a box and power the ESP8266, for example with a powerbank via USB. You can place this box near your front door, so your project will warn you of the rain outside at just the right moment.

You think bigger and about your own weather server? Then learn here how to turn your ESP8266 into a web server.

Please note: Unfortunately, you cannot rely 100% on the weather data from the Internet. Sometimes it might be safer to take a look out the window ­čśë

Letzte Aktualisierung am 2021-01-09 / Affiliate Links / Bilder von der Amazon Product Advertising API

You may also like

Comments are closed.