Posted on Leave a comment

ESP8266 Deep sleep mode

I always wanted to learn about the deep sleep mode in ESP8266. So I stumble across a few post in the internet, and comparing various post, there are several ways the ESP8266 can perform the deep sleep. They are:

  1. Deep-sleep
  2. Light-sleep
  3. Modem-sleep

Each mode can be described in the following tables:

As you can see in the table above, the point to have Deep-sleep is to conserve as much current as possible. In all mode above the Wi-Fi will be off. This will ensure that maximum power saving is achieved. In Deep-sleep the only things that awake is the RTC, so the typical application for this would be for a sensor reading that will happened periodically to take up every few minutes for non mission critical and update the reading. A good example for this would be a temperature sensor that wakes up every few seconds or even minutes to read the temperature and update this reading, this can be through MQTT, Thingspeak or IFTTT.

According to ESP8266 SDK, you can only sleep for 4,294,967,295 µs which is about 71 minutes.

Wake up Trigger

When ESP8266 is in Deep-sleep, it will need a mechanism to wake-up, given that everything, including CPU is OFF. The only thing that is still on is RTC. To wake up that means we have 2 options, first one is to set the time to wake up, and the second one is to press the reset button on the ESP8266 to wake it up. The first one can be done using the following code:

ESP.deepSleep(15e6);  // deep sleep for 15 seconds

To allow this to happen you will need to connect the WAKE up pin GPIO 16 (D0) to the RST pin. This can be shown in the following diagram:

Please note that when the RST is connected to D0, this will not allow the code to be uploaded to the ESP8266. The suggestion is to have a jumper or switch to allow the control of the connection between RST and D0 pin.

So with a practical example to allow reading of temperature sensor every 15 seconds we can modify the circuit above by adding the LM35 temperature sensor and a switch to allow connection and disconnection between RST and D0. This is shown in the following diagram:

The normal setup() function will need to contain the code to connect to WiFi and the posting of the reading of the temperature. This can be done using the following code:

void setup() {
   Serial.begin(115200);
   Serial.println("device is in Wake up mode");
   while (!Serial) { }
   connectToWifi();                // connect to WiFi
   int value = analogRead(A0);
   float volts=(value * 3.03) /1024;      //conversion to volts   
   tempC = volts*100;             //conversion to temp Celsius
   Serial.print("Temperature C: ");
   Serial.println(tempC);
   data();                       // post data else where
   Serial.println("deep sleep for 15 seconds");
   ESP.deepSleep(15e6); 
 }

In the code above once the ESP8266 wake up, the first thing it will do is to connect the the WiFi via the connectToWifi() function. Then it will read the sensor reading from A0, and convert this reading to celsius and posted the data and go back to sleep. The connectToWifi() function is shown below:

void connectToWifi() {
   Serial.print("Connecting to: SSID NAME"); //uncomment next line to show SSID name
   //Serial.print(ssid); 
   WiFi.begin(ssid, password);  
   Serial.println(" ");// print an empty line
   Serial.print("Attempting to connect: ");
 //try to connect for 10 seconds
   int i = 10;
   while(WiFi.status() != WL_CONNECTED && i >=0) {
     delay(1000);
     Serial.print(i);
     Serial.print(", ");
     i--;
   }
   Serial.println(" ");// print an empty line
 //print connection result
   if(WiFi.status() == WL_CONNECTED){
     Serial.print("Connected."); 
     Serial.println(" ");// print an empty line
     Serial.print("NodeMCU ip address: "); 
     Serial.println(WiFi.localIP());
   }
   else {
     Serial.println("Connection failed - check your credentials or connection");
   }
 }

Thus, the loop() function will not contain any code, as this will never get executed at all. This is shown below:

void loop() {
   //if deep sleep is working, this code will never run.
   Serial.println("This shouldn't get printed");
 }

This conclude my learning on ESP8266 Deep sleep, please let me know if it is useful and don’t forget to subscribe for more and don’t hesitate to let me know if you have any questions.

