NodeMCU ESP-12E: A Google Charts Gauge

See Your NodeMCU ESP8266 Data from Almost Anywhere

Not convinced that IoT Projects are for you?  Intimidated by all the new confusing terms and technologies? Then stand by…

For under twenty dollars,  we are going to display a value from our Node MCU on a web page using an attractive Gauge.  If you have WiFi access,  this might take you a couple hours.

What You’re Going to Do

In a nutshell,  you will:

  1. Create a value in the CloudMQTT account.
  2. Copy, paste, modify and upload a sketch to the NodeMCU
  3. Verify that you receive the data on your MQTT
  4. Copy, paste and modify an HTML page to the Blogger Account
  5. View the data from your desktop or smart phone

The graphic below illustrates these steps.

 

What You’re Going to Need

Get a NodeMCU ESP-12E Development Board

This is where you will spend your money.  Many of these are available for under ten dollars and come with free shipping.   You can purchase one at any of the following locations:

Amazon      eBay      BangGood      DealExtreme     ITead

Prepare Your NodeMCU for Use With the Arduino IDE

The Arduino Integrated Development Environment is freely available at the Arduino site.  If you’ve used an Arduino, you probably already have it.  If not,  you can download a copy HERE.

The next thing you will need to do is prepare your Arduino IDE and your NodeMCU board so that they work with each other.   Its simple and is described in the Henry’s Bench article found HERE.

Get a Free Amazon CloudMQTT Account

This will be your MQTT Broker.   If you are new to MQTT,  you can read this MQTT Basics article.  Its a simple read and will help you to understand some of the IoT terminology.

This account will allow you to up to connect ten devices and is perfect for your first several projects.    You can get that account HERE.

Get a Free Blogger Account by Google

This is where you will create your web page that has your gauge displaying the data from your ESP8266 NodeMCU development board.  If you don’t already have an account,  you can get one HERE.

Get the Free AdafruitMQTT Library

This library allows you to turn your NodeMCU device into either an MQTT publisher or subscriber.  We’ll be creating a publisher.  It can be found HERE.

If you don’t already know how to add a library,  you can read the instructions over on the Arduino Site.

NodeMCU Web Page Gauge Tutorial

Create an ‘Instance’ on Your AWS CloudMQTT Account

Sign into cloudMQTT and access your Control Panel.  Click +Create to create a new ‘Instance’.

Name your new instance ‘myFirstValue’.   Click Create.

View the details on this Instance.   You may want to keep it open.  You will want these details later.

Copy, and Paste the Sketch into Arduino IDE

Copy and Paste this into your Arduino IDE.   Don’t upload it yet.   It needs to be modified.

// Henry's Bench
// NodeMCU to cloudMQTT Connection

#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

/************************* WiFi Access Point *********************************/

#define WLAN_SSID       "YOUR ROUTER SSID"
#define WLAN_PASS       "YOUR ROUTER PASSWORD"

/************************* Information to Connect to Cloud MQTT *********************************/
/*  You will need and account - Its FREE  */

#define AIO_SERVER      "AWS SERVER"  
#define AIO_SERVERPORT  YOUR INSTANCE PORT                  
#define AIO_USERNAME    "YOUR INSTANCE USER"
#define AIO_KEY         "YOUR INSTANCE KEY"

/************ Setting up your WiFi Client and MQTT Client ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.

WiFiClient client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Set Up a Feed to Publish To ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>

Adafruit_MQTT_Publish myFirstValue = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/myFirstValue");


/********************* Values ******************************/
// Need a changing value to send.  We will increment this value
// in the getVal function.  
//we start at zero and when it gets to 10 we start over.

uint32_t xVal=-1;

/*************************** Sketch Code ***********************************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());
 
}


void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  

  // Now we can publish stuff!
  Serial.print(F("\nSending myValue "));
  Serial.print((xVal-1));
  Serial.print("...");
  if (! myFirstValue.publish(getVal())) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
  /*
  if(! mqtt.ping()) {
    mqtt.disconnect();
  }
  */
  delay(1000);
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}


//  Use this increment myVal

uint8_t getVal(){

  if(xVal == 11){
      xVal = 0;
  }
  return xVal++;
  
}

