ESP8266 (Web Server – Part 5): how to use Google Charts to display gauges and charts

Now that we have a records we will add graphics to the Web interface of the ESP8266 using the Google Charts library. There are many libraries to create graphics and gauges in Javascript / HTML5. Google Charts is a very rich library that offers 28 different models (line, gauge, horizontal or vertical histogram, glove, pie, bubble, card, radar …) sufficient to start and create a beautiful interface. We will see in another tutorial other libraries with a more modern display.

The full source code of the project is also available on GitHub here

Prepare data for bar histogram

We’ll start by creating a small histogram that allows us to see the evolution of the average temperature (and humidity) for the last 7 hours (the registration period defined in the previous tutorial). Unless I’m mistaken on my part, there is no library to do the classification of measurements on Arduino (say me in the comments otherwise). I propose a small algorithm which allows to calculate the temperature and the average humidity for 7 classes (1 class per hour).

This algorithm is probably not the best for it but the goal of this tutorial is the creation of graphics and Google Charts sending data from the Arduino code to the Web interface.

How it works ?

  1. We initialize two arrays (statTemp and statHumi) with initial value -999 (or any other arbitrary value).
  2. We calculate the size of a class sizeClass = sizeHist / nbClass
  3. One moves the data table (only when it is full, it will be necessary to optimize this). The variable k gives the position in the table
  4. If the cell is empty (-999) then it is given the current value. Otherwise the average value (current value + previous value / 2)
  5. We test if we must change class (k + 1)> sizeClass * (currentClass + 1)
  6. Both tables are updated in the JSON (bart and barh).

Add Google Charts to a Web Interface ESP8266

Let us now turn to serious matters.

The Google Charts library

Google is definitely everywhere. The Google Charts library is a library that exists since 2008. It is not the most beautiful library that exists but it is simple enough to implement and especially it is quite easy to create graphs real time (or at least ‘We will update very often). We will test other libraries later. The documentation is pretty good. Only flat, currently some graphics are available in the old version and in the new (Material Design). It is easy enough to locate it, for example to draw a line chart, you can

Or for the new version (Material Design)

All the options are not yet available in the Material Design version, which makes it quite tedious to focus. If the aesthetic aspect is not primordial for you, I advise you to stay on the old version.

esp8266 web server google charts graphiques

HTML code

To load the library, simply add in the section Head this reference

Adding a Bootstrap Panel

The Bootstrap panel class allows to present data in the form of a map with a header (Bootstrap documentation). We will use it to create a header containing the current measurements returned by the sensors (DHT22 and BMP180).

The Panel consists of a header, panel-heading class. If we want to add a title, we must add the panel-title class to the class h1 (or hx). But nothing prevents us from putting other things into heading. Here we will simply add a row that will be cut into 3 equal columns (col-md-4). To make it responsive on small screens, add the class col-xs-4 (for example). In each column, we simply put an identifier that will be used to display the content as soon as values are available.

Which gives the following Pug code

Here’s what we’ll get

esp8266 web server bootstrap panel title header

Add graphs (line, vertical histogram, gauge) on 2 columns

The graphs will take place in another panel-body class div. We will simply add 2 lines cut in 2 columns. Either 4 cells. In each cell, you will place a Google Chart. Dan HTML code, there is nothing to set apart a style. Here, one takes all available width (width: 100%) and sets a height, for example height: 300px. For the gauge, I simply added a margin left (margin-left: 25%) because by default it is pasted on the left edge.

Finally you have noticed a title h2 that will make visible if there is no histogram to display and vice versa.

Javascript code

Depending on the type of graphic you want, additional packages must be loaded in addition to the corechart.

Then we indicate the function that will be launched as soon as the page has been loaded and the resources have been retrieved and loaded.

To create a graph, you must already create an object by specifying its type. You retrieve your destination with the document.getElementById function (for example).

Then there are several methods to assign options and data, here is one. A data table is created.

Then add the columns that will contain the values of the graph. The data type must be specified for each column. It is necessary to refer to the documentation to know the available formats (data format) for the desired graphic, here for example for a AreaChart. Here the time is of the form timeofday.

You can also define options, for example the position of the legend (position: “bottom” to place it underneath, “none” to disable its display), the label of the axes, etc … An example for the AreaChart

Now all you have to do is create a function to retrieve data from the ESP8266 and display it on the screen. To do this, we will simply use the jquery $.getJSON function already used in the previous tutorial. To avoid wasting the resources of the computer, smartphone or tablet and ESP8266, one checks that the graphics board is active before making an update

Processing the JSON sent by the Web Server ESP8266

We will retrieve the data in the form of a JSON. for example

We will have to make a small loop that runs the timestamp array to add a new row each time to the chart data table. For example, the data are prepared for the temperature / humidity graph of DHT22. The first column must contain one hour. For that we will use the function javascript new Date which is able to convert a timestamp unix into a date. It is necessary to multiply by 1000 because the function waits for milli-seconds, the timestamp is in seconds in this case. Finally, the date is indicated in the form of a table [HH, MM, SS]. Sorry, but have to do with the Google API! The treatment of time is always a problem finally!

