Introduction: Build a Custom ESP8266 Arduino WiFi Library
The ESP8266 development board is a lot of fun to work with. This small and inexpensive WiFi capable microprocessor has rapidly become a very popular platform for prototyping and building IoT solutions.
Naturally, I've got in on the action with the latest version - the ESP8266 12-E Dev Kit. As I already have an Arduino IDE installed, I decided to make it my IDE of choice in order to quickly on-board myself and get familiar with the ESP8266 microprocessor.
The WiFi capability is no doubt (one of) the most appealing features of this board. But during the learning process, it became obvious that I had to make a few, not-so-hard changes to the Arduino-ESP8266 development environment in order to make my Wifi sketches a bit more manageable.
In this IBLE, we'll build a simple Arduino library to achieve the following objectives:
- Centrally configure and manage WiFi settings
- Use the library within a sketch that makes use of the WiFi capabilities of the ESP8266
- Avoid monotonous repetitions when configuring WiFi settings within Arduino sketches
- Avoid exposing the WiFi SSID and password settings via the Arduino sketches
Let's get started!
Step 1: Setting Up the Arduino-ESP8266 Development Environment
There are many sites on the web that talk about Arduino and/or the ESP8266. However, the resources listed below have been immensely helpful in getting me started.
- The latest ESP8266 12-E Dev Kit Development Board
- available from Amazon and other popular online retailers
- Acrobotic Industries has a nice tutorial on integrating the ESP8266 custom firmware with the Arduino IDE
- look for the section titled "Custom Firmware With The Arduino IDE" on their getting started page
- The latest version of the Arduino IDE
- this IBLE uses the latest version 1.8.0 for Windows 10 downloaded from the Arduino page
- A micro-USB cable to communicate and program the ESP8266 from a computer running the Arduino IDE
If all the steps have been completed without any errors, the Arduino IDE should have the ESP8266 board listed and also have access to all the related libraries and examples as shown in one of the screen shots.
Arduino Port Settings:
Note that the port identifier "COM3" may be different on your computer - make sure that the port indicated in the Windows Device Manager matches the port selected in the Arduino IDE.
- Windows 7/10 computers usually download and install the SiliconLabs CP2102 USB to UART driver when the ESP8266 is connected to the computer via the micro-USB cable
- Linux and Mac computers may require explicit installation of this driver downloadable from Silcon Labs
Get a proper micro-USB "data" cable - a wrong type of cable will leave you stranded for hours wondering why your computer won't recognize the ESP8266 despite installing the proper USB driver.
A cable that can work with an SD card reader is a better choice than the one that is primarily used just for charging phones or headsets.
Although this IBLE presumes that readers are familiar with developing projects on the Arduino platform, helpful beginner level hints have been incorporated wherever possible.
Step 2: Working With Arduino ESP8266 WiFi Code Samples
The images illustrate a standard WiFiWebServer example sketch that comes with the ESP8266 installation . Each of these WiFi examples requires that you update the WiFi settings before the code can be compiled and flashed to the ESP8266 board. Personally, this approach has the following issues:
Monotonous and repetitive WiFi settings
Needs no further explanation as you'll feel the monotony once you've worked through a few code samples!
Vulnerable WiFi Password
Leaves WiFi settings open and visible in code - I run the risk of accidentally (and unintentionally) publishing my WiFi settings to public domain should I carelessly share this code online (not very good!)
Scattered Password Management
I periodically keep changing my WiFi password - this means that I have to remember to carry these changes over to each and every one of my Arduino sketch files that uses WiFi settings
For these reasons, I decided to make my code base a bit more manageable thus enabling me to focus on learning how to program the ESP8266 instead of having to manage WiFi settings in code.
There may be other solutions - this is just one way of making life easier
Subsequent steps described in this IBLE are optional - you can still manage your WiFi settings in each of the Arduino sketches
Regardless, coding standards in the software industry are rapidly tightening - keeping information such as passwords separate and invisible from program code, once considered a best practice is fast becoming part of the secure and required coding practice guidelines!
Step 3: Separating WiFi Settings From Code
To keep things simple, we'll integrate our WiFi settings within a simple custom Arduino library and deploy it into the IDE.
The Arduino website has resources in case readers want to get started with the basics on custom libraries.Therefore, the depth of this subject is not within the scope of this IBLE.
Besides, the next steps demonstrated here are simple and do not require additional resources other than a humble text editor such as Notepad (on Windows).
Custom Library Prerequisites:
The first step is to decide on a name for our custom library - we'll call ours MyWifiCentral.
With the name decided, we'll design and build the following required components of this library:
- MyWifiCentral.h - the header file
- MyWifiCentral.cpp - the c plus plus (or cpp) file
- Save both files to a library folder by name MyWifiCentral
Both files will be coded using some of the simplest concepts of C++.
You can name your library anything as long as it conforms with the Arduino naming guidelines, but the names of the header file, the CPP file, and the folder must match with the name of the library
Keep in mind that too specific a library name can cause unintended name collisions at the time of deploying a custom library
Naming the library ESP8266Wifi will be in direct conflict with the fact that an Arduino library with that name already exists!
On the other hand, a name such as MyWifiCentral eliminates collisions by the very personal nature of how it sounds thus making it more suited for your personal development environment.
In addition, the fact that the name does not contain "ESP8266" indicates that this is a library designed for general use, not specifically for the ESP8266. There are other Arduino WiFi libraries that can benefit from such a general feature.
Step 4: Building the Header File
Very simply, a header (or H) file is a bare bones representation of the library you plan to build. The code markers <1 through <6 describe the various components of the header file.
- The features of this library are collectively referred to as variables and methods
- The resources this library will have access to (Example Arduino.h) will also be listed in this header file
- The Notepad editor does not support formatting - the easiest way to format the code is to type it in the Arduino editor and then copy-paste it into Notepad
- When saving the .H file in Notepad, make sure that the file type is set to "All files(*.*)" to prevent the file from being saved with a ".txt" extension
SAVING LIBRARY FILES:
- Create a new folder at a convenient location on your computer and name it MyWifiCentral
- As described in the preceding steps, the name of this folder must be a (case-sensitive) match with the name of the library
The completed header file has been attached here below.
Next, on to the CPP file.
Step 5: Building the CPP File
The CPP (or c plus plus) file materializes the actual custom library. All attributes and resources listed in the header file created in the previous step are fully defined in the CPP file.
The visual contains full comments that help describe each part of the library.
The attached file contains the code that can be deployed to the Arduino environment in subsequent steps.
- Each method in the .CPP file is prefixed with the "MyWifiCentral::" identifer indicating that all methods are part of the MyWifiCentral custom library
- As noted in the previous step, make sure that the file is formatted right and that the file is saved with a ".cpp" extension
- Save the .CPP file alongside the .H file in the MyWifiCentral library folder created in the previous step
NOT TO FORGET!
- Make sure to set the WiFi settings to match with your WiFi network before proceeding further
Step 6: Deploying the Library to the Arduino IDE
To deploy the custom library into the Arduino environment, follow these steps:
- Close all open Arduino IDE windows
- Locate the Arduino libraries folder under the Arduino program folder:
- If Arduino has been installed as a Windows program, the path is usually C:\Program Files\Arduino\libraries
- In this case, the Arduino program has been downloaded as a non-admin install and unzipped to the My Documents folder
- Once the location has been determined, simply move the entire MyWifiCentral folder under the libraries folder
The accompanying visual illustrates the custom library deployment. At this point, the library has become part of your Arduino environment.
The next step is to confirm that the library is available for active use via the Arduino IDE.
Step 7: Including the Custom WiFi Library in a Sketch
Begin by opening up the Arduino IDE. We'll need an Arduino sketch to use our custom library. For that, we'll start of with a standard example named WiFiWebServer that comes with the ESP8266 firmware installation.
Open this sketch by navigating through the File menu item like so:
File > Examples > ESP8266WiFi > WiFiWebServer
The example sketch will open up in a new Arduino window.
Next, include the custom library into the example sketch using the Sketch menu item:
Sketch > Include Library > MyWifiCentral
A new line will be automatically added to the top of the sketch and the header file MyWifiCentral.h built in the preceding steps will be included in the sketch.
The include statement confirms that the sketch has access to the methods of the MyWifiCentral library
Step 8: Utilizing the Custom Library Methods
To put the custom library to real use, we'll replace the standard WiFi connection code with the methods from our custom library.
The first visual compares changes to the code alongside definitions in the header file.
On line #13 we load the library into memory my declaring an object instance:
On lines #14 and #15 we replace the hard coded placeholders for ssid and password with our library methods ssid() and passcode() respectively:
char* ssid = myWifiCentral.ssid(); char* password = myWifiCentral.passcode();
Next, we remove the const (short for constant) keyword on both these lines .
Because the very purpose of the custom library is to make the WiFi settings variable and subject to future changes. Therefore, the library methods ssid() and passcode() return char*. Assigning char* to const char* will result in an error when the Sketch is compiled. Therefore, the const keyword has to be removed!
That's it! All we need to do now is to save and compile the sketch to confirm that there are no errors. You can give the sketch any name as long as it does not begin with a number. In this case the new name begins with an underscore followed by a number.
To compile the sketch, simply click on the Check mark button on the menu bar as shown. If all steps have been followed correctly, the status bar at the bottom of the IDE window should display a "Done Compiling" message.
Next, we'll flash the compiled sketch to the ESP8266 board.
Step 9: Flashing the Sketch to the ESP8266
Before flashing the sketch, make sure that:
- the ESP8266 board is firmly connected to the computers' USB port via the micro-USB cable
- the port is correctly selected from the Tools > Port menu item
In this case the port is set to COM3, but it may be different on your machine.
To flash the sketch to the board, click on the Compile button as shown. If the computer is connected to ESP8266, the sketch should be downloaded to the board in a few seconds. During this time, the Blue LED on the ESP8266 will flash rapidly.
In addition, the window at the bottom of the Arduino IDE will indicate the progress of the flashing process.
Now we're ready to test the functionality of the Sketch and the custom WiFi library!
Step 10: Testing the Wifi Capability
Before proceeding further, refer to the documentation at the top of the sketch. This sketch makes the ESP8266 perform the following functions:
- Connect to the Internet via the configured WiFi settings (provided our custom library has no errors!)
- Get an IP address and start up a basic web server that becomes accessible via your favorite browser
Once the IP is assigned, we can open up the browser and toggle the on board Blue LED by typing in a couple of URLs
To view this test in progress, open the Serial Monitor window using the Ctrl+Shift+M combination on your keyboard. On the bottom right of this window, make sure that the baud rate is set to 115200.
If the WiFi settings have been configured correctly in the custom library, the ESP8266 should be able to connect to the internet and get an IP assigned to it.
Using the IP, you can toggle the LED ON or OFF by typing in the URLs in your browser window .
The testing sequence is illustrated by markers <1 through <6 in the visual above.
Step 11: Observations, Standard Code Vs. Managed Custom Library
Finally, we summarize our observations by running a side by side comparison of the standard code and the managed custom library.
The most significant observation is password security:
- Standard code lays bare your WiFi credentials whilst managed code has no direct references to it - makes the solution a lot cleaner!
Next thing absent is the repetitive WiFi code:
- Should the WiFi settings change, every one of your sketches will need manual edits
- With managed code, all you do is change your WiFi settings in the CPP file just once, restart your Arduino IDE, compile and flash the sketch once more into the ESP8266!
The Counter argument would be:
I'll be using one sketch at a time! What's the big deal?
But which one? What if you have 20 sketches and only two of them are actively in service on a couple of ESP8266 chips? Will you make changes to just these 2 only to forget the remaining 18?
Easier a change in one central location than hunting down each and every WiFi related sketch!
Happy coding, have fun and thanks for reading my IBLE!
kalya made it!