ESP8266 : An IoT System on Chip

Mobile Weather Sensors Using ESP8266 – Phase 4: Mobile App Gadgets

speedAs I found myself staring at the information collected by the Mobile Weather Sensors, searching for ideas on how to best present the information visually, the reality hit me….

While this is a decent App for collecting information on-the-go, it data itself and the environment it is collected in does not lend itself well to real-time visualizations.

Two problems…

First of all, there is a significant lack of visibility of the smartphone screen outdoors. You could have developed the most magnificent display, with eye-catching vividly colored displays. Great inside, but the screen appears almost blank when taken outside in the direct sunlight. And that is where this mobile sensor system is most of the time.

The other issue is the slow moving, almost static values of the sensors. Temperature, humidity and pressure do not vary much moment by moment.

Despite the limited usefulness of GUI displays for this application, I decided to throw a few in anyways.

There is always something to be gained…

You see, these added screens can be used in any App. Providing quick and easy-to-implement options to display your data.

Since this App has been structured with a standard web page format (html to render the GUI, CSS to style and JavaScript for processing), JavaScript charting is the obvious and most logical choice for real-time visualizations of the sensor data.

The good news is that there are many options available.

This site provides access to 15 different Javascript Charting Libraries. D3.js seems to be the crowd favorite. It has lots of flexibility. But I did find it somewhat more complex to get started with, and the charts were not responsive to different screen sizes.

So I chose Chart.js. Why? It was quick and easy to implement. Yup, their claim actually rang true for this application “Simple, clean and engaging charts…”. And yes, they are also very responsive to the smaller smartphone screens.

A Speed Chart

The first chart displays velocity. It is essentially a speedometer. The code simply updates and displays the last 10 speed values received from the GPS sensor. The current reading is displayed as the next point on the right side of a line chart. This new speed value pushes the other 9 readings one position left on the chart, with the left-most reading dropping off the chart.

As I mentioned, the smartphone display is nearly impossible to view outdoors in the direct sunlight. For a test of this real-time chart, I simply held my phone upright and rode my bicycle down the street. Using an independent Garmin GPS device for reference, I rode at varying speeds to confirm that the smartphone app display values correlated.

The current speed value (mph) is also displayed under the chart.

I was pleased to observe the accuracy of the display.

Perfect Widgets

No, there really is no such thing as “perfect”. But I have gotten a few gadgets from Perfect Widgets which have now been added to this application.

First, I tested a compass widget, using only the “heading” value from the smartphone’s GPS sensor. After reviewing a recording of the display, it became apparent that considerable lag occurred between a change in direction. The audio was recorded along with the display. While the sound quality is not great, it clearly illustrates the lag in responsiveness when direction changes.

The lag could easily be overcome my using the Android magnetometer sensor in place of the GPS heading value. But since we are focusing on the real-time sensor displays, that change will be pushed off into a future upgrade.

Clock Widget fed from GPS Sensor

Sure, you can readily extract the time from the phone or even pull up a timeserver. But for this Application, let’s use the GPS time-stamp.

So now a dynamically changeable clock image was needed…

Once again, I looked the the “Perfect Widgets” library for a clock gadget. In this case, 3 sliders must be updated to maintain the clock. One for each of the moving clock needles (Hours, Minutes, Seconds). Minutes and seconds are easy, since the are extracted from the Date object every time it is refreshed (a value from 0 to 59).

But the same hour is returned for 60 minutes. As we all know, analog clocks move smoothly minute-by-minute from 1 hour to the next. And so we must add a fraction equal to the current minute divided by 60 to get the current “partial hour”. The Date object also returns the hour as a number between 0 and 23. This must also be adjusted for our 12-hour analog clock widget.

var d = new Date(position.timestamp);
se.setValue(d.getSeconds(),false);
mn.setValue(d.getMinutes(),false);
if(d.getHours<13) {
    hr.setValue(d.getHours()+(d.getMinutes()/60),false);
}
else {
    hr.setValue(d.getHours() - 12 + (d.getMinutes()/60),false);
}

Here is what the gadget looks like…

Small Yet Useful App Update

 Some times I have wanted to use the smartphone App alone.

Without the ESP8266 running…

In those cases, I found it necessary to record sensor data while omitting the ESP8266 information. This was particularly useful in times when it was easier to check things out without taking the extra steps to activate my ESP8266 module.

The simple solution was to add a button to the  top of the navigation bar to toggle enabling/disabling the use of the ESP8266 in the log file. The following screenshot shows this added button in the default “ESP used” state.

appupdate

Conclusion

We now have a few real-time visual representations of the Mobile Sensor Data. There are many more possibilities for the creation of visual displays. Here again is the link  that provides a reference to some of the best JavaScript charting tools available.

Want to see the code behind the charts I have present? The code developed thus far (Phases 1-4 of this project) is accessible on Github here.

I hope you find these tools useful in your projects…

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

Mobile Web Sensors Using ESP8266 – Phase 3: Google Map Visualizations

This is a continuation of the “Mobile Web Sensors Using ESP8266” series.

Mobile Web Sensors Using ESP8266 – Phase 1
Mobile Web Sensors Using ESP8266 – Phase 2

Google Map and Excel Visualizations

This is where things get interesting. I just got back from a yoga class. This was a simple 4 mile bicycle trek across town; a perfect opportunity to collect some data using the Mobile Sensor System.

For this test run. a USB battery was used to power the ESP8266-12 based device. I simply plugged a USB cable in to powered it up, stuffed it into a fanny pack, connected my Android phone to the device’s WIFI signal and started the App.

I could tell it was working by observing the UTC time change rapidly on the phone app’s GUI. Another look at the display upon arrival at my destination confirmed that the data collection was still  running. Success!

But the raw data file was not in a very human readable form:

timestamp,lat,lon,spd,alt,btmp,dtmp,bp,dh,syst,sysh,syslp
1439830613611,34.2943768,-118.8439855,null,null,80.6,57.79,29.23,50.70,120,30840,37
1439830614632,34.2943768,-118.8439855,null,null,80.6,57.90,29.23,50.59,121,30840,38
1439830615646,34.2943715,-118.8439865,null,null,80.24,57.90,29.23,50.59,122,31280,39
1439830618611,34.2945713,-118.8441038,0,180,80.24,57.90,29.23,50.50,125,30832,42
1439830619607,34.2945664,-118.8441046,0,180,80.24,57.90,29.23,50.50,126,31280,43
1439830621616,34.2945921,-118.8441143,0,181,80.42,57.90,29.24,50.50,128,30840,45
1439830625549,34.2945638,-118.8440880,0,175,80.42,57.90,29.23,50.40,132,30840,49
1439830625649,34.2945638,-118.8440880,0,175,80.42,57.90,29.23,50.40,132,30840,49
1439830627653,34.2945510,-118.8440810,0,175,80.60,57.90,29.23,50.40,134,31280,51
1439830630563,34.2945510,-118.8440807,0,175,80.60,58.0,29.23,50.79,136,31280,53
1439830631631,34.2945508,-118.8440805,0,175,80.60,58.0,29.23,50.70,138,29112,55