Add this block of values at once with the addRows function. Note that the addRow function also exists (for a single line).

Here I chose not to keep the old values, so we will delete them with the removeRows function which takes as parameter the index and the number of rows to remove.

View and refresh graphics automatically

All is ready, you can ask the browser to display the chartTemp chart.

You can hide a chart if it is empty and display an information message instead. Just test the number of rows in the data array with the getNumberOfRows() method. Then show() or hide() on the element to make it visible or hide it. That’s it.

It only remains for the browser to update the graphics regularly by creating a timer using the setInterval() function. The timer is placed just before the updateGraph() function.

Arduino Code

We will add a call to the sendHistory() function when the web server intercepts a call on the /graph_temp.json page.

All measurements are stored in a JSON object using the ArduinoJSON library. It is very easy to generate a string using the printTo function. Which stores the result in a buffer. It will therefore be necessary to have enough memory if not the export will be impossible. We send the client the Serialized serialized JSON with server.send().

Be careful to stay reasonable and do not ask for an updated graphics every second. With little data, the ESP8266 will cash, but for how long … To know the minimum frequency not to be exceeded, look at the time to get an answer with the development tools of a browser.

Final Project Code

The full source code of the project is also available on GitHub here

Pug Template

The Pug template (Jade) easier to understand, edit, correct than HTML code.

HTML code

The HTML code generated from the template Pug above.


Arduino Code

And the Arduino code to upload in the ESP8266. The code is intended for a Wemos D1 Mini equipped with a Shield DHT22 as well as a BMP180 on bus I2C.

Interface obtained

Connect to the ESP8266 from a browser. Wait a few seconds to get the first measurements. The two graphs at the top make it possible to monitor the temperature, humidity and atmospheric pressure during the recording period (here 40 minutes). The atmospheric pressure is also reported on a gauge. The colors are real (red for risk of storm and rain), orange (variable time), green (beautiful temp). It is not possible to define other zones, which is a pity. Finally, the histogram makes it possible to follow the average evolution of temperature and humidity. Here, each bar represents about 6 minutes.

esp8266 web server spiffs bootstrap dht22 bmp180 google charts

So, our ESP8266 Web Server programming tutorial soon comes to an end. In the next tutorial we will see how to update “in the air” (OTA) the Arduino program.

Subscribe to the weekly newsletter

No spam and no other use will be made of your email. You can unsubscribe anytime.

  • francesco maviglia

    Great project, thank you very much. I have tried with wemos d1, and it worked immediately, even by modifying a little bit the code to use different sensors. I have anyway the issue that once the 7 hours are reached the graphs stop being updated, and the remain alwyas the same. I would immagine that they are meant to scroll as the time pgoes by, maybe even forgetting the past data. Does it work like this for you?
    Thank you

    • Hello Francesco and thank you very much. No, I did not encounter this problem during the developments. Maybe it’s a problem rated internet browser. You tried to close the page and open a new one?

      • francesco maviglia

        Thank you. What I suspect is that the Json command remove was somehow missbehaving. I rolled back the library to the version that you showe in the tutorial 4 and now the graph seems to work fine (I will test the stability during the next few days). I will now train myself in changing the graph type and parameters (i.e. the duration increased to 24h), and see how it goes.

        • Perfect. thank you very much for your feedback.

          • francesco maviglia

            Strangely enought it worked for about one day and half, then it got
            stuck again to the latest values. Just to explain: The first page shows
            normally the tabular data that the sensor feeds, while the in the graph page, the
            two top panels, shows a frozen 7 hour situation, of the last 7 hours
            after 1,5 days that I started the system. Clearly at the beginning the
            system was able to update and scroll the hours, but at a certain point
            this was not anymore the case. The gauge instead still works and keeps
            updated. How can I diagnose the problem? I suspect, as mentioned, either on the JSON capabiity to delete the array, or maybe on the fact that my internet connection jups, sometime, and not receiving the signal from the server the algorithm fails? could II add some code to ignore the request of data, if is not avaialbe, without getting the program flows stuck? Thank you for our help

          • Hello Franscesco. Thanks for your info. Maybe it would be necessary to test the validity of the side web browser or force the reloading of the page (every hour for example).

          • francesco maviglia

            thank you again, I have changed the hardware (using a wemos mini), but similar problem arise. Now the plots on the graph pages upper part have an issue on the time scale. See pictures below. Could it be that this is due to retrival of the internet server for the time? https://uploads.disquscdn.com/images/f9133917fae020adade530302fb0751f05ca7b41be4f6bb042d2808340f20a06.png

        • francesco maviglia

          Strangely enopught it worked for about one day and half, then it got stuck again to the latest values. Just to explain: The first page shows normally the tabular data the sensor feeds, while the graph page, the two top panels, shoe a frozen 7 hour situation, of the last 7 hours after 1,5 days that ?I started the sistem. clearly at the beginning the system was able to update and scroll the hours, but at a certain point this was not anymore the case. The gauge instead still works and keeps updated. How can I diagnose the problem? Thank you for our help