IoT Projects

Connect your ESP8266 to any available Wi-Fi network

 1.jpg

The ESP8266 is a microcontroller developed by Espressif  Systems. Known as a WiFi Module, this microcontroller has the ability to perform WiFi related activities like Internet of things applications and home automation. Ranging in price and features, there are many types of ESP8266 modules available, but all of them are incredibly useful for IoT world.

Regardless of the IoT application you’ve developed, when using the ESP8266, you must set the WiFi credentials into the ESP8266’s firmware to establish the required connections and be able to send data to the cloud. This is one way to connect, but you can also build your own access point into the board making a universal firmware which will establish a connection in any network available just by pressing a button.

Requirements 

Step 1. Hardware Setup

Note: The Ubidots team made some modifications in the ConfigManager Library to implement a routine the begins the AP mode simply by pressing an external reset button.

Depending on the ESP8266 module you chooses, you may need to assign the reset pin using this library version. The default button settings are assigned to PIN 5; if you are using a NodeMCU you must connect the button into the D1 pin.

2.png

Step 2. Setup the Arduino IDE with your device

To start with any ESP8266 device you have to install the boards into the Arduino IDE, please follow the steps below to be able to compile the board.

Please download the Arduino IDE if you do not already have it.

1.- Open the Arduino IDE, select Files -> Preferences and enter the URL below Additional Board Manager URLs field. You can add multiple URLs, separating them with commas

http://arduino.esp8266.com/stable/package_esp8266com_index.json into

NOTE: If you’re a Mac user, please note that Arduino and File contain different drop down functions compared to Windows users. Also, you will need to install the following driver to be able to upload your NodeMCU.

3.png

2.- Open Boards Manager from Tools -> Board -> Boards Manager and install esp8266 platform. To simply find the correct device, search ESP8266 within the search bar.

4.png

3.- Select the ESP8266 module that you are using. In this case, we decided to use the NodeMCU 1.0 (ESP-12 Module). To select the board go to:

  • Tools > Board > Select the board.

5.png

Additionally, we need to be able to communicate with the NodeMCU, we also need to select the port com.

  • Go to Tools > Port >  Select the appropriate PORT for your device.

6.png

Also, to keep everything running fast and smooth – let’s make sure the upload speed is optimized to 115200. 

  • Go to Tools > Upload Speed > 115200:

7.png

4.- Go to the following repository to download the ConfigManager library. To download the library clicking the green button called “Clone or download” and select “Download ZIP“.

8.png

5.- Now back in the Arduino IDE, click on Sketch -> Include Library -> Add .ZIP Library

6.- Select the .ZIP file of ConfigManager and then “Accept” or “Choose

If successful you will receive the message below in the Arduino IDE:

9.png

7.- Next, go to Sketch/Program -> Include Library -> Library Manager and install the PubSubClient library. To simply find the correct library, search PubSubClient within the search bar.

10.png

8.- Now, reboot the Arduino IDE prior to upload.

9.- Once you have the ESP8266 platform and the libraries required installed, you have to install the Arduino ESP8266 filesystem uploader. Please follow all the installation steps of the repository and return back to this guide.

10.-  Once your uploader is installed, create a new sketch to work in and save it. Ours is called AP_ESP8266:

11.png

11. Next, go to the sketch directory and create new folder named data. 

12.png

12.- Once the directory is created, download this HTML file and attached it to the directory. This file will be used in the file system.

13.png

13. Next, we need to upload the file into the ESP8266 flash file system. To begin, make sure you have selected a board port, and closed Serial Monitor. 

14.- Select Tools > ESP8266 Sketch Data Upload menu item to start uploading the files into the ESP8266 flash file system.

14.png

When done, the IDE status bar will display SPIFFS Image Uploaded message.

15.png

15.- Now in the Arduino IDE, paste the code below. Once pasted, please assign the device and variable label desired by you, plus your individual, unique Ubidots TOKEN. If you do not have your Ubidots TOKEN, reference the following article.

