Multiple Analog Sensors with NodeMCU Web Server

Multiple Analog Sensors with NodeMCU Web Server

Introduction

ESP8266 is one of the most populat chips for Internet of Things programming. Unfortunately, it only has one analog pin (A0), which is not enough in case you want to read multiple sensors. A common solution ot this problem is using a multiplexer: it has multiple inputs and you call (programmatically, in real time) tell it which one to read, or to put it differently, which one to conect to its single output.

In this tutorial we are going to use 74HC 4051 - a 8 channels multiplexer.

We will create a server that provides a web page. This web page is similar to previous example: it allows sending commands to 8266 (turn light dione on/off), and receives thermistor-provided themperature data. The difference is, we now have two thermistors (and can increase it up to eight), so we use a multiplexer.

Again, if we compare this example with the previous one, we can see that an analog pin A0 of ESP8266 is now connected to a multiplexer, instead of going directly to a sensor (thermistor).

A multiplexer "splits" this A0's "channel", so two pins (Y6 and Y7 in this example) are connected to it. Connected, of course, ONE AT A TIME, and which thermistor is being read at the moment, depends on the state of 3 command pins, S0, S1 and S2.

As in the previous example, thermistors are used together with the 10K resistor, forming a bridge.

Schematics

It might look complex, but the only difference between sketch and one from the previous tutorial is that thermistors are connected to A0 via a multiplexer, and not directly.

Code

First of all (again, as in a previous example), we keep HTML code for our web page in a variable, variable is stored in an index.h file, which is included in the main C++ file.

The code was inspired by Circuits4you.com, a site that is highly recommended.

index.h

                        
                    

We had two choices here: we could create a separate request for each sensor, but for multisensor systems it would create a messy code. It is easier to pack two sensors' readings into a single string variable (it happens in a C++ code, see below) and to copy it in an HTML element called "thermistors". Note that if we want to do something with this data, like plotting a chart, we can always parse the string, which is much cheaper than creating extra requests.

Let's take a look at the Arduino code:

                        
                    

To run this example, connect th eESP8266's USB to your PC, compile and upload the Arduino program. Make sure your modem's WiFi is on and support for 2.4G is checked in modem settings.

When the connection is established, the IP address will be displayed in the Arduino's Monitor. Copy it and open that page in your browser. You will see the web page:

(C) snowcron.com, all rights reserved

Please read the disclaimer