ESP8266 Weather Station User Guide V 1.
Contents 1. Introduction ................................................................................................................... 4 2. Assembly ...................................................................................................................... 5 3. 4. 5. 6. A. ESP8266 Module .................................................................................................. 5 B. OLED Display ..............................................................................
7. 8. B. The Grammar ...................................................................................................... 41 C. The JSON Streaming Parser Library................................................................... 42 D. Conclusion........................................................................................................... 44 Collecting and Displaying Local Data ......................................................................... 45 A. The Climate Node Setup .....
1.Introduction The ESP8266 WeatherStation is one easy way to get started with the ESP8266 and IoT. The included guide helps you step-by-step to setup an internet connected weather station which shows current and forecasted weather information. The Uctronics ESP8266 WeatherStation Kit has the advantage that everything fits together, but you can of course also get the components from your preferred supplier.
2.Assembly A. ESP8266 Module There are many different modules available based on ESP8266s, they differ in a number of aspects such as the quantity of available GPIO pins or if they can be programmed easily without need of an additional Serial-to-USB converter. If you are a beginer I suggest you use a developer-friendly module like the NodeMCU V1.0 or the Wemos D1 mini. They come with a USB connector and have the maximum number of available pins ready for your usage.
B. OLED Display With the display, you also have many options: do you want the pixels to be white or blue, or do you even prefer a two-color display where the footer is in one color and the rest in another? What really matters is the driver chip and the protocol. The OLED library currently supports I2C and SPI for both the SSD1306 and the SH1106 chip. The first is often used for 0.96” inch displays while the second one is used for 0.96” displays.
C. DHT11 Humidity & Temperature Sensor This DHT11 Temperature & Humidity Sensor features a temperature & humidity sensor complex with a calibrated digital signal output. By using the exclusive digital-signalacquisition technique and temperature & humidity sensing technology, it ensures high reliability and excellent long-term stability.
D. Wires & Cables You will also need some wires to connect the display to the ESP8266. In case you want to connect the display directly to the NodeMCU you will need at least four female-to-female jumper wires, since both the display and the NodeMCU have male pin headers. The wires don’t need to be long, 7.87” (20cm) is usually enough. To program the ESP8266 module you will also need a micro USB cable.
3. Tool Setup In this chapter, we will prepare your development environment by installing all the tools necessary. Drivers are needed to communicate with the ESP8266, a tool called “Arduino IDE” will let us write code, and a sample project will prove that the components are working well together.
A. Download and Install the Serial Driver To program the NodeMCU V1.0, your development platform (PC, Mac, Linux) needs to detect the Serial-To-USB adapter soldered onto the ESP8266 module. This ESP8266 development module has built in a high-quality Labs CP2102 Single-Chip USB to UART Bridge with MicroUSB connector that baud rates up to 921600. You can download and install the driver from here: https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.
B. The Arduino IDE The Arduino Integrated Development Environment (IDE) is the tool you will use to program the ESP8266. IDEs are more than just editors; they help you with various tasks during the development process. To install the Arduino IDE, go to https://www.arduino.cc/en/Main/Software and download the latest version matching your operating system: ⚫ For Mac OS X, you can download a ZIP file which you then have to extract.
C. Install the ESP8266 tool chain A tool chain is the set of tools that lets you compile and create binaries for a certain platform. Since we want to create binaries for the ESP8266 we need a different tool chain than the one that comes with the plain vanilla Arduino IDE. The Arduino IDE has a wonderful feature, Board Manager, to save you the hassle of downloading many different files and copying them into obscure locations.
D. Selecting the Correct Board Now your Arduino IDE knows about ESP8266 boards in general. But not all the ESP8266 boards are the same; there are subtle but important differences in available Flash Memory and how they can be programmed. The selection of the correct board also defines the names of the GPIO pins: the designers of the NodeMCU decided to introduce a completely new naming scheme for the pins.
E. Setting the Correct Port Serial interface: At the hardware level the ESP8266 is programmed through a serial interface. In short this is a very common communication interface which normally requires three lines: transmit (TX), receive (RX) and ground (GND). Both devices involved in the communication need to agree on the rate the characters are sent over the wire. This rate is usually measured in BAUD. 10 BAUD is equal to 1 character per second.
F. Testing the Setup: WiFi Scanner Thanks for bearing with the complicated preparation until getting to the really cool part. We are going to run our first program on the NodeMCU! In the Menu of the Arduino IDE go to File > Examples > ESP8266Wifi and select WiFiScan. A new window will open up. This window is your current project and is also called a “Sketch”. To compile and transfer the binary to the ESP8266 click on the green circle that contains an arrow on the very top of the window.
G. Summary Before we continue to the WeatherStation project let’s have a closer look at what we just accomplished: ⚫ We installed a driver which lets us program the ESP8266 with custom code that we wrote. Which driver needs to be installed depends on the Serial-to-USB converter we use. Some ESP modules already have such a converter; others will need an additional one. ⚫ We downloaded and installed the Arduino IDE. In the IDE we write the code, compile it and transfer it to the embedded device.
4. ESP8266 Programming Basics In this chapter, we will have a look at the building blocks of an Arduino sketch. This will help you to understand and modify the Weather Station which we will build in the next chapter. If you just want to get the WeatherStation running you can skip this chapter. A. Preparation In this chapter, we will work with exercises which you can download from GitHub. They contain several Arduino projects for the ESP8266.
B. The Arduino Sketch The Arduino platform was built with the beginner in mind. Compared to a normal C program the Arduino IDE hides a few things from you to simplify the setup. First of all you do not have to create a makefile to build your code into an executable binary. The Arduino IDE also includes a default header file for you: #include "Arduino.h". This contains all definitions needed for a regular Arduino program.
C. Hello World: The serial console Every self-respecting programming tutorial starts with a “Hello World” program. And I don’t want to break with this tradition here. A Hello-World program usually does no more than printing these two words somewhere on the screen. But we are programming a microcontroller which does not have a screen yet. So where can we display the text? We will use the Serial object to do that.
Now your output should look something like this: If you want to learn more about the Serial object you can find more in the following link: http://esp8266.github.io/Arduino/versions/2.3.0/doc/reference.html#serial The exercise contains another important built-in function: delay(1000); This instructs the processor to wait 1000 milliseconds (1 second) before continuing with the execution.
D. Input/Output: GPIO pins Now that we can talk to our microcontroller over the serial line it is time to interact with the real world. Our ESP8266 is equipped with several so-called General Purpose Input Output or in short GPIO pins. They can be used for many different applications such as sensing and generating digital signals of the 3.3 Volt range. This is important if you plan to use an external component with your ESP8266: hardware designed for older Arduinos often uses the 5V (CMOS) range.
GPIO5 D1 GPIO14 D5 GPIO6 N/A GPIO15 D8 GPIO7 N/A GPIO16 D0 GPIO8 N/A PIN DEFINITION NodeMCU DevKit Pin Map https://github.com/nodemcu/nodemcu-devkit-v1.0 D0(GPIO16) can only be used as gpio read/write, no interrupt supported, no pwm/i2c/ow supported. Exercise 04.02: Can’t touch this!? In this exercise, you are going to read from the button on your NodeMCU labelled with FLASH. This button is connected to the D3 pin.
E. Interrupts Depending on your age you might remember interrupts from your PC. They were always important to get your sound card to play beautiful music. The ESP8266 can also be controlled by interrupts. In the previous exercises we were checking regularly for the state of a GPIO pin. This is fine if you are not doing anything else in the main loop. But you might miss a change in a state if it is very short, and that is were the interrupts can help.
F. Measuring analog signals So far we can read and write the digital states HIGHand LOW, but what if we want to deal with analog signals? The ESP has one Analog To Digital Converter (ADC) which can be used to measure voltage in the range 0 - 1V. To do that use the following command: unsigned value = analogRead(A0); You can also use the ADC to measure the input voltage without any additional wiring.
G. WiFi The last few chapters were all about built-in functions of the Arduino/ESP8266 platform. Now we will start using libraries which are part of the platform and are already installed. So how can we use the WiFi module of the ESP8266? First of all you need to know that the ESP8266 can operate as a WiFi client (like a smartphone or laptop) and/or as an access point (like a WiFi router or extender). You can set this mode with: WiFi.
H. HTTP By connecting to the internet you can exchange data between your ESP8266 and the network. Let’s look at how we can load content from a web server using the Hyper Text Transfer Protocol (HTTP). This protocol is the foundation of the World Wide Web. 1 #include 2 3 char* ssid = "SSID"; 4 const char* password = "PASSW0RD"; 5 6 const char* host = "www.squix.org"; 7 8 void setup() { 9 Serial.begin(115200); 10 11 Serial.print("Connecting to "); 12 Serial.println(ssid); 13 14 WiFi.
30 31 Serial.print("connecting to "); 32 Serial.println(host); 33 34 // Use WiFiClient class to create TCP connections 35 WiFiClient client; 36 const int httpPort = 80; 37 if (!client.connect(host, httpPort)) { 38 Serial.println("connection failed"); 39 return; 40 } 41 42 // We now create a URI for the request 43 String url = "/guide/"; 44 45 Serial.print("Requesting URL: "); 46 Serial.println(url); 47 48 // This will send the request to the server 49 client.
64 String line = client.readStringUntil('\r'); 65 Serial.print(line); 66 } 67 68 } How does this work? First we define the SSID and password of the WiFi access point we want to connect to. Please note that there are better ways to do that. The WiFiManager (https://github.com/tzapu/WiFiManager) for instance starts the ESP8266 as an access point if it cannot connect to any SSID. You then use your smartphone to configure the WiFi credentials and there is no need to hard code these into your firmware.
A click on View Certificate will bring up the detail window about Google’s certificate: Scroll down to the bottom of the window and copy the value behind SHA1. This is the fingerprint to verify that you are actually talking to www.google.ch. Exercise 04.06: Better safe than sorry! In this exercise we will start with the same program as I included earlier in this chapter. But now you are going to change the code to receive the search site from google on a secure channel.
5. The ESP8266 WeatherStation In this chapter we will get the WeatherStation to run. We will install several libraries used for setting up access to the internet, for reading and parsing the data from the service providing your local weather forecasts, as well as a library to display the data on the OLED display. Then we will adjust the WeatherStation code to display your local weather information and get a so-called API key to access the weather forecast service. A.
SSD1306 OLED Library
B. Open the Weather Station Example You have now installed the three required libraries. Often Arduino libraries contain example sketches which behave like a template to kick-start your project. If you have already worked with the Arduino IDE you might have used other demo sketches before. In the last chapter we used the Wifi Scanner Sketch. Now we are going to use the WeatherStation template to get started.
C. Getting the OpenWeatherMap API Key API (Key): What is an API and what is an API Key? Application Programming Interfaces (APIs) are a well-defined way on how one piece of code can talk to another. This can be on the same device, but often refers to the communication between two devices connected by a network. For the WeatherStation we need to get current and forecast data in a machinereadable format. To do this we will call the API of a service called OpenWeatherMap.
C. Getting the OpenWeatherMap API Key The ESP8266 WeatherStation: OpenWeatherMap API Page If you should forget your key you can always come back and get it here.
D. Configuring the Weather Station Earlier when you chose the WeatherStation example you created a copy of the code included in thelibrary. This code needs to be adapted so that it works for you. There are better options than putting configuration into your code: we could for instance offer a web interface where you could configure your settings. This would be much better since you could change values without changing the code, which would require compiling a new firmware and sending it over to the device.
E. Connecting the Hardware The WeatherStation Kit comes with an OLED display that has four connectors: VCC, GND, SCL and SDA. They have the following meaning: ⚫ VCC and GND are the power supply of the display. VCC is the positive supply voltage and GND stands for “ground”. They will be connected to 3V3 and GND on the NodeMCU board ⚫ SCL and SDA are the data lines of the I2C protocol. SCL stands for Serial Clock and SDA for Serial Data.
changed the pin naming for their LUA firmware. If you are programming a NodeMCU module you can use the printed D# names. If you use a generic ESP8266 module then you have to use the corresponding GPIO numbers.
F. First Run Now we’re all set to run the WeatherStation software for the first time. Click on the Upload arrow and wait until the compilation and the transfer have ended. Now you should see the OLED display lighting up and displaying a WiFi icon. The module should now be trying to acquire access to the wireless network you have defined earlier. This is just the beginning. In the next chapter I’ll give you some ideas of what else you can build with the WeatherStation hardware.
G. Summary If everything went well you now have a working ESP8266 WeatherStation. Congratulations! Let’s look back what we did in this chapter: ⚫ We used the WeatherStation example and created a working copy for us. All changes will be applied to the copy, not the original example. If you accidentally make your code unusable you can always go back to the example and start with a fresh copy. ⚫ We installed several libraries by using the Arduino IDE Library Manager.
6. The WeatherStation Code Explained In this chapter we will have a look at the building blocks of the WeatherStation. This project is a relatively complex piece of code and I hope to improve this chapter over time with new details. A. The JSON Streaming Parser You might not know it but the most important puzzle piece for the WeatherStation project is a thing called a streaming parser. What is a streaming parser? You are most certainly using parsers every day.
bits and bytes but also tries to understand the content. The streaming parser doesn’t care how big the document (or the amount of water) is, it just takes out what it needs from the stream. Streaming parsers are also referred to as event-based parsers since they react to certain events in the data stream. DOM parsers are referred to as tree-based parsers since they build a full representation of the document in the tree-like structure.
B. The Grammar The following image describes the grammar of a valid JSON object in a very concise way. It means that a JSON object knows three basic types: ⚫ object ⚫ array and ⚫ value JSON grammar Objects always start and end with curly brackets. They can be either empty (line to the top) or contain string/value pairs, separated by a colon. These pairs can be repeated by adding a comma between them. Arrays start and end with square brackets. They can be either empty or contain a value.
C. The JSON Streaming Parser Library Why would we want to use a streaming parser on the ESP8266? Embedded devices usually have very limited resources available. One scarce resource is the heap memory. Many of the REST APIs I am using in my projects provide big response objects, but we are usually just interested in a small fraction of it. As mentioned earlier, a tree-based parser would load the whole document into memory and make it available once the document stream has ended.
the last key was I had seen and then I store the value in the appropriate variable. For the example from before I would do 1 void ExampleListener::key(String key) { 2 currentKey_ = key; 3 } 4 5 void ExampleListener::value(String key) { 6 if (currentKey_ == "name") { 7 name_ = value; 8 } else if (currentKey_ == "city") { 9 city_ = value; 10 } 11 } In the stream of the object {“name”: “Eichhorn”} we will first get a call to the method key() with the value “name” which we store in currentKey_.
D. Conclusion For a document or object of the size we had in the example a streaming parser is usually an extreme overkill. It is complicated to use, requires you to write a lot of code and is memorywise probably even worse than a tree parser. It is only recommended to implement a streaming parser if you have big objects or if you just don’t know how big your object might be.
7. Collecting and Displaying Local Data So far we have created a device which connects to the internet and uses an API to fetch weather data. But this is not really an Internet-of-Things application; after all we are just displaying data. In this chapter, we will change that. A. The Climate Node Setup This project will enable you to collect humidity and temperature in one room of your house or apartment and display the values in another room on the WeatherStation.
B. Thingspeak Setup Thingspeak is a free cloud service which allows you to easily post (sensor) data, to visualize it and to retrieve it again using simple HTTP methods. I’d like to point out that you could also use OpenWeatherMap to store your climate data and it probably would be very easy to do as well. But I believe that for education purposes Thingspeak permits more degrees of freedom. After all you could also send readouts from a motion sensor and visualize this information on a chart.
Thingspeak API keys The first one will allow you to write to this channel in Thingspeak, and the second one will allow you to read from it. Treat them as secrets and with care. Others might be able to spam your channel or to “steal” your data. We will use these keys soon enough… Also note the channel ID on top of the screen, in my case 76642.
C. Programming the Climate Node Now we have all the ingredients to post the climate data to Thingspeak. We just have to program the ESP8266 accordingly. Go to: https://github.com/supprot/ArduCAM_esp8266dht-thingspeak-logger.git and download the code as a Zip file (or optionally do a GitHub checkout). Now adapt the settings to your needs: In particular the Wifi settings and the Thingspeak API key have to be updated. Take the Write API key from the previous step.
8. More Projects In the last chapters, you successfully set up the development environment to program the ESP8266 and got your first Internet-of-Things device running. While this chapter concludes this Getting Started Guide I hope it is just the beginning of many interesting IoT projects you will build. A. The ESP8266 PlaneSpotter The ESP8266 PlaneSpotter is an additional project that you can build with the same hardware you used for the WeatherStation.
B. The ESP8266 WorldClock The WorldClock is yet another simple project which you can build with the WeatherStation hardware - and you already have a demo installed in your Arduino editor.