Collecting this sensor data and saving it to a file was an important step. And now, the next thing to do was to present the data in a visually useful format. I had intended to import the CSV file containing the data into Excel. However, while creating custom Excel spreadsheet charts and graphs was a quick and simple method of visualizing the data, my first approach was to seek out possible on-line tools already available for this purpose.

So the search began. It did not take long to find a way to import the spreadsheet into google maps. But would it be simple? would I have to crop out the latitude and longitude values from my data file for the mapping program to use it?

I was surprised at how easy it was…

The web site was www.gpsvisualizer.com.

After opening a web browser to that site, you simply click on “Choose File” and select the csv file created from the Android App.

Then, just click on “Go” and a satellite map with the tracks from the data appears.

Googlemap2

No changes to the csv file were needed. What a great tool! It figured out the appropriate data fields for lat & long and overlay-ed them on the map with a red trace.

Okay, what other options are available with this “GPS Visualizer”?

gpsvisualizer1

The “Choose an output format” revealed several image options as well as an elevation profile. The elevation profile looked like it might be interesting…

But I noticed the default units were meters. Being a US resident, feet are preferred. These units, along with many other options, were select-able by clicking on the link “Profiles (elevation,etc.)”.

Googlemap2-3

Here, you could set the X and Y Axis plots to any of the fields shown above. I was stoked to see the list included “Heart rate”. My Heart rate sensor will be added to this project at some point soon. Plotting it against elevation change should present some interesting results.

I created a test plot of elevation over distance traveled along this 4-mile route. While any field could be selected, this sample plot colorizes the speed. Again, the plot shows the speed to generally stay below 20 mph, typical for city street bicycling.

Googlemap2-4

That steep slope (and slow speed–red plot color) at about the 3.5 mile distance correlates with the only significant hill climb along the route. Nice to confirm that the data collected makes sense!

But then it hit me. Nice to see that this “GPS Visualizer” can portray the GPS data in charts…but what about the customized sensors? Like temperature, barometric pressure, and the relative humidity? Could this tool also support these unique fields in the plots?

I was pleased to discover that the answer is…

YES!

Note that the last field in the drop-down above is “custom”. Selecting this option allows you to enter any field name. Those are the field names in the first row of the CSV file of the data captured with our mobile sensor system. I selected “humidity” for the y-axis as a test case with a colorization of the speed.

Googlemap2-5
I was surprised to see the drop in relative humidity from the start to the finish of the ride. It was probably due to the sensor drying out someone with motion. It had been in the controlled, air conditioned environment of the yoga studio at the start and was then exposed to our dry Southern California air.

Looks like this “GPS Visualizer” tool will come in handy to produce quick charts from the sensor data.

Visualizations Using Excel

While most everyone if familiar with excel, this discussion would not be complete without a few chart example produced from the raw CSV file.

But when the CSV file was opened using Excel, a couple of issues had to be addressed first before plotting the data.

  1. The timestamp field was shown in scientific format. this was corrected by changing the format from “General” to “Number” with 0 decimal places.
  2. The first 3 entries for the spd and alt fields were “null”. These were changed to the value of the 4th entry, the first one with valid values. Note: these values came from the GPS API in the Android code. Neither one accurately represents the actual speed and altitude. Yet the google plots were accurate. This problem was due to assuming the parameter units incorrectly:
    1. The altitude was reported in meters. Since we were looking for feet, it must be converted using the scale factor
      of 3.28084 feet/meter. This has now been corrected in the Android App code.
    2. The speed is reported in meters per second. Since we were looking for MPH, it must be converted using the scale factor of 2.23694 miles/hour per meter/second. This has now been corrected in the Android App code.
    3. For the evaluation of the data collected in excel, two columns were added to perform the conversion: MPH and altitude.Problem with the speed, however, is that many of the samples returned 0 meters/sec as the speed. To solve this, I may introduce a new speed algorithm to the mobile app code to convert two GPS coordinates to distance. This distance, along with the change in timestamp values would be used to calculate speed.
  3. The “dtmp” values (temperature as read by the humidity sensor) are incorrect. The temperature starts at 57.79 degrees while the temperature read by the barometric sensor starts at 80.6. It looked to me like the conversion is missing the “plus 32” in the ESP8266 code. But a review of the code did not reveal any problems. The conversion did include the required “plus 32). I would like to hear from anyone else using the DH22 to see if they are all off in temperature or it is just my sensor that is incorrect. For now, the DH22 temperature reading will be discarded as invalid.

The first thing I tried was to plot the coordinates over the ESP system time(seconds since reset).

excel1

Problem with this plot is the relatively small change in latitude and longitude. It essentially looks like a straight line. This was easily rectified by plotting the latitude and longitude separately.

exce2.
Okay, and now let’s plot the elevation again, like we did with the GPS visualizer.

exce3
Yes, this does look the same as the GPS Visualizer. Except colorizing the plot with a 3rd parameter is not an option. Even with just these few sample plots, I am definitely liking the visualizer of standard Excel charts.

Conclusion

As you can see, there is more than one option available to visually represent data collected with IoT sensors. And it is worthwhile to investigate tools that may be readily available before attempting to build your own charts, from scratch. Here we just explored a fraction of what is available for this purpose.

Phase 4: Mobile App Gadgets is next. In that post, I am going to add some visualizations to the Android application. This will add a real-time visual element to the crude data windows created in phase 1.

I hope you find this information useful…

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

Mobile Web Sensors Using ESP8266 – Phase 2: Data Recorder

Collecting data from sensors and displaying them on your phone while you are on the go is great, but without a storage method the data is lost. Sure, you could snap a picture of the display, but that is just a frozen set of data points. And not in a format suitable for data analysis.

I thought this might be a difficult task. But much to my surprise, it was amazingly simple to save data to a non-volatile file on the smartphone’s SDcard.

Here is how it’s done…