Posted on Leave a comment

IoT Remote Gate Opener

I am helping my brother to make a remote Gate opener. He have a remote that can open the gate, but being in this day and age, we would like to connect everything to the Internet. So the concept can be seen in the following picture:

IoT Remote Gate Opener circuit
Remote Gate Opener

The brain consist of ESP8266, which is connected to relay that will trigger the remote. The original idea is to have some sort of sensor (magnetic) that can be detected using Hall Effect sensor to detect when the gate had been closed or opened. Then to be able to access this remotely from anywhere in the world, we can connect this to Node-RED and subsequently able to access this via Apple Homekit.

To start off as the proof of concept and to reduce the complexity, we revert back to the basics, by just connecting the ESP8266 to a relay that will activate the remote to open and close the Gate door. To start off follow the following steps:

Step 1. Gather the components

Components for ESP8266 with Relay

We will need ESP8266, Relay module, and PCB to connect the two together. You can connect the two module together by soldering it on to the PCB. Connect the 3.3 Volt pin from ESP8266 to VCC of the Relay module, and GND from the ESP8266 to the GND of the Relay module, and finally for this example, I am connecting the pin D5 to the IN pin of the Relay module. Note that the Relay IN is active LOW, this means that the relay will be activated (Green LED on Relay board turn ON) when IN is LOW. The fully assembled board looks like the following picture.

Fully assembled ESP8266 with Relay module

Step 2. Modify the Remote

Remote Modification
Remote Wiring

In the image above, we solder 2 wire across the button that can activate the Gate. This two wire will be connected by the Relay module later on.

Step 3. Uploading the Arduino Code

The idea is to use ESP8266 as a webserver. This will allow us to show a setting page to connect the ESP8266 to the WiFi without having to hardcode the WiFi access points in the code. The website will also serve as the command to turn the Relay ON and OFF. Thanks for the handy work of Martyn Currey on how to create JavaScipt and AJAX within the ESP8266, and also some AJAX code to update ESP8266 from Circuits4you, I was able to massage the AJAX code into my previous Arduino code for the Temperature sensor. The final result looks like the following picture.

ESP8266 Webserver
ESP8266 Webserver

Once the ESP8266 is connected to the WiFi, only then the “Switch” button will appear in the webserver interface. When the ESP8266 is not connected to the WiFi, by default it will revert to be an Access Point, this will allow you to connect and configure the WiFi settings.

When you click on the “Switch” it will turn the relay ON, and thus simulating the press of the remote button to open the gate. Because we don’t have any feedback from the Gate in this solution, we will need to turn the “Switch” off manually, otherwise the button on the gate remote will be pressed and the battery will drain.

In the next section we will dive in a bit deeper into the Arduino code. If you are not interested in the code, you can skip this section and just upload the code straight away into the ESP8266. When the ESP8266 load up the first time you will be able to see the AP as coded in “settings.h” file. The AP name is “ESP-Gate” with the default password defined in the file. You can change this to make sure it is much more secure.

define CLOCK_NAME "ESP-Gate"
define WIFI_AP_NAME CLOCK_NAME
define WIFI_APPSK "DefaultAPPassword" // default AP password

Step 4. Arduino Code deep dive

The Arduino code comes in 5 files, and here are the list of the files:

  1. ESP8266GateSwitchV2: This is the main file where the magic happens. Pay special attention to the following sections (void setup(), void handleLED(), void handleRoot(), void loop()).
  2. Clock.h: This file is the header file for the CLOCK
  3. mainPage.h: This file is the webserver html file which get served when you connect to the ESP8266 web server
  4. ntp: This file consist of the function to connect to the ntp server to synchronise the clock
  5. settings.h: This file contain most of the settings for the project.

Void setup() section

#include <ESP8266WebServer.h>
// Create an instance of the server
// specify the port to listen on as an argument
ESP8266WebServer server(80);