Copy and paste the below code into the Arduino IDE including your specific device and variable parameters.

/*****************************************
 * Include Libraries
 ****************************************/
#include <ESP8266WiFi.h>
#include <ConfigManager.h>
#include <PubSubClient.h>

/****************************************
 * Define Constants
 ****************************************/
 
namespace{
  const char * AP_NAME = "Ubidots Access Point"; // Assigns your Access Point name
  const char * MQTT_SERVER = "things.ubidots.com"; 
  const char * TOKEN = "...."; // Assigns your Ubidots TOKEN
  const char * DEVICE_LABEL = "my-device"; // Assigns your Device Label
  const char * VARIABLE_LABEL = "my-variable"; // Assigns your Variable Label
  int SENSOR = A0;
}

char topic[150];
char payload[50];
String clientMac = "";
unsigned char mac[6];

struct Config {
  char name[20];
  bool enabled;
  int8 hour;
} config;

/****************************************
 * Initialize a global instance
 ****************************************/
WiFiClient espClient;
PubSubClient client(espClient);
ConfigManager configManager;


/****************************************
 * Auxiliar Functions
 ****************************************/

void callback(char* topic, byte* payload, unsigned int length){
  
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientMac.c_str(), TOKEN, NULL)) {
      Serial.println("connected");
      break;
      } else {
        configManager.reset();
        Serial.print("failed, rc=");
        Serial.print(client.state());
        Serial.println(" try again in 3 seconds");
        for(uint8_t Blink=0; Blink<=3; Blink++){
          digitalWrite(LED, LOW);
          delay(500);
          digitalWrite(LED, HIGH);
          delay(500);
        }
      }
  }
}

String macToStr(const uint8_t* mac) {
  String result;
  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);
    if (i < 5)result += ':';
  }
  return result;
}

/****************************************
 * Main Functions
 ****************************************/
void setup() {
  Serial.begin(115200);
  /* Declare PINs as input/outpu */
  pinMode(SENSOR, INPUT);
  pinMode(PIN_RESET, INPUT);
  pinMode(LED, OUTPUT);

  /* Assign WiFi MAC address as MQTT client name */
  WiFi.macAddress(mac);
  clientMac += macToStr(mac);

  /* Access Point configuration */
  configManager.setAPName(AP_NAME);
  configManager.addParameter("name", config.name, 20);
  configManager.addParameter("enabled", &config.enabled);
  configManager.addParameter("hour", &config.hour);
  configManager.begin(config);

  /* Set Sets the server details */
  client.setServer(MQTT_SERVER, 1883);
  client.setCallback(callback);
  
  /* Build the topic request */
  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
}

void loop() {  
  configManager.reset();
  configManager.loop();    
  
  /* MQTT client reconnection */
  if (!client.connected()) {
      reconnect();
  }
  
  /* Sensor Reading */
  int value = analogRead(SENSOR);
  /* Build the payload request */
  sprintf(payload, "{\"%s\": %d}", VARIABLE_LABEL, value);
  /* Publish sensor value to Ubidots */ 
  client.publish(topic, payload);
  client.loop();
  delay(5000);
}

16.- After the code contains your parameters, Verify the code within the Arduino IDE. To do this, in the top left corner of our Arduino IDE you will see the below icons.

  • Click “check mark” icon to verify any code.

17.png

Once verified, you will receive the message below in the Arduino IDE:

18.png

Next, upload your code into your NodeMCU.

  • Choose the “right-arrow” icon beside the check mark icon to upload code

19.png

Once the code is uploaded, you will receive the message below in the Arduino IDE:

20.png

Now your ESP8266 module is ready to establish the connection with any available network just pressing the button!

17.- Confirm: Open the Serial monitor to verify the connection status; press the button connected to your ESP module and hold for 5 seconds until you see the message “Starting Access Point” display in your serial monitor:

21.gif

18.- Now that the Access Point is created, you can establish the connection from your phone. Open the Wi-Fi access and select the network available called “Ubidots Access Point

22.png