Starting with the data collection framework from Phase 1 of this Mobile Sensor series, we now add code to record the sensor data as it is sampled. To make things simple yet useful, each data set will be saved in CSV (comma separated value) format. The file, consisting of a series of data sets, can then easily be imported as an excel spreadsheet.

The FileSystem API will be used to open and save the data to an Android device SDcard. Fortunately, the code developed for Phase 1 of this project already has the required permissions included so we can gain access to the OS file system. First, the projects res/xml/config.xml must include the following feature:

<feature name="File">
    <param name="android-package" value="org.apache.cordova.file.FileUtils" />
    <param name="onload" value="true" />
</feature>

And the AndroidManifest.xml file must include the permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Since there are two sources of inputs (the gps sensor and the ESP8266), two CSV strings are built at the time the data is received. The GPS CSV string is added to the “onGeoSuccess()” callback:

gpssavestring = position.timestamp + "," 
              + "," + long.substring(0, 12)
              + "," + latt.substring(0, 11) 
              +,"," + position.coords.speed
              + "," + position.coords.altitude;

Five geo values are to be saved: UTC when coordinates were received, lat, long, speed and altitude.

Likewise, a CSV string is created each time the weather sensors are updated in the function updateWeatherSensorData():

 sensavestring = "," + thedata.B_Temperature 
               + "," + thedata.DH_Temperature
               + "," + thedata.B_Pressure
               + "," + thedata.DH_Humidity
               + "," + thedata.SYS_Time
               + "," + thedata.SYS_Heap
               + "," + thedata.SYS_Loopcnt + "\n";

Finally, the two CSV strings are concatinated and written to a file on the SDcard using the File System API:

//--------------------------------------------
//Update Save Data to File 
//--------------------------------------------
function saveData2File() {
	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
    fileSystem.root.getFile("mydata/dsa.csv", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
    if(gotFileWriter.started == undefined) {
        gotFileWriter.started = 0;
        gotFileWriter.tosave = "initial";
    }
    if(gotFileWriter.started!=1234) {
        if(writer.length>0) {
            writer.truncate(0);
        }
	    writer.seek(0);
	    writer.write("timestamp,lat,lon,spd,alt,btmp,dtmp,bp,dh,,syst,sysh,syslp\n");
        gotFileWriter.started=1234;
    }
    if(gotFileWriter.tosave != gpssavestring) {
        save2filestring = gpssavestring + sensavestring;
        gotFileWriter.tosave = gpssavestring; 
        writer.seek(writer.length);
        writer.write(save2filestring);
    }
}

Note that the data is saved to a hard coded path/filename on the Android Smartphone SDCard (mydata/dsa.csv). Before running this project, the folder mydata must be created on your phone’s SDCard.

The code for mobile data sensors with data recording is available on Github here.

Conclusion

That’s it. This mobile sensor project now saves the data captured to an SDcard file. It’s time to take the system out on a mobile excursion. I’m going to take this project out for a ride on my bicycle now to collect some data samples. In the next phase, the data collected will be imported into excel and google maps to produce more visually appealing representations of the information.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

ESP8266 Amazon Web Service (AWS) API

Using AWS Cloud services for the Internet of Things back-end can be beneficial for applications of all sizes, small to very large. Small and simple DIY home projects can leverage the power of AWS services while staying within the no-cost free-tier level of usage. And the larger systems, with many sensor and control devices can take advantage of the reliability and virtually unlimited scalability that AWS offers.

If you have an urgent need for an AWS API for the ESP8266 right now, I have placed it on GitHub here.

My initial interest was in some simple home automation projects. And I was planning to use the ultra-cheap ESP8266 to push my sensor readings up to the AWS database storage services and the receive control commands from the AWS Lambda service.

But there was a problem.

I could not find an API targeted for the ESP8266 in the AWS SDK. Yet the solution was right there….within the SDK. All that had to be done was to adapt one of the currently supported micro-controller APIs for use with the ESP8266. After reviewing the APIs offered, the one that had the most in common with the ESP8266 was the Spark Core API.

My first step was to build and test the sample code for the Spark Core (now known as “Particle”). Fortunately, I had a Spark Core device available for this purpose. While there were a few issues with the SDK library which caused the compile process to fail, it did not take long to get working Spark Core/AWS sample application up and running. Code changes included:

AWSClient2.cpp         
Change: Declarations missing for AWS_DATE_LEN2, AWS_TIME_LEN2 and HASH_HEX_LEN2

AmazonDynamoDBClient.h
Change: Added "MinimalList<MinimalString > SS;" to the class "AttributeValue"

After correcting the SDK code, the compile completed successful. And the subsequent testing on my device confirmed the functionality of the API, interfacing flawlessly with AWS.

The next step was to compile this SDK code with the Arduino IDE for ESP8266.

Since both the Spark Core and the Arduino IDE for ESP8266 used the sketch/library model, the structure of the API did not have to be revised. The device specific library code was put in the  Esp8266AWSImplementations.h/.cpp files.

The most significant thing missing from the ESP8266 base library was a time server. The function “updateCurTime()” was added to the Esp8266AWSImplementations.cpp file to fill that void. That function attempts to retrieve the current time in JSON format from a yahoo timeserver. While the timeserver URL works properly from a web browser, an error is returned from the ESP8266 “http GET” request. But, fortunately, the http error response includes the current GMT time. Since that is what is needed for the AWS API, it is simply scraped off the response string and used to build an AWS request.

I also revised the AWS demo program (designed for the Spark Core) to eliminate the need for a switch trigger. Instead of initiating an AWS request from the change in state of a switch, the AWS API interface is tested continuously in the sketch’s loop() function.

This is what the demo sketch does:

setup()
- connects to your local Wifi and initializes an AWS database client.
- a web server is also started, but is not used for this demo sketch
 
loop()
- first gets the current RGB values from a dynamoDB table
- then sets the dynamoDB table RGB values to an increment of the value from the 'get'

The next step

With this framework, you can exploit the low cost implementation of AWS Cloud-based IoT systems of all sizes. Sure, many applications can be handled locally within the confines of your network enabled ESP8266. But that solution has limited scalability, and is subject down-time associated with power outages and system crashes.

Here are just a few applications that come to mind for AWS Cloud IoT systems for the DIY explorer:

  1. Home Security: Apply some redundancy to your local system by pushing your sensor values and even camera images up to the AWS Cloud at a consistent interval. Then, apply ITTT (if this then that) logic running on your AWS account to take action (send text or email or phone someone or sound an alarm) when a sensor detects an intruder, power outage (sensor updates stopped), fire, smoke, water leak, ect.
  2. Hot attic: When an attic sensor (sent to the AWS Cloud) exceeds a trigger temperature, the AWS Cloud sends a command to your local ESP8266 to turn on a fan to vent the heat.
  3. Water usage: If the water flow meter readings (sent to AWS regularly from an ESP8266) senses unusual water flow, a signal is sent by the AWS Cloud to an ESP8266 based control valve to shut the water off. This sort of thing can be scaled to distribute the monitoring and control to each and every valve and faucet in the house, so that the problem is isolated to it’s source.

Conclusion

There are many more IoT applications that can marry the ESP8266 with the AWS Cloud computing resources. Almost anything you can imagine can now become a reality; and for a tiny fraction of the cost needed just a short time ago. The API presented here brings the low-cost network enabled sensor/control power of the ESP8266 SoC to the all encompassing AWS Cloud.

I hope you find this information useful.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

Mobile Weather Sensors Using ESP8266

mtbike

Mountain Biking in the local trails in my Southern California home has kept me both reasonably fit while maintaining a close connection with nature. As you roll through many of the trails here, the terrain varies significantly…from the darker shadows of the canyon floors to the wide-open sun exposed ridge-top fire roads. And with these changes there are noticeable variations in the temperature and moisture in the air.

So I got to thinking…

Wouldn’t it be interesting to track these variations as the trail climbs up the mountain face and descends down the other side? Sure, there are gadgets available that do this kind of thing. Like tracking your position, speed, altitude and heart-rate. If you really look around, you might even find one that reports the temperature. Not cheap, but they are available.

Hmmm… Let’s see, can we make a do-it-yourself alternate? A solution that is much cheaper than the cost of a commercially bought product?

This looked like a perfect task for the super low-cost ESP8266 and a few inexpensive sensors. Coupled with a data link to a smartphone, you got a mobile platform tailored to track just about anything. A system that can be tailored to your exact needs. All at a fraction of the cost of a commercially available product, if you can find one meeting the specifications you want.

Here is what I came up with…

My initial design simply collects data samples and saves them to a file on my Android SD Card. This file is then transferred to a PC for visual representation with excel. Later, I intend to add screens to the Android App to display the data on phone. But first, a data collection and storage system was needed.

After thinking about how I wanted to implement these features, the project was broken down into several phases. This post addresses phase 1. Yep, this project is “work-in-progress” and phase 1 is as far as I have gotten…so far. Check back to this blog soon for updates that cover the subsequent elements of this Application as they are developed. Once completed, the “phases” that following will be turned into links.

Phase 1: Mobile Data Collection

Okay, to get started, the scope of the data collection set needed to be defined. First I made a list of the information to collect. While subject to change, initial list includes:

Parameter Units Device
1 Temperature Degrees F ESP8266 Sensor (BMP085)
2 Barometric Pressure in Hg ESP8266 Sensor (BMP085)
3 Humidity Percent ESP8266 Sensor (DHT22)
4 Speed mph Smartphone GPS Sensor
5 Altitude feet Smartphone GPS Sensor
6 Heading Degrees Smartphone GPS Sensor
7 Latitude Degrees Smartphone GPS Sensor
8 Longitude Degrees Smartphone GPS Sensor
9 Heart Rate beats per minute Garmin Ant+ HRM
10 GPS Timestamp ms Smartphone GPS Sensor
11 ESP8266 Run-time seconds ESP8266
12 ESP8266 Heap Bytes ESP8266
13 ESP8266 Iterations Loops ESP8266

The Mobile Smartphone App

The smartphone App is obviously the heart of this project. In this first phase, it must gather data from 3 different sources. But that’s not the only thing to consider. Aside from the Smartphone App, the project also uses an external micro-controller. So the hardware and software design of the ESP8266 system also needs to be developed. But let’s start with the Smartphone App and it’s 3 sources of data.

  1. Phone’s Internal GPS Sensor
  2. ESP8266 Micro-controller
  3. Garmin Heart Rate Monitor

But how do we do it? What do the hardware and software components look like to make this a reality?

GPS Data

My first thought was to add a GPS sensor as an ESP8266 sensor input. But then the obvious hit me… The Smartphone has a built-in GPS Sensor. Why not use it instead of added a redundant capability to the ESP8266 system?

Thanks to the geolocation API included with HTML5, access to the Smartphone GPS data is easy. Starting with the default Native Cordova Android App, the App code (Javascript/jQuery) needed to collect location information from the Phone’s GPS receiver is minimal.

HTML to display the sensor data (simplified, styling excluded):

1. Temperature <p id="tempBaro"></p>
2. Barometric Pressure<p id="presBaro"></p>
3. Humidity<p id="humidity"></p>
4. Speed<p id="Speed"></p>
5. Altitude<p id="Altitude"></p>
6. Heading<p id="Heading"></p>
7. Latitude<p id="Lat"></p>
8. Longitude<p id="Lon"></p>
9. Heart Rate<p id="HeartRate"></p>
10. GPS Timestamp<p id="GpsTimestamp"></p>
11. ESP8266 Run-time<p id="systime"></p>
12. ESP8266 Heap<p id="sysheap"></p>
13. ESP8266 Iterations<p id="sysloop"></p>
Status:<p id="msg">Ok</p>

Javascript/jQuery to collect and update the sensor data display:

 options = {
     enableHighAccuracy: true,
     timeout: 1000,
     maximumAge: 0
 };
 
 //------------------------------------------
 // Functions triggered after page loaded
 //------------------------------------------
 jQuery(window).load(function () {
     navigator.geolocation.watchPosition(onSuccess, onError, options);
 });

 //------------------------------------------ 
 // onSuccess Callback
 //------------------------------------------
 function onSuccess(position) {
     var latt = position.coords.latitude.toFixed(7).toString();
     var long = position.coords.longitude.toFixed(7).toString();
     $("#Lat").html(latt.substring(0, 11));
     $("#Lon").html(long.substring(0, 12));
     $("#Speed").html(position.coords.speed);
     $("#Altitude").html(position.coords.altitude);
     $("#Heading").html(position.coords.heading);
     $("#GpsTimestamp").html(position.timestamp);
     updateWeatherSensorData();
 }
 //-----------------------------------------
 // onError Callback 
 //-----------------------------------------
 function onError(error) {
     //Do nothing (ignore data set) or display message here if an error occurs
     var element = document.getElementById('msg');
     element.innerHTML = 'Failed GPS monitor' + '<br />';
 }

 

The “options” structure sets the GPS configuration. The “enableHighAccuracy” field must be set to true. This tells the geolocation API to use the phones GPS Sensor. If it is set to false, the API will use the 4G or WIFI connection to determine location. Believe me, you do not want that active, it is very slow. It also will not work on the trail when you are out of cell tower range. The timeout is set to 1 second, setting the maximum time to acquire a location from the GPS sensor. Finally, the maximumAge sets the time to use a cached value before acquiring a new location from the sensor. Setting this to zero forces a new acquisition every time a position change is detected.

Once the Cordova web-based App page (index.html) has been loaded, the geolocation “watchPosition” callback is registered. Subsequently, every time the phones’ GPS sensor detects a change in position, the “onSuccess” callback function is executed. The “onError” callback is run if an error is detected.

navigator.geolocation.watchPosition(onSuccess, onError, options);

You can do anything you want with the data in the “onSuccess” callback. This example simply displays the values on the App window by setting the html for the objects by id to the GPS Sensor measured value. As noted, the next phase of this project will log these values to an SD card file on the Smartphone.

ESP8266 Data

The last line of the “onSuccess” callback executes the function “updateWeatherSensorData”.

 //--------------------------------------------
 //Update WeatherSensor Data
 //--------------------------------------------
 function updateWeatherSensorData() {
     requestURL = "http://192.168.22.1:9703/?request=GetSensors";
     if ( typeof updateWeatherSensorData.timeout == 'undefined' ) {
         // It has not... perform the initialization
         updateWeatherSensorData.timeout = 0;
     }
     //Get Weather Sensor Value
     $.ajax({
         url: requestURL,
         error: function(error){
             if(updateWeatherSensorData.timeout++ <10) {
                 setTimeout(updateWeatherSensorData, 1000);
             }
             else {
                 updateWeatherSensorData.timeout = 0;
             }
         },
         success: function(thedata){
             $("#tempBaro").html(thedata.B_Temperature);
             $("#presBaro").html(thedata.B_Pressure);
             $("#humidity").html(thedata.DH_Humidity);
             $("#systime").html(thedata.SYS_Time);
             $("#sysheap").html(thedata.SYS_Heap);
             $("#sysloop").html(thedata.SYS_Loopcnt);
             updateWeatherSensorData.timeout = 0;
         },
         timeout: 7000 // sets timeout to 7 seconds
     });
 }

 

The updateWeatherSensorData() function makes an AJAX request to the ESP8266 to return the current sensor values and status in JSON format. Just as with the GPS Sensor data, these values are simply used to set the html for the applicable displayed objects by id.

Heart Rate Monitor Data

A placeholder has been set in the code to collect heart rate monitor sensor data. While I have used Apps that interface with an external heart rate monitor using ANT+ and therefore know it is possible, I have have not accessed this interface in my own App…yet. So, not to hold up the initial release of this project, the Heart Rate Monitor data is planned to be added in Phase 5 using the ANT+ for Android API.

ESP8266 Configuration

The ESP8266 hardware interfaces to just two sensors for this initial design:

  1. BMP085 – Temperature and Pressure Sensors
  2. DHT22    – Temperature and Humidity Sensors

After many revisions from experience using the ESP8266, the hardware for Phase I of this project is configured as shown in the following schematic:

ESP8266-mobile-schematic - Phase 2
The basic ESP8266 framework is shown on the left side of the schematic with the two sensors on the right. Refer to the following posts for more information about the operation of this circuit:

The ESP8266 code for this project is very straight-forward. It consists of a simple web server, with the module operating in access point (AP) mode. The SSID has a fixed value of “ESP8266N4” and responds to the hard-coded IP: 192.168.22.1 on port 9703. These, of course, can be set to any value or even configured at run-time through the serial or initial web server default value. However, this example sticks with the hard-coded values since this system will only be paired with a single Smartphone.

The web server responds to a request for sensor values and status with a JSON string that can be easily parsed with an AJAX call.

Request URL:

http://192.168.22.1:9703/?request=GetSensors

 

JSON string returned:

{
"B_Pressure":"29.24",
"B_Temperature":"79.34",
"B_Altitude":"555.0",
"DH_Humidity":"34.7",
"DH_Temperature":"69.1",
"SYS_Time":"38",
"SYS_Heap":"32368",
"SYS_Loopcnt":"10",
"SYS_WifiStatus":"255",
"SYS_WifiRecon":"0",
"SYS_WifiMode":"2"
}

 

The code is based on the IoT_Demo example included in the EspressIf SDK. This project uses SDK Version 1.1.1. The latest version as of this post (1.2.0) should also work but I have not tested it with my code yet.  The ESP8266 source code for Phase I of this project is available on GitHub here.

Mobile App Screen Display

The current App GUI display for Phase I of this project exhibits 13 values.

Mobile Sensors

 This GUI includes CSS styling which takes advantage of the responsiveness of bootstrap. The source code for Phase I of this project is available on GitHub here.

Operation

Once the ESP8266 schematic has been built and the SDK based code has been installed, the ESP8266 is ready. The Android Application should also be installed on the target SmartPhone.

First, power up the ESP8266 from a 5 VDC source. The schematic includes a 5V to 3.3V converter, so I typically use a USB wall source or portable battery. Then you go to the phones WIFI configuration screen and select the ESP8266, which has an SSID of “ESP8266N4” in this example. This will connect the SmartPhone to the ESP8266 so sensor data can be read on demand.

Now start up the Android App. The data will update live, typically at a rate of at least once every second. Go ahead, walk around with the phone and observe the GPS Lat and Long values change. You can also put a finger on the barometric pressure sensor and see a change in the temperature value reported on the display.

Conclusion

We now have a working mobile application that collects sensor data and displays it on the smartphone screen. Using a USB battery with 5000 ma-hours or more, the system can easily move with you, secured in a backpack, fanny-pack or even in your pocket. Stay tuned for the next phase – Periodic logging of these data packets to a file; coming soon…

One final note: While this example uses an Android phone, the Cordova platform used is largely platform independent. While I am not familiar with iOS development, it should be a relatively simple task to adapt this application to work with an iPhone with little or no change to the code.

Hope you find this information useful…

 

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

Compiling ESP8266 Legacy App with SDK 1.1.1

SDK

Have you ever upgraded to a newer version of software or operating system, only to find once working Apps suddenly broken? And now it is not so easy to turn back…

I ran into this sort of thing with the ESP8266 SDK version 1.1.1. It had fixes for the problems I had been experiencing, but my application would no longer compile without error. Yep, this SDK was not compatible with programs developed using my earlier SDK (1.0.1). Some things were added. One item was now required, yet it did not exist before version 1.1.1. Still other features were removed.

Even the IoT_Demo example included with this latest version would not build successfully.

This upgrade started to rub me the wrong way. But finally, through some code review, minor modifications and interaction with EspressIf, the incompatibilities I had encountered were eventually sorted out.

Here is what I discovered and had to change to build an older application (based on the IoT_Demo example) with the improvements offered with SDK 1.1.1. So you can minimize the upgrade challenges and move on. To focus on your latest creation.

Tweaking your application for SDK 1.1.1 compatibility

1. The structure “rst_info” in user_interface.h has changed.

From this:

struct rst_info{
    uint32 <strong>flag</strong>;
    uint32 exccause;
    uint32 epc1;
    uint32 epc2;
    uint32 epc3;
    uint32 excvaddr;
    uint32 depc;
};

To this:

struct rst_info{
    uint32 <strong>reason</strong>;
    uint32 exccause;
    uint32 epc1;
    uint32 epc2;
    uint32 epc3;
    uint32 excvaddr;
    uint32 depc;
};

This will require a change to the structure reference in the function user_esp_platform_init(void) in the file user_esp_platform.c. Change all references from rtc_info.flag to rtc_info.reason.

2. PULLDWN has been removed.

The code statements need to be removed or commented out in the gpio16.c file:

	switch(pull) {
		case GPIO_PULLUP:
			//PIN_PULLDWN_DIS(pin_mux[pin]);
			PIN_PULLUP_EN(pin_mux[pin]);
			break;
		case GPIO_PULLDOWN:
			PIN_PULLUP_DIS(pin_mux[pin]);
			//PIN_PULLDWN_EN(pin_mux[pin]);
			break;
		case GPIO_FLOAT:
			PIN_PULLUP_DIS(pin_mux[pin]);
			//PIN_PULLDWN_DIS(pin_mux[pin]);
			break;
		default:
			PIN_PULLUP_DIS(pin_mux[pin]);
			//PIN_PULLDWN_DIS(pin_mux[pin]);
			break;
	}

NOTE: My application also called “PIN_PULLDWN_DIS” in ds18b20.c. If you are using the ds18b20.c or any other library that calls “PIN_PULLDWN_DIS”, it will need to be removed or commented out.
3. “user_main.c” now is required to include the function “user_rf_pre_init().

void user_rf_pre_init(void)
{
	system_phy_set_rfoption(2);
}

You do not need to include a call to “system_phy_set_rfoption()” in this function, but this is the ONLY function that allows this function to be called. If interested in learning more, refer to the latest SDK programming guide for this new feature.

4. The “Make” file is missing a required library.

Add “pwm” to the LIB line in the Make file for a successful application build:

# libraries used in this project, mainly provided by the SDK
LIBS		= c gcc hal phy pp net80211 lwip wpa <strong>pwm</strong> main json upgrade

And with these minor adjustments, I have successfully built my previously built App using SDK 1.1.1.

This is quite thrilling for me and I hope you too have success using SDK 1.1.1 and beyond. For me, this is the best SDK version yet.

The issues I had in the past with the Wifi server failing to respond to requests (STATION Mode) after about a minute and the AP mode simply not working with Android devices are gone.

Now we can focus on creating amazing things, with all the features of the always improving SDK APIs. From my experience, the SDK is by far the most capable environment to build your IoT visions available for the cheap yet capable ESP8266.

I hope you find this information useful.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

ESP8266 WIFI dropout-proof connectivity

How to eliminate ESP8266 WIFI drop-outs

Just when it seemed like the ESP8266 was operating rock-solid, indeed running continuously for days now without resetting, or worse, fatally crashing, a sign that something was wrong appeared…

wifi

Out of the corner of my eye, a flash of light seemed to originate from the up ’till now reliably running ESP8266 based circuit. As my gaze turned directly towards the module, the blue LED started flashing. Not just once, but several times with a silent couple of seconds between illuminations…

“Uh-Ohh”, I thought, “looks like the ESP8266 is once again in a reset loop!” First thing to check was the ESP8266 web server response to a http GET request. The server did respond with a JSON string, just like it was programmed to do. And much to my surprise, the status (seconds running since last reset), indicated the module had been continuously running for days.

So why the flashing blue LED?

I noticed that sending a http GET request around the time the flashing occurs required considerable time (up to 10 seconds) before the ESP8266 returned a JSON response string. This could only mean one thing…

A WIFI Connectivity Check and Recover is Essential

The application firmware had detected a loss in WIFI connectivity and was attempting to reconnect. I had added a WIFI check to the top of the Arduino IDE loop() function. It never seemed to detect a loss of WIFI. That is, until now…

While the following code was developed using the Arduino IDE, the same check should be included for the SDK or NodeMCU code as well.

//connect wifi if not connected
if (WiFi.status() != WL_CONNECTED) {
    delay(1);
    startWIFI();
    return;
}

 

So the setup() function initially establishes the WIFI conection with a call to startWIFI(). The WIFI status is subsequently checked each iteration of the loop() to maintain the connection.

Fortunately, I had included some status messages in the startWIFI() function sent out the serial port just in case some troubleshooting was needed. This came in handy to confirm the root cause of the flashing blue LED.

void startWIFI(void) {
    //set IP if not correct
    IPAddress ip = WiFi.localIP();
    if( ip!= ipadd) {
        WiFi.config(ipadd, ipgat, ipsub); //dsa added 12.04.2015
        Serial.println();
        delay(10);
        Serial.print("ESP8266 IP:");
        delay(10);
        Serial.println(ip);
        delay(10);
        Serial.print("Fixed IP:");
        delay(10);
        Serial.println(ipadd);
        delay(10);
        Serial.print("IP now set to: ");
        delay(10);
        Serial.println(WiFi.localIP());
        delay(10);
    }
    // Connect to WiFi network
    Serial.println();
    delay(10);
    Serial.println();
    delay(10);
    Serial.print("Connecting to ");
    delay(10);
    Serial.println(ssid);
    delay(10);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
    }
    Serial.println("");
    Serial.println("WiFi connected");

    // Start the server
    server.begin();
    Serial.println("Server started");

    // Print the IP address
    Serial.print("ESP8266 IP: ");
    Serial.println(WiFi.localIP());

    // Print the server port
    Serial.print("ESP8266 WebServer Port: ");
    Serial.println(SVRPORT);
    delay(300);
}

 