void setup() {
DebugStart();
timer = 200;
pinMode(LED_BUILTIN, OUTPUT);
pinMode(LEDpin, OUTPUT); // setup LED
digitalWrite(LEDpin, HIGH); // Relay Active LOW
setupWiFi(1); // SetupAP mode
setupTime();
server.on("/", handleRoot);
server.on("/form", handleForm);
server.on("/setLED", handleLED);
server.begin();
}

This section will initialise the LEDpin, which is the trigger connected to the IN input of the Relay module. We will need to set the LEDpin to HIGH, because the relay module is active LOW. Initially setupWiFi will be called to try to connect to the WiFi, if this fail the program will defaulted to AP mode. SetupTime() will attempt to setup the time by synchonising the time with ntp server. The next couple of line define what function will be called when the webserver is being invoked. For example, handleRoot function will be called when the root of the webserver is being accessed. The handleForm function will be callled when the “/form” is being called, this is called when we setting up the Wifi parameter as well a a few other settings of the clock, daylight savings, etc. Finally “/setLED” will be called when we “button” is being pressed to activate the Relay.

void handleLED() section

void handleLED() {
String ledState = "OFF";
String t_state = server.arg("LEDstate"); //Refer xhttp.open("GET", "setLED?LEDstate="+led, true);
Serial.println(t_state);
if(t_state == "1"){
digitalWrite(LEDpin,LOW); //LED ON
ledState = "ON"; //Feedback parameter
}
else {
digitalWrite(LEDpin,HIGH); //LED OFF
ledState = "OFF"; //Feedback parameter
}
server.send(200, "text/plane", ledState); //Send web page
}

If we look at the handleLED function above, this is where the Relay is being activated. When the AJAX code post the LEDstate parameters back to the webserver, this section will check whether the LEDState parameter value is equal to 1 or 0, if it is 1, the code will write LEDpin output to LOW, and activate the Relay, and if the parameter value is 0, the code will write LEDpin output to HIGH, and deactivated the Relay. The ledState feedback parameter is just to make our life easier when debugging the code, this will show on the website whether the ledState is ON or OFF via AJAX return code.

void loop() section

void loop() {
server.handleClient();
if (timeStatus() != timeNotSet){
time_t t = now();
}
}

This section of the code is very simple, all it needs to do is to make sure the server.handleClient() function is called, to ensure that ESP8266 will allow client to connect to it’s webserver.

void handleRoot() section

void handleRoot() {
DebugLn("handleRoot");
String s = MAIN_page;
if (WiFi.status() == WL_CONNECTED) {
s += ButtonControl;
// check led state
boolean pinStatus = digitalRead(LEDpin);
if (pinStatus==LOW) {
s.replace("@@NA@@", "ON");
s.replace("@@SW@@", "ON");
s.replace("@@Checked@@", "checked");
}
else {
s.replace("@@NA@@", "OFF");
s.replace("@@SW@@", "OFF");
s.replace("@@Checked@@", "");
}
}
s+= WifiSetting;
time_t t = now();
s.replace("@@SSID@@", settings.ssid);
s.replace("@@PSK@@", settings.psk);
s.replace("@@TZ@@", String(settings.timezone));
s.replace("@@USDST@@", settings.usdst?"checked":"");
s.replace("@@HOUR@@", String(adjustedHour(t)));
s.replace("@@MIN@@", String(minute(t)));
s.replace("@@NTPSRV@@", settings.timeserver);
s.replace("@@NTPINT@@", String(settings.interval));
s.replace("@@SYNCSTATUS@@", timeStatus() == timeSet ? "OK" : "Overdue");
s.replace("@@CLOCKNAME@@", settings.name);
s.replace("@@UPDATERESPONSE@@", httpUpdateResponse);
httpUpdateResponse = "";
server.send(200, "text/html", s);
}

This section deals on how the root of the webserver should look like. It will first get the MAIN_page content from mainPage.h file, and then substitute the checkbox status based on the reading of the LEDpin. If the currently the LEDpin is LOW, that means the switch is active, so it will need to show the “switch” as on. And if the reading is HIGH, this means that the switch is not active, so it will need to show the “switch” as off. Then the rest of the code is to display the WiFi SSID, time zone, ntp server, update interval, device name.

