Sunday, October 29, 2017

state of IOT device

One of my friends visited a while ago and put some valid questions.
He: "Why are you writing this blog, there are already millions of tutorials regarding configuring esp8266."
Me: "Most tutorials just talk of a specific thing to do with esp. I am writing to build a real product."
He: "There are already Hundreds of similar products in the market, why are you building your own?"
At this point, I have to pause and ask my self why? Although I did not get a satisfactory response but yet I do not have those devices in my house. Hopefully by the time I complete building this whole product I have an answer.


Past few months, was bit busy and hence could not work this.

So, in the previous post, we have seen how we can send a command to the ESP module and made the module work on those commands. Eventually, we would require knowing if the command is completed or not, or what is the current status of the esp module.

In this post we would see how to respond from the esp module also, we are going to see how we can respond a small webpage from esp.

Tools: Nothing new, same tools we used in the previous post.

(You may copy code and refer from my git repo WifiConnect.ino file if you run out in an issue).

Lets first understand what we wanted to do. The user makes an HTTP request to the esp, means the esp is working like a web server here. The HTTP request must also respond something, right? so we will return an HTML string as a response. The HTML will render as a page in the browser who made the request.
To achieve this we will be using two functions of client object println() and print(), both of these accepts a string and does output the string to the connected client. the only difference in these two functions is the println causes a new line after the string hence the whole text goes structured to the client. we would use the println to send the whole line while print to go string concatenated over multiple statements.

We are going to pick up where we left in the previous post and add following lines below the 'if' statements, where we digitalwrite the HIGH / LOW to LED_BUILTIN.

client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one

These lines will respond header to the

client.println("<!DOCTYPE HTML>");
client.println("<html>");

From here the HTML starts, we are sending doctype and starting <html> tag.

client.print("Led is now: ");
if(value == HIGH) {
client.println("On");
} else {
client.println("Off")
}

So inside the <html> node, we would just send the current value of our variable 'value'. So it would be like 'Led is now: On' or 'Led is now Off'

client.println("</html>");

The last line is just the closing statement of html tag we opened.

We are all done, just upload the sketch to esp and lets test.

Now when you call the same URL as we did in the previous post, in addition to turning led on or off you will also get the set value. You may also verify the whole response by checking the source of the responded page.

Now you have learned how to create a small web server in esp and let it do some digital functions also how to respond from that web server. You may try out my other examples in the same GitHub repo to master coding esp, you will find example to creating an on/off switch using relay and capacitive touch sensor, and also you can find example for creating a LED strip with patterns. I will try to update readme in each example of GitHub to show the plan and how to use it.


In the Next few Posts we will concentrate on creating servers so that the esp devices can be controlled from inside and outside of our home as well as we will try to integrate them with various assistants like Google assistant, Alexa, Siri and others.

Sunday, June 4, 2017

my First IOT Device

My First IOT Device

Hi There, Hope you all are enthusiast about building you connected (IOT) device.

In the previous post, we have uploaded a blink sample to ESP and learnt how to program the ESP (Wemos) module. In this post, we are going to connect the Wemos programmatically to the Wifi network and control the Wemos via WiFi.

Tools: Nothing new, same tools we used in the previous post.

(You may copy code and refer from my git repo WifiConnect.ino file, if you run out in an issue).

The process flow we are looking here is:

WiFiConnect processflow.png

Following are the code Steps you need to connect the Wemos module to Wifi Router, We will take the code base from the previous Blink code:

YouTube Video, Uploading shortly...

  1. Make sure Arduino is configured as mentioned in the previous post to program ESP modules.
  2. Open the Blink Example as shown in previous post and Save As (whatever you like) in your workspace.
  3. The first line requires the inclusion of a header file ESP8266WiFi.h, This includes everything you would require to connect the ESP to Wifi.
#include <ESP8266WiFi.h>
  1. Define constants to hold your router SSID and Password, and a variable value to hold current value of the LED.