As I mentioned, the my ESP8266 web server returns status, along with sensor readings in a JSON string upon receiving http GET request. This data is logged to a mySQL database, once every hour. A CRON php script pulls the ESP8266 data and saves it to the database.

The next step

In order to assess how frequent WIFI connectivity is lost and restarted, I am going to add a static counter to my startWIFI() function. This will identify the number of times the WifFi connection was lost and reestablished since the last reset. That value will be recorded to mySQL along with the other values. It will be interesting to see how often this occurs. Once a day? Several times per hour? We shall see…

If you have had any issues maintaining WIFI connectivity, or your server stops responding to request, consider this as a solution.

I hope you find this information useful…

Update: July 5, 2015

The ESP8266 supporting my weather sensor webserver did reset 23 days ago. I took that opportunity to add a static counter to the startWIFI() function. A ThingSpeak channel has also been established to share the live results publicly.  As of this update, the Wifi connectivity was lost 537 times.

Recovery was successful every time as no ESP resets have occurred yet.

This empirical data shows the Wifi connectivity is lost on average 23 times per day.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

A cleaner ESP8266-12 hardware setup

ESP8266 packaging issues

One of the first challenges to overcome when you get a bare module ESP8266-12 SoC is how to connect this unit to a circuit. It comes without header pins and the pin pitch is less than the standard 2.54 used on solder-less and copper breadboards. Clearly, it is not ready to use out-of-the-box like, for example, any of the Arduino options.