I hope you like this post, and please subscribe if you haven’t done so. And let me know if you have any questions.

Posted on Leave a comment

ESP8266 Secure AP mode

Quite often we take shortcut to make things simple. That that sometimes will come and bite you back. To make sure you always consider security in mind at everything you do. Password is to keep something secure, and not to be forgotten.

In this post, I am trying to show how simple the security can be implemented to ensure that we always have security in mind. There is nothing worse than having a fully working system and then get hacked. This will cause unnecessary stress later.

If you are using ESP8266 in AP mode to setup the WIFI configuration, don’t forget to set the password and make sure you keep it secure by remembering it and not tell anyone.

In order to do this you can set the password when setting the ESP as and AP, this is done using the following code:

WiFi.softAP(WIFI_AP_NAME, AP_PASS);

The second line in the above code passed in “AP_PASS” variable, this will ensure that you can connect to the ESP using the password. You can also leave the second parameter blank to leave it open, but then anyone can connect to it and messed up with your setting. Things to note, the password will need to be more than 8 Characters, otherwise, the function call will fail. The best way to check this is to check the Serial Monitor and modify the above code to be as follow:

Serial.print("Starting AP mode:");
Serial.println(WiFi.softAP(WIFI_AP_NAME, AP_PASS)? "Ready": "Failed!");

When the AP is started, you can see in the Serial monitor window whether the function call WiFi.softAP is success or not. The simple code describing the above can be found below.

/*
   Copyright (c) 2015, Majenko Technologies
   All rights reserved.
   Redistribution and use in source and binary forms, with or without modification,
   are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright notice, this
     list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, this
     list of conditions and the following disclaimer in the documentation and/or
     other materials provided with the distribution.
 * * Neither the name of Majenko Technologies nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
   ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* Create a WiFi access point and provide a web server on it. */

#include 
#include 
#include 

#ifndef APSSID
#define APSSID "ESPap"
#define APPSK  "thereisnospoon"
#endif

/* Set these to your desired credentials. */
const char *ssid = APSSID;
const char *password = APPSK;

ESP8266WebServer server(80);

/* Just a little test message.  Go to http://192.168.4.1 in a web browser
   connected to this access point to see it.
*/
void handleRoot() {
  server.send(200, "text/html", "You are connected");
}

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");
  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

Hopefully you will find this article useful to secure your IoT devices and saving you the headache of being hacked in the future. If you like this post, please share and don’t forget to subscribe the blog for more article about IoT and Arduino.

Posted on Leave a comment

3 Step to use External Interrupt on ESP8266

I was in the middle of replicating my 433 MHz remote control using Arduino. The receiver circuit is quite simple and it is using Arduino pin 2 (interrupt) to detect the data signal from the receiver.

I was wondering whether I can do the same thing with ESP8266. After a short google, I found some information about Interrupt pin D3 (GPIO0) and also D0 (GPIO16). At a glance it seems do able.

Here are the steps to use the interrupt.

  1. Initialise IO pin as input
  2. Initialise IO with Interrupt Subroutine definition
  3. Interrupt Subroutine.

Here are the code that I stumble upon from the Circuits4you.com website.

const int interruptPin = 0; //GPIO 0 (Flash Button) STEP 1
const int LED=2; //On board blue LED
 
void setup() {
  Serial.begin(115200);
  pinMode(LED,OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE); // STEP 2
}
 
void loop()
{
    digitalWrite(LED,HIGH); //LED off
    delay(1000);
    digitalWrite(LED,LOW); //LED on
    delay(1000);
}
 
//This program get executed when interrupt is occurs i.e.change of input state - STEP 3
void handleInterrupt() {
    Serial.println("Interrupt Detected");
}

I will try this tonight and report back whether the Interrupt detection works or not.