const char* ssid = "ssid name";
const char* password = "ssid password";
int value = LOW;
  1. Create a server at port 80 to listen and respond.
WiFiServer server(80);
  1. In setup() procedure we would connect to wifi and setup our server.
    1. Create serial process, We need Serial to figure out the IP of this device when it is connected to Wifi. We will add a short delay so that serial monitor can initialize.
Serial.begin(115200);
delay(10);
    1. Not necessary but we will initialize the LED to be off.
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
    1. Connect the Wifi to the SSID with the password provided. Don’t forget to set the SSID and password, of your home wifi, in the constants we defined in step 4.
    2. Put a while and a delay to check if wifi connection is successful.
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
}
    1. Now we will use the Serial to send the IP of the device to serial monitor. (You could you serial to send any debug data or info to serial monitor).
Serial.print(WiFi.localIP());
    1. Here we finish with the setup.
  1. The loop() process will continue to listen to client request and process the request as required.
    1. Check if the Server is created and available.
WiFiClient client = server.available();
if (!client) {
  return;
}
    1. Wait and listen to client.
while(!client.available()){
  delay(1);
}
    1. As soon as request is sent by client, read the string sent by client and flush the object.
String request = client.readStringUntil('\r');
client.flush();

    1. Parse the request string and set the LED value as requested by client.
if (request.indexOf("/LED=ON") != -1) {
  digitalWrite(LED_BUILTIN, HIGH);
  value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1){
  digitalWrite(LED_BUILTIN, LOW);
  value = LOW;
}
  1. Now you are all done with the code. From Tools menu open the Serial Monitor.
  2. Upload the the Code to Wemos using the Upload Toolbar button. ( I believe you remember how to upload from the previous post).
  3. Watch the Serial monitor for the IP address of the Wemos when connected.
  4. In you PC or any other device, open browser and type ‘http://<ipAddress>/LED=ON’
  5. Verify the LED on the board turns on.
  6. In the browser type http://<ipAddress>/LED=OFF
  7. Verify that LED on the board turns off.


So here you see that now the device is on your wifi network and accepts commands over http request. 

The next step is to Modify the code to respond the current status of the LED (pin) and create UI  

Saturday, June 3, 2017

the ESP Module: Prepare the dev environment.


Although there are many variants of the ESP8266 module, I came across ‘Wemos D1 Mini Pro’ a few months back and this is the best module I ever have found. The Major features that led me to say it the best module are:


  • Integrated CP2104 USB-TO-UART IC: This makes programming of the module super easy. I have been trying the ESP8266-E01 to program using various USB-To-* modules but had no luck in past 1 year.
  • 16M EPROM: The other variant only have 4M memory hence this will allow pushing larger programs. The large memory will also enable you to do Over The Air updates.
  • 11 onboard IO: few other variants also have more IO but this is onboard hence you do not need external shield to access IO pins
  • Arduino: This module can be programmed using Arduino IDE which is most stable and much easy programming tool I found.
  • Dirt cheap: The module is retail at $5.50 + ~$2.0 shipping at AliExpress but if you will buy in bulk from Alibaba then you could get it for <$5 including shipping.


Well, enough bragging let’s start with what we have.



