NodeMCU ESP-12E IoT: Publishing a Value

Use Arduino IDE and NodeMCU to Send Data to The Internet

Publishing or sending data to the internet is among coolest things that an IoT (Internet of Things)  object can do.   That’s what we’re going to do in this tutorial.   Specifically,  we’re going to set up our NodeMCU to send changing data to the Internet and we’re view that data via a web browser that is on your desktop computer or mobile phone.

Because this is geared towards beginners, we’re going to make use of the very user friendly adafruit.io website.

What You Need

NodeMCU ESP-12E Development Board

These are pretty cheap. If you’re savvy you can adapt this tutorial to another ESP8266 device that you may have.  If you’re a beginner, you can simply purchase one from any of the vendors below:

Amazon      eBay      Bang Good      Deal Extreme

Prepare Arduino IDE and NodeMCU Board

The Arduino IDC (Integrated Development Environment) needs to be set up to work with your NodeMCU development board.  If you have already done so,  you may read the tutorial found HERE.

Have Some Knowledge About Powering the NodeMCU

This tutorial worked just fine for me when powering from the USB port of my computer.  That may not be the case for you.  If you have problems powering your NodeMCU via the USB port, you may need to power another way.  You have several options that you can read about HERE.

Establish a Connection to your WiFi Router

Establishing a connection to your WiFi router is pretty simple and you may not need any help.  However if you’re relatively new,  you can read this tutorial found HERE.

NodeMCU Publishing Data to the Internet Tutorial

Get the Adafruit MQTT Library

You’re going to need the Adafruit MQTT library found HERE.    If you’re new to adding libraries to your Arduino IDE,  you can read the article found HERE.

Get an Adafruit Account

The accounts are free.  Keep in mind, Adafruit is contributes A LOT to the maker community.   Throw them some business once in a while.  I do.

In any case,  you can sign up for an Adafruit account HERE.   Click the sign in button and you will be given and opportunity to create a new account. Create one and note your user name.

Access Adafruit IO Sign In

The web site is found HERE.   You will be given an option to sign it.  Sign in using your Adafruit account.

You will need to navigate to the screen pictured below to access your Adafruit IO Key.   Record this Key.  You will need it.

Connect NodeMCU to Your Computer

The connections are pretty basic.  Just connect the NodeMCU to your Computer.

Copy, Paste and Upload the NodeMCU IoT Publish Sketch

You will need to substitute:

  • Your router SSID
  • Your router Password
  • Your Adafruit Username
  • Your Adafruit IO Key
// Henry's Bench
// NodeMCU IoT Publish to Internet
// Modified from Adafruit Library Example

/***************************************************
  Adafruit MQTT Library ESP8266 Example

  Must use ESP8266 Arduino from:
    https://github.com/esp8266/Arduino

  Works great with Adafruit's Huzzah ESP board & Feather
  ----> https://www.adafruit.com/product/2471
  ----> https://www.adafruit.com/products/2821

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
#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 Adafruit IO *********************************/
/*  You will need and account - Its FREE  */

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "YOUR ADAFRUIT USER NAME"
#define AIO_KEY         "YOUR ADAFRUIT IO 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++;
  
}

View Your Serial Monitor Output

Open your Arduino IDE serial monitor.  The output should look something like the picture below.

Check For an Adafruit IO Feed

Go back to Adafruit.io and check your feeds.   A new feed should have been added for you.  Its name will be ‘myFirstValue’.

Create a New Adafruit IO Dashboard

Navigate to “Your Dashboards” and create a new dashboard called “MyFirstDash”

Add a Gauge to the Dashboard

Your new dashboard will be displayed, but it won’t have any ‘blocks’ for displaying data.   We will add one now.   Click the plus sign to create a block and select the gauge.

After pressing the ‘create’ button, you will be prompted to select a feed.  Choose ‘myFirstValue’.

Now you will need to enter some information about your gauge.  Set the min value to zero and set the max value to 10.  Click ‘CREATE BLOCK’.

Verify your Gauge

Your gauge will now be displayed on your dashboard.   The value should be changing about once a second.

Other Things to Try

  • If you have a smart phone, log into adafruit.io from its browser.   You should be able to see your gauge displaying the data published by your NodeMCU.
  • Create a Line Chart.  Use 15 for max Y value and 0 for min Y value.   Set your time to 0.01 Hour.   You should see a saw tooth representing how your data changed.
  • Add a Feed Block and see a log of your values.