The Remote.

BAUHN Remote Control

The remote consist of 4 ON button and 4 OFF buttons, each one is labelled A, B, C and D.It works independently controlling the remote power point switch.

The power point needs to be sync against one of the button pair (A, B, C or D). In this experiment I am detecting button B.

Below are the connection between ESP8266 to the 433 MHz receiver. As you can see I only connected 3 cables. 3.3V Vcc for Power (red cable), GND (green cable) and Data (Yellow) connected to GPIO0 of ESP8266 (D3).

I had used a slightly different sketch which is utilising the rc-switch library, and it also can provide the same detection that I had done using Arduino Uno. Here are the sketch that I had used to detect the remote.

#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();

void setup() {
Serial.begin(9600);
mySwitch.enableReceive(0); // Receiver on interrupt 0 => that is pin GPIO0 or D3 in ESP8266

pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (mySwitch.available()) {
Serial.print("Received ");
output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
mySwitch.resetAvailable();
}
}

I had connect the receiver to Pin D3 on ESP8266, and getting the following result when I press the B-ON button.

Received Decimal: 9085236 (24Bit) Binary: 100010101010000100110100 Tri-State: not applicable PulseLength: 500 microseconds Protocol: 5
Raw data: 7036,1061,455,589,934,607,918,613,952,1071,454,575,955,1065,457,565,971,1033,509,509,1021,1022,506,526,995,542,981,548,977,543,979,1055,482,561,1057,466,1080,942,548,980,540,486,1067,956,552,484,1071,564,966,
Received Decimal: 9085236 (24Bit) Binary: 100010101010000100110100 Tri-State: not applicable PulseLength: 500 microseconds Protocol: 5
Raw data: 6969,1116,407,629,907,553,987,554,928,1085,445,593,924,1123,405,623,912,1122,403,625,901,1049,489,537,988,546,974,556,965,565,970,1045,483,561,944,559,969,1070,453,1073,453,578,949,1066,460,577,946,545,1021,

So I can conclude that the Interrupt definitely working ok. The next step would be to capture a few more data and trying to send it back via the 433MHz transmitter to try to replicate each of the button. Given that the ESP8266 can be connected to WIFI and also can server as a webserver this will make it possible to control the remote via internet as an IoT device.

Stay tune for the next article. Please share or subscribe if you like to see more of this article and feel free to drop me a comment.

Posted on Leave a comment

Connecting IoT Sensors data to Node-RED

This is the continuation of the Temperature sensor project in the previous post. The concept is to allow the data from sensors (temperature, motion) can be displayed in Apple Homekit, so that the user can interact with the information and control the IoT connected devices (Lights, Fan, etc). It is best described in the following picture.

The following instruction shows how to install Node-RED on a linux computer running Debian OS.

sudo npm install -g --unsafe-perm node-red

You will also need to install the mosquitto MQTT message broker, here are the command required

sudo apt-key add mosquitto-repo.gpg.key
sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update
sudo apt-get install mosquitto

You will also need the latest Python library, so grab them using the following instruction

sudo apt-get install python-dev

Test the installation. In this example I was using Linux Debian, so typing the command node if you get the following in the command prompt, that means the installation is successful. So then you can exit node by typing .exit command in the prompt >.

If all goes well, you can run the node-red command in the command prompt. You should get the following message. This shows that the node-red is now running at http://127.0.0.1:1880.

Node-RED Settings

Node-RED setting file called settings.js, on Linux it is located in the /usr/lib/node-modules/node-red folder. You will have another settings.js file in the .node-red folder in your home folder. This setting will be loaded by default.

Creating the flow in Node-RED

Now that you have a running Node-RED, it is time to create the flow. In this example we will create a simple flow to read temperature posted by our ESP8266. Let’s start by firing up your favourite browser and point to the following URL: http://127.0.0.1:1880/

You will be presented with a blank screen similar to the following picture. Now to start creating a flow, drop an “Inject” node from input section. We will use this as a trigger to get the temperature reading. Once you dropped it in, double click to set the property. We call the node “timestamp” and we set the interval to repeat every 4 minutes.