Tools:


  • A PC, of course, you need one with USB port and some processing. If you have one you still are using, that will work.
  • Arduino IDE (https://www.arduino.cc/en/Main/Software), this is an open source software and is available for Windows, Mac, and Linux. There is a web editor also available but I am not sure how to integrate new boards in it so will not cover that.
  • A Micro USB data cable, Required to power the ESP board and upload programs.
  • Other Tool: A soldering iron, Jumper wires and may be Multimeter.






Prepare the development environment.



  1. Open Arduino, Go to Preferences and add URL. http://arduino.esp8266.com/stable/package_esp8266com_index.json
This allows adding ESP as a board in Arduino

Screen Shot 2017-05-24 at 10.39.35 PM.png

  1. Now Go to Tools > Board * > Board Manager and type ESP in the filter box.
  2. Select esp8266 by esp8266 community and click install (Mine is already installed and hence you do not see install button enabled)

Screen Shot 2017-05-24 at 10.42.30 PM.png

  1. Now should be able to see the esp Modules in the Tools > Board Sub Menu.



  1. Select Wemos D1 R2 & Mini Module.
  2. Connect Wemos to USB
  3. Select the port in Tools > Port
Wemos D1 mini (4M) uses CH340G while D1 Mini Pro (16M) uses CP2104 chip to connect and program your ESP using USB. You may need to visit https://www.wemos.cc/tutorial/get-started-arduino.html to get and install drivers related to your chip and host OS.

Windows:
Windows 10 should install the appropriate drivers as soon as you connect the Wemos module, if not you may need to download and install drivers from the link mentioned above.
Once drivers are installed, open Control Panel > Device Manager and find USB to UART under ‘Ports (COM & LPT)’ jot down the Port number shown as COMx (eg COM6).
Capture_DM.PNG
Open Arduino IDE and select the jotted port from Tools > Ports list.

Mac:
Install Mac drivers corresponding to you chip from the link mentioned above.
Connect the Module through USB.
Open Arduino IDE and under Tools > Port the serial port should appear as *USBtoUART. Select the port.
Screen Shot 2017-05-25 at 7.28.20 AM.png
(The Unix-based OS will have steps similar to Mac OS, but as I do not have any active Linux machine, I could not steps and screenshots)

After all these done, you are good to go with programming your ESP module.

Test your ESP module and upload your first Program.
In this step, we are going to take blink sample and upload to ESP to test if the module is any good and will also see in brief the structure of the program.


  1. Open Arduino IDE (I believe you already have it open)
  2. Open Blink program from File > Examples > 01.Basics > Blink
  3. Upload the program to ESP module using the button Screen Shot 2017-05-25 at 8.33.37 AM.png in the Toolbar.
  4. You would see the progress in the Output Window (the black are at the bottom of the IDE) Verify that the image is successfully uploaded.
  5. Once uploaded the board should auto restart and your program should start executing. Check then led on the board continuously turns on / off with a delay of a second.

Code:
A quick explanation of the Arduino program.
The Arduino program constitutes of 2 basic functions/Methods/Procedures (whatever you want to call it):
void setup(): This is the procedure gets executed once only in the runtime of the program and that too when the board is powered or the reset button (the small push button on the side of USB connector) is pressed. You should be writing your program initialization code in this section.
void loop(): This procedure will be called repeatedly after completion of the previous cycle (By this I mean that the loop is not asynchronous). You would write your core execution logic here.
Inside these procedures, you might be curious what the keyword means.
pinMode(): as I mentioned earlier the board have GPIO pins, the pinMode procedure does set function of the pin. The procedure accepts 2 params pin name and mode. Mode = INPUT will set the pin in read mode (code can read data from the register) for code and the mode = OUTPUT will set the pin in write mode (code can write data to the register). In most of the cases we need to define the pin to a variable but in this sample, the var LED_BUILTIN is predefined by Arduino and refers to default LED on the board (Although this is not a physical pin but refers a register). Hence in the setup() procedure, we are defining the LED pin to initialize that in write mode.
digitalWrite(): This procedure also accepts 2 parameters the pin name and value. The Value can be HIGH or LOW constant when value HIGH is passed that will enable voltage >3 V on that pin causing LED to glow and when LOW is passed it will reduce the voltage < 3V hence cause LED to turn off.
delay(): this procedure holds the execution to specified number of milliseconds. The parameter passed to it is milliseconds value (FYI, 1 second = 1000 milliseconds).


Hurray….
Your ESP Module, Your PC and more importantly You are all Set-Up to develop IOT modules.




PS: Please don't mind me being very detailed, I am writing this keeping my 12 year old in mind.