Modify the Arduino Sketch for Use with your WiFi Router

You will want to look at the label on your router to get your SSID and Password.   If you’re unfamiliar with this, you can read the tutorial found HERE.

Modify the Arduino Sketch for Use with AWS CloudMQTT

You will need to refer to your AWS CloudMQTT Instance details.  You will need to modify server, port, user name and password (or Key) information accordingly.

Upload Sketch to the NodeMCU ESP-12E and Verify Output.

Upload the sketch and return to the CloudMQTT instance details screen.  Click on Websocket UI.   You should see messages coming from your NodeMCU arriving at about one second rate.   The message will count from zero to ten.  Once it gets to ten, it will start all over.

Turn Blogger SSL On.

Blogger comes with a free SSL certificate.  Access your Blogger Account settings and turn SSL on.

Create a New Page On Blogger

Access your Blogger Account and create a new page by first clicking on Pages and then clicking New Page.


Your New Page will appear.   Give it a name and click on HTML.


Copy and Paste NodeMCU Gauge HTML (as HTML) Into Your Blogger Page

The link to  HTML makes use of a couple of Javascript APIs to create a Websocket to your CloudMQTT feed and to Draw the gauge.   The gauge is drawn using Google Charts.     The MQTT Websocket is created using Paho Client for Javascript by Eclipse.

<html>

<head>
  <title>My First Value</title>
  <script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>


</head>

<body>

<div id="connstatus">
-----</div>
<div id="chart_div" style="height: 300px; width: 300px;">
</div>
</body>

<script>
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);


var myMsg = 0; // where I put my message

// gauge variables.





// Google Charts Stuff
     function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['My Value', 'Value'],
          ['Count', 0],
        ]);

        var options = {
          min: 0, max: 10,
          width: 300, height: 300,
          redFrom: 9.5, redTo: 10,
          yellowFrom:9.0, yellowTo: 9.5,
          minorTicks: 2,
          majorTicks: ["0","1","2","3","4","5","6", "7", "8","9","10"]
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);

        setInterval(function() {
          data.setValue(0, 1, myMsg );
          chart.draw(data, options);
        }, 400);
      }


 // Create a client instance
  //client = new Paho.MQTT.Client("host", port,"client_id");


  client = new Paho.MQTT.Client("YOUR-CLOUD-MQTT-SERVER", "YOUR-CLOUDMQTT-WEBSOCKET-PORT", "web_" + parseInt(Math.random() * 100, 10));

  // set callback handlers
  client.onConnectionLost = onConnectionLost;
  client.onMessageArrived = onMessageArrived;
  var options = {
    useSSL: true,
    userName: "YOUR-CLOUDMQTT-USERNAME",
    password: "YOUR-CLOUDMQTT-PASSWORD",
    onSuccess:onConnect,
    onFailure:doFail
  }

  // connect the client



    client.connect(options);


  // called when the client connects
  function onConnect() {
    // Once a connection has been made, make a subscription and send a message.
    document.getElementById("connstatus").innerHTML = "Connected";
    console.log("onConnect");
    client.subscribe("YOUR-CLOUDMQTT-USERNAME/feeds/myFirstValue");
  }

  function doFail(e){
    console.log(e);
  }

  // called when the client loses its connection
  function onConnectionLost(responseObject) {
    document.getElementById("connstatus").innerHTML = "Not Connected";
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:"+responseObject.errorMessage);
    }
  }

  // called when a message arrives
  function onMessageArrived(message) {
    myMsg = message.payloadString;

  }

  function updateChart(){
    data.setValue(0, 1, 50);
    chart.draw(data, options);
  }

</script>

</html>
NodeMCU Gauge

Make Modifications to HTML Copied to Blogger

You will need to refer back to your CloudMQTT Instance Details and make modifications to the HMTL Code.

Find the section in the HTML code that calls for your server name, port, username and password.  Use the information found on the CloudMQTT Instance Details page to change these values.  Note that you are using the Websocket port on this page.


Make one final Blogger HTML edit to change the username in the feed description.


Publish Your Page and View the Result

Click Publish and view your page.  The result should look like the picture below.    Go ahead a navigate to this page on your smart phone browser.  The result should be very similar.