The next step is to connect this with an “http” node, so drop an “http” node and configure this as http GET to call a server side script in the webserver. What the script needs to return is the temperature in JSON format as below:

{"CurrentTemperature":25}

So my data_store2.php script does exactly that, as shown in the following code:

 /* readtemperature file from temp.txt file    return the value back in JSON format for HomeKit  */ 
$theparam = $_GET;
$file = './temp.txt';
$temperature = file_get_contents($file);
echo '{"CurrentTemperature":'.$temperature.'}';

Now the final step is to connect to the “Homekit” node from the Advance nodes menu. Once you drop the “Homekit” node, you can double click to configure the property as below.

Once all had been connected, it is time to deploy the node. You can do this by clicking on the “Deploy” button at the top of the Node-RED window. You will need to click the “Deploy” button whenever you make any changes to the node. Sometime the deployment might stop the Node-RED server, so you just have to run the node-red command again in the command prompt.

If all goes well, you can now test this node by clicking on the button next to “timestamp” node, the temperature should be read from the webserver and displayed in Homekit, similar to the following picture.

That conclude this session on how to configure the Node-RED to work with our temperature sensor data from ESP8266. Please let me know if you have any questions related to this and don’t forget to subscribe for update on the similar projects. The next session we are going to connect this to the Apple homekit in IPhone or IPad.

Posted on Leave a comment

IoT Gas Sensor with ESP8266

I had been wanting to get the gas sensor working with my ESP8266 as an additional item on the IoT list. So similar to the IoT Temperature sensor from the previous post, I had created the IoT gas sensor using ESP8266.

Using the same idea you don’t have to open port in your router, but leveraging an intermediate layer by publishing the data to a website. Here are the list of components used:

The circuit

We are connecting the Gas sensor analog output to Analog input (AD0) of ESP8266 as shown in the following picture.

ESP8266WithGasSensor

The Buzzer is connected to Pin GND and D3.

We will check the sensor via analog to give much better variation, we can also use the Digital output from the sensor, but you will have to calibrate this properly to ensure that it gives the desired trigger when a certain composition of gas was detected. You can use the prototype board to connect them all up and using Arduino interface you can load the code.

If you are not familiar on how to setup the Arduino IDE (integrated development Environment) I had an instructables post that can help you to get started.

The finished connection should look like something below:

IoT Gas Sensor with ESP8266

Now that you have a setup the circuit, there is one more step to setup the Cloud webserver (optional) if you want the sensor to periodically upload the gas reading to the webserver so that you can monitor this remotely.

Assumption: You have a working webserver, and familiar with transferring files to your webserver.

Web server setup

Transfer the content of “IoTGasSensorwebserver.zip” into the root of your webserver. Let’s assume that your webserver is “http://arduinotestbed.com”

You can put the file in a separate folder, but you need to modify the sketch to point to the correct location of “gasdata_store.php”

In this example we are assuming that the full path to the file are http://arduinotestbed.com/gasdata_store.php

Once you had uploaded the files, you can test that it is working going to the following link

http://arduinotestbed.com/GasData.php

watch out for the character case as most webserver are case sensitive. If all is working, you should see something that looks like the following:

IoT Gas Data

One more thing you will need to make sure is the file “gas.txt” needs to be writeable, so you need to set the permission of this file to “666” by using the following unix command:

chmod 666 gas.txt

This file is where the sensor data will be uploaded into by the ESP8266.

You can download the webserver scripting using this link.

Uploading the arduino sketch

Now you are ready to upload the sketch code to the ESP8266. You should have 2 files:

  • ESP8266GasSensor.ino
  • mainPage.h
  • settings.h

Put them all in the same folder and open the “ESP8266GasSensor.ino” in the Arduino IDE, then make small modification to the code to point to the correct webserver location shown in the following picture:

Arduino code changes

Modify the line

String weburi = "/gasdata_store.php"

if you didn’t put this file in the root of the webserver, this should point to the correct path of the file. Then compiled and load the sketch to ESP8266. If all goes well you should have a working AP (Access point) from the ESP8266 the first time you run this. The AP’s name is called “ESP-GasSensor”.

Try to connect to this AP using your laptop or mobile phone, then find out what is the ip address that was assigned to you, this can be done using “ipconfig” command in windows or “ifconfig” command if you are in linux or mac. If you are using iPhone you can click on the “i” button next to the ESP-GasSensor that you are connected to.

Open your web browser and point to the ESP-GasSensor Ip address, if you are assigned with 192.168.4.10 as your up, the ESP-GasSensor is have the ip of 192.168.4.1, so you can point your web browser to http://192.168.4.1

You should be presented with the settings page where you can enter your wifi configuration. Once you had enter your WiFi access point that connects to the internet, tick the “update Wifi Config” check box, and click on “update” to save the settings to the ESP8266.

The ESP8266 will now restart and trying to connect to your WiFi router. If all goes well you should see the gas data being updated to you webserver on a regular interval. In this example you can point your browser to

http://arduinotestbed.com/GasData.php

Congratulations!! if you manage to reach this part. You should give yourself a pat on the back. Now you can tell your friends about the gas sensor that you have.

You can download the full arduino source code here.

Final adjustment

But wait you might want to re-calibrate the sensor alarm to suit your need. This is not just for show, it should trigger and alarm when the threshold of gas reach a certain level. Depends on the type of sensor that you are using you will need to calibrate this. So go get a lighter, and point the lighter towards the sensor, and without lighting the lighter, press the gas release button on the lighter, so the gas will flow to the sensor. This should trip the buzzer. If not then you need to check whether the reading goes up by looking at the webserver. If this is not working then you need to check the connection, the sensor and the buzzer. If all goes well, the buzzer should make a noise. The threshold in the code is set to 100, you should be able to find it in the following section of the code:

double threshold = 100;

Feel free to change the threshold to higher or lower depends on your need. I hope you like this project. If you do please drop me a line, and subscribe to my blog for more projects.

 

Posted on Leave a comment

IoT Motion Sensor with light

This is the extension of the earlier post IoT Temperature Sensor with ESP8266. The extension is to additional IoT Motion Sensor with light.

Here are the concept picture.

We are going to connect the PIR sensor (motion sensor) to the other free port of the ESP8266. The PIR sensor consist of 3 legs, shown in the following picture:

As you can see, there are tiny marking of +,0,- on the PCB next to the legs. So connect the “+” to 3.3V, “-” to the ground and the middle pin “0” to pin D6 of ESP8266.

To detect the motion we added the following code to our Arduino program:

void handlePIR(){
  DebugLn("handlePIR");
  motion = digitalRead(PIRpin) == HIGH;
  if (motion){
    digitalWrite(LED_BUILTIN, LOW);
    if (locklow){
      // make sure we wait for a transition to LOW before any further output
      locklow = false;
      Serial.print("motion detected at ");
      Serial.print(millis()/1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
 } else {
   digitalWrite(LED_BUILTIN, HIGH);
   if (takeLowTime){
     lowIn = millis(); // save the time of the transition from high to LOW
     takeLowTime = false; // make sure this is only done at the start of LOW phase
   }
   // if the sensor is low for more than the given pause, assume no more motion is going to happen
   if (!locklow && millis() - lowIn > pause){
   // make sure this block is executed again after new motion sequence had been detected
     locklow = true;
     Serial.print("motion ended at ");
     Serial.print((millis() - pause)/1000);
     Serial.print(" sec");
     delay(50);
   }
 }
 // post to webserver
 data = "pir_sensor=" + String(motion);
 postData(data);
}

The code above will light up the internal LED (Internal LED active LOW) when there is a motion being detected by the sensor.

In the next step we will connect the LED light to the circuit to allow us to control the light from the Internet.