My first circuit used a 16-pin DIP package with short jumper wires soldered between the ESP8266 pin holes and the DIP. This assembly was then plugged directly on a solder-less breadboard. While this gave me a quick start into the ESP8266 world, the setup was messy and even worse – unstable.

Solder-less Breadboard

Disappointed and often frustrated by the poor performance of the setup, my next setup used a copper plated breadboard. The ESP8266 was mounted to the board using thin (28 AWG) bare wires. These wires were soldered between the ESP8266 through-holes and the breadboard pads. This was a vast improvement in terms of stability. I currently have a system that has been running for over 2 weeks now with no resets or system crashes. The real-time data collected with this system is displayed publicly on ThingSpeak for independent verification.

But with this setup, the tiny interface wires require a lot of time to initially assemble.

That’s where this adapter plate really shines…

Yes, it really made things easier when I stumbled upon a clean and inexpensive adapter for the ESP8266-7/12 modules. For just 28 cents (AliExpress), you get a PWB plate with pre-soldered mounting pads and a 10k pull-up connected to the chip enable (CH_PD).

A 10K resistor is also included that pulls-down GPIO15 to ground. This resistor is way to large to be of any value for that purpose. For proper boot operation, you must add a connection between GPIO15 and ground.

Finally, the fix is in – the pin labels for GPIO4 and GPIO5 have been corrected on this plate. No more confusion for that until now overlooked ESP8266-12 module design error.