Once the connection is established, it will redirect you to the side below. Set the your Wi-Fi parameters into the fields and press “save

23.png

19.- To verify if the connection is established properly go to the Serial Monitor:

24.gif

Now, return to your Ubidots accounts to visualize the device created and the data received:

25.png

Result

An Access Point that connects your device to any network available without setting the credentials into the  firmware; thus making a universal firmware that can be used anywhere.

Now it is your turn to give it a try. Sign up with Ubidots for Education for free today!

Facebook Comments

14 COMMENTS

  1. Update after 25min. It worked…my ESP had initially saved configuration and then gets automatically connected to my wifi. lol

    PS. Great tutorial:)

  2. Hello Shelendra,

    If you desire to used HTTP instead of MQTT, you just have to modify the sketch provided here with the one provided in the help center (http://help.ubidots.com/connect-your-devices/connect-an-esp8266-nodemcu-10-to-ubidots). Take in count that the section to be changed is the client configuration, the rest of the code like the network connectivity and sensor readings should be stay as is established in the code.

    If you have any additional question, you can post it in the Ubidots community(http://community.ubidots.com/)! 🙂

    All the best,
    Maria C.

  3. Hello, I have been trying to get this program to work. I need more information to help me understand what this is supposed to do. I assumed that the program would connect to a wifi router to connect to the internet. But when I connect to the “Ubidots Access Point“ I am told there is no internet access. If I then browse ubidots.com I get the UBIDOTS HTML page that asks for SSID and Password. What should I enter there?
    In the sketch there is a line; String clientMac = “”; Is this a variable I should fill out or a placeholder for the program? What MAC address should I use? I was thinking the Wifi router MAC address, maybe.
    I am able to program a Sparkfun ESP8266 Thing with this program, instead of the NodeMCU 1.0 (ESP-12 Module). I see the “pressed” and “starting access point” when I connect #5 to 3V3 on the Thing. Then nothing reliably happens. I am not getting internet access thru the access point, I can see it and select it with my cell phone. But it says internet is not available. I am new to this Arduino IDE but have been able to see a lot work. How does the program access the internet? More comments on the program lines may help me know where to look. Is there an article write up about this program that explains more? Thank you.

  4. Hi. thanks for the tutorial.
    I’m new to this, but how could I do to put other fields besides the ssid and password and use them in my sketch. Sorry for my english I’m from Colombia

  5. Hello Alejandro,

    Sorry but your question is not enough clear to me, which other fields would you like to add?

    All the best,
    Maria C.

  6. Dear Glen,

    The code provided in the blog post is used to establish a connection with any internet network available close to your device. Once you press the button and received the message “starting access point”, you will note that a browser is opened with a Ubidots page where do you have to assign the SSID (Network name) and password of the network. In that section, you have to add the parameters of the network desired to establish the connection, once the parameters are assgined your device should establish the connection without any issue and have to be updating data to Ubidots cloud.

    If you desire to burn the network parameters instead of using the device as AP, I highly recommend to this guide (http://help.ubidots.com/connect-your-devices/connect-an-esp8266-nodemcu-10-to-ubidots-using-mqtt).

    I hope this would help you.

    All the best,
    Maria C.

  7. Hi ,
    I have a problem with connecting my esp8266-01 to ubidots throught arduino uno , i tried many connections but nothing results

    Can you advice me please

  8. Hi,Maria how i can have a universal connection with Nodmcu and Blynk app which mean that if i open blynk app and it asks me to enter ssid and password of the router and connect with it.Its an home automation based project which currently working on it.

  9. Hey Sameer,

    Thanks for asking that.

    Indeed, the scope of this guide is to show how the ESP8266 can be used as an Access Point for provisioning purposes (i.e. set WiFi credentials); it’s not about how to connect a device with a blynk app. To gain additional insights into how you can connect devices to the cloud and deploy end-user friend App, check out the below resource to assist you in getting a device online and have a platform to build and launch your ideas.

    https://ubidots.com/docs/api/mqtt.html

Comments are closed.