ESP8266-12 adapter plate

The circuit has come together quite nicely. So far, it has proven to be a very dependable configuration. Boots without errors and flashes reliably the first time, every time. We shall see if this remains true as more the flash cycles are performed.

Fully assembled ESP8266 with adapter plate

This begs the question… Why not mount all the parts on a plate like this & eliminate the original carrier board?

A few design considerations

  • Notice the 0.1uF decoupling capacitor added close to the ESP8266 assembly. Positioning this essential capacitor there…directly across the ESP8266 VCC and Gnd pins, is absolutely critical for stable operation.

20150519_decouplingcap

  • The header pins were mounted backwards so the longer posts are facing upwards. This will be useful should it be necessary to connect female jumpers directly to any ESP8266 pin.
  • The USB to serial adapter cable connections are split between two terminal sections. The right two terminals connect USB 5V and Ground. The left two terminals, serial transmit and receive, are only used when flashing the firmware. Once deployed, the left two terminals are disconnected and the 5V and ground connections are attached to a USB cable. This supports power sourced from a USB wall or car adapter as well as a USB battery.
  • The ESP serial receive pin has a 100 ohm series resistor included from the serial transmit source. In addition, a 3.3V zener diode clamps the input voltage into the ESP8266. Many ESP8266 users omit these parts. This is not advisable. Exceeding the specified input range will likely degrade the system performance and possibly introduce hard to find latent defects! For long-term reliable operation, these common, readily available components should be included in every interface circuit.

ESP8266-schematic - serial

  • An AMS1117 voltage regulator converts the 5V to 3.3V for the ESP8266 supply. This is mounted on the breadboard copper side of the breadboard so the heat sink built into the regulator can be soldered to the board.

Regulator Heat Sink

  • To minimize instabilities from voltage ripple, two 470 uF capacitors are used, one across the 5V source and one across the 3.3V ESP8266 supply.

ESP8266-schematic - power

In Conclusion

In my experience, while cheap, feature rich and full of promise, unwanted system resets, flash failures and crashes have been the curse when working with the ESP8266.

But there is hope…

This recently introduced adapter plate, along with the hardware interface features presented here will help mitigate these undesirable outcomes.

Hope you find this information useful…

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

8 ESP8266 analog inputs for 22 cents

Want More Analog Inputs?

Do you have a project needing more than one analog input? If your using an ESP8266, that would seem to be a problem as it only offers a single input. Before you commit to using an Arduino, Spark Core, Raspberry PI or other higher priced micro-controller, one with multiple analog inputs, consider this…

ESP8266image

Adding an 8-1 multiplexer chip to your ESP8266-07 or -12 circuit can expand your system capability from one to eight analog inputs.  I recently tested this out, using a 74HC4051 CMOS analog multiplexer component I got from an AliExpress supplier.

The cost?

$2.19 for 10 chips, or $0.22 per chip.

They are available in a 16-pin DIP package  with 2.54 pitch for easy use with a solder-less breadboard.muxpicSo what’s the downside? Well, selecting one of the 8 analog inputs will require 3 GPIO pins. For many applications, that should not pose a problem when using the ESP8266-07 or -12. These versions have 7 easily accessible GPIO pins available, leaving you with 4 GPIO pins for any digital input or output requirement after adding the 8 analog inputs.

Here is the circuit I used to test this configuration:

ESP8266-schematic - amux-test_rev1

The left side of this drawing is the standard circuit I have been using for all of my ESP8266 projects. A typical USB to serial adapter is used when developing and flashing the circuit. When deployed, I use a USB plug with a wall adapter to provide a 5V source, without the Tx/Rx signals.

The analog multiplexer is controlled by 3 GPIO pins; 14,12 and 13. Setting the states of these 3 digital outputs determine which analog input will be measured.

GPIO14 GPIO12 GPIO13
A0 0 0 0
A1 0 0 1
A2 0 1 0
A3 0 1 1
A4 1 0 0
A5 1 0 1
A6 1 1 0
A7 1 1 1

The sketch used to test this circuit was developed using the ESP8266 Arduino IDE.

The serial output loops through each analog input, setting the multiplexer and reading an input every 2.5 seconds. The sketch also behaves as a web server. All 8 analog values can be retrieved in a single JSON string returned from an http GET request.

ESP8266 ADC Performance Evaluation

Using this circuit and software, I proceeded to collect some data to characterize the ESP8266 analog input range. First, the multiplexer selector was verified by connecting each input to ground and verifying the Analog count returned was 0. Likewise, each input was connected to 3.3V with a reading of 1024 returned when reading the ESP8266 ADC pin.

All good so far…

Then I connected the A0 input to a variable resistor to vary the input voltage voltage.

ESP8266-schematic - amux-Test-Circuit-updated

At the same time, an external Digital Multimeter (DMM) was used to monitor the voltage applied to the ESP ADC input via the multiplexer. For each voltage setting, I recorded the DMM reading and the ADC count returned from the ESP8266. It would have been great to have a calibrated bus controlled DMM to automate this process, but for the purpose of this DIY home project, I simply entered the values into an excel spreadsheet manually.

Thirty-seven voltage settings were applied in the range between 0.2V and 1.2V. Any voltage below 0.2V returned a 0 bit count while voltages above 1.2V returned 1024. I observed approximately 10 values returned from the ESP8266 for each voltage applied and recorded the high and low bit count readings for these measurements. The average of the high and low reading was then used to chart the results.

ESP8266 ADC voltage vs bit count

As you can see, the results were reasonably linear. But there is compression at the voltage extremes. For practical use, I would not use the non-linear ends, limiting the voltage swing from 0.25 to 1.15 V, a 0.9 V range.

The data collected can be reduced to a “best fit” equation. This would provide a method of converting the raw ADC value count to a voltage. Ideally, a data point should be collected for each ADC count value. The equipment I used for this exercise was not calibrated or accurate enough to do this. Given these uncertainties in my test setup, I am not sure if the variances I observed for consecutive readings…and they did vary somewhat…was result of the input voltage source or the ESP8266 ADC.

Still…with the data I had collected, the formula was determined to be:

Vain = (0.94* ADCcount + 200) mV

The slope was determined by dividing the voltage difference by the ADC count  difference at each end of the voltage range. And 200 mV, the intercept, is the voltage when the ADC started reporting 0 for the count.

While there does not appear to be a definitive specification, this is consistent with what I have read regarding the ESP8266. The 10-bit ADC resolution is supposed to be approximately 1 mV with a 1 V range.

Resolving Sensor Incompatibilities

So what can you do if your sensor range is outside the ESP8266 0.2 to 1.2 V window?

Scaling of course.

This can be accomplished passively, using a resistor divider, or actively, with the addition of an op-amp. The interface of choice would be an active op-amp based circuit.

For example, suppose your sensor has a 0-5V range. This would need to be scaled to fit in the ESP8266 0.2 to 1.2 V input range. Obviously, resolution will be compromised as we go from a larger range to a smaller one, but it can be done. And with a single power supply.

ESP8266 Analog Input Voltage Level Shifter

Resistor values calculated here. The 24K/1K resistor divider supplies the 0.2V offset with the gain set for the 1.15 V output with a 5V maximum input applied. This circuit would need to be modified for your specific sensor voltage range.

In summary

So there you have it. Eight analog inputs measured using a single ESP8266 SoC. Possible simply by adding a 22 cent chip.

And I got to mention one more option. Just in case you want even more…

A 16 channel version of the multiplexer is also available (74HCT4067). That’s a whole lot of analog!

I hope you find this information useful.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

My ESP8266 Controlled Temperature Sensors now on ThingSpeak

Now that my ESP8266 controlled sensors have been on-line and are now reliably running, the next step was to push some of the data up to ThingSpeak. Up to now, I had been saving the readings exclusively in my host server account’s mySQL database.

And now the temperature readings are also pushed up to ThingSpeak, once every hour.

But not by the ESP8266 micro-controller. No…I have discovered that the stability of the ESP8266, at least at this time, is linked to the frequency of accessing it through http client GET requests. Access to my ESP8266 is tightly controlled. It has to be. I’ve written about structuring a stable ESP8266 Arduino IDE sketch loop() in another post. This may be helpful if you are have issues with the ESP8266 reliability.

The video created to describe the ThinkSpeak channel breaks down the unique methodology I’ve used to move sensor readings up to ThingSpeak.

You can check out the real-time data now visually served to the world on my new ThingSpeak channel. I’m hoping there is something unique about the method used to upload the readings and the eye-catching displays that could be of value to someone. Something not found on any other of the many channels displaying similar data.

Setting up the channel was easy. ThingSpeak is a free platform serving first as a repository database, like mySQL, to store data read from your Internet of Things (IoT) gadgets.

Once you have a periodic data feed to ThingSpeak, the platform can execute actions based on the data. It also provides a simple API to take some of the burden off your micro-controller. Here’s highlights of what ThingSpeak can do for you:

  • ThingTweet – This service provides a simple API for your IoT thing to post Twitter messages.
  • React -Performs whatever action you need when the data in your channel meets your custom set condition. Some obvious examples:
    • Turn light on when proximity sensor detects someone in room
    • Water lawn when moisture detector reaches dry threshold.
    • Turn heater on when temperature drops below certain reading.
  • TalkBack – API that has device execute queued commands. The queue is loaded in ThingSpeak. Then the device request a command, and performs an action based on the command it gets from the ThingSpeak queue. I have not thought of an application for this yet, but I’m sure you might find some from ThingSpeak.
  • TimeControl – Allows you to setup ThingHTTP or ThingTweet requests a a predetermined time. There are many ways to do this, but using ThingSpeak could reduce the burden placed on your device or other element in your IoT ecosystem.

Temp Humidity Baro-Pressure

That’s it for now. Keep your creative juices flowing. I may add my humidity and barometric pressure readings to the initial ThingSpeak soon – in a 3-gauge display window. Like you see above. Being in the US, my temperature is in Fahrenheit and the pressure is inches of mercury. What will you do next?

I hope you find this information useful…

 

 

 

 

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr