Latest Entries »

 

In the previous post we’ve seen how to program ESP8266 using Arduino IDE by installing the Boards Manager.

This post is on using the powerful ESP8266 WiFi Library which is automatically installed while using the Boards Manager.When you proceed with the  board package for the ESP8266,as explained in previous post, the ESP8266 WiFi library is automatically installed for you.

             Now, any time you want to use the classes and the functions from that ESP8266 WiFi library,  use the Include statement at the top of the program first, followed by the header name

#include <ESP8266WiFi.h>

at the starting of Arduino code & start using the Classes associated with this library.

ESP8266 WiFi library is designed after the the standard Arduino WiFi library but has even more functionality than the standard Arduino library .The standard Arduino WiFi library is used for the WiFi shield or with the Arduino boards like YUN with inbuilt WiFi.

With the introduction of ESP8266 , the WiFi functionality has become much cheaper & easy to use.

The WiFi library has many classes that you can use. Each class has functions in it that are specific to that class. There’s the WiFi class, the IP address class, the server class, the client class and the UDP class.

 

class1

 

In this post we’re going to explore the WiFi class & its functions.

The WiFi class allows to establish a connection with an access point.

What’s cool about the WiFi class is that we don’t  have to create an instance of this class. We can  go ahead and start using it. It’s like the serial library of Arduino. We don’t need to create an instance of the serial library.

class2

 

First Function of the library is WiFi.begin().

The usage of this function is similar to our Serial.begin().

Just like Serial.begin() , we use WiFi.begin() .WiFi.begin() requires 2 strings as arguments. You need to pass the SSID and the password of the Access point you wish to connect.You need to pass the arguments as character arrays or strings with a lower case s.

WiFi.begin(ssid,pass);

The possible return values are

WL_CONNECTED      after successful connection is established with the Access Point

WL_IDLE_STATUS       when Wi-Fi is in process of changing between statuses

WL_NO_SSID_AVAIL     in case configured SSID cannot be reached

WL_CONNECT_FAILED  if password is incorrect

WL_DISCONNECTED        if module is not configured in station mode

 

The status function in the WiFi class, doesn’t take any arguments but it returns stuff depending on the status of the network that you’re connected to.

Usually, first, you call WiFi.begin, you pass the SSID and the password because you’re trying to establish a connection with the network. Then, what you do is you wait in a loop until WiFi.status returns the value WL_CONNECTED.

——————————

WiFi.begin(ssid,password);

while (WiFi.status() != WL_CONNECTED)

{

delay(500);

Serial.print(“.”);

}

——————————

 

WiFi.SSID();

WiFi.SSID doesn’t take any arguments but it returns the name of the SSID that you’re connected to.

 

WiFi.RSSI()

Returns the current signal strength in  dB

 

WiFi.scanNetworks()

Returns the number of discovered networks.It will not list the network names , but returns the number of networks.

WiFi.macAddress()

Returns the MAC address of the ESP device

There is a specific function available to print out key Wi-Fi diagnostic information:

WiFi.printDiag(Serial);

Here is a sample sketch to demonstrate the WiFi library.

—————————————————-

#include <ESP8266WiFi.h>

void setup()
{
  Serial.begin(115200);
  Serial.println();

//disconnect any previous connections
  WiFi.disconnect();
  delay(1000);

//scan for number of nearby networks & print SSIDs

  Serial.print("Nearby networks found  :");
  Serial.println(WiFi.scanNetworks());
  delay(500);

Serial.println("List of surrounding Network SSIDs…:");
  int n = WiFi.scanNetworks();
  for (int i = 0; i < n; i++)
{
  Serial.println(WiFi.SSID(i));
}
  Serial.println();

//connect to preferred SSID
  
  WiFi.begin("SARAVANA-ACT", "mypass123");

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

// print SSID name,local IP allotted ,MAC address & signal strength

  Serial.println();
  Serial.print("Connected to SSID          : ");
  Serial.println(WiFi.SSID());

  Serial.print("IP address allotted to ESP : ");
  Serial.println(WiFi.localIP());
 
  Serial.print("MAC Address of ESP         : ");
  Serial.println(WiFi.macAddress());

  Serial.print("Signal strength is         : ");
  Serial.println(WiFi.RSSI());

  }

void loop()
{
}

——————————————————–

The screenshot shows the result in the serial monitor of Arduino IDE

scan3

 

The Client & Server classes & their methods are shown in screen shots below :

class3

 

 

class4

Download PDF tutorial file for the WiFi library from

https://www.gitbook.com/download/pdf/book/krzychb/esp8266wifi-library

 

cooltext753793315   cooltext753790696

The ESP8266 by itself hosts a 32 bit Microcontroller on it & you can now program your ESP using Arduino IDE. Best part is that NO Arduino board is required.You can upload your code from Arduino IDE , as if you were upgrading the Firmware on ESP.

You can pretty much write any code  for an Arduino and run it on the ESP8266. Of course there is a limit to the I/O on some of the modules, but the Flash on the ESP-12E (Black) module is 4MB and the RAM is 80kB! Add to that the 80MHz 32-bit processor and you have a pretty impressive little cute Arduino.

A sample Blink example program on the ESP8266 turns out to be around 225kB, but that includes the core code.So it’s advisable to use an ESP8266 with more FLASH Memory.Generally the BLACK ones are with higher memory than the Blue ones.The new ESP12E has a Flash of whooping 4MB !!  The Arduino UNO has just 32k Flash & Mega 256k.

esp_blue_black

 

esp12e_bl_black

 

Program uploading is done at 115,200 Baud, the default for the module. But It still takes a while to upload a sketch to the module , unlike a regular Arduino.

To begin, you must install the ESP8266 board files in the Arduino IDE.

That is easy enough to do. Make sure that your Arduino IDE is latest

Open the Arduino preferences from File  —> Preferences

Image 1

 

Add the following URL to the "Additional Boards Manager URLs" seen at the bottom of Preferences Window

http://arduino.esp8266.com/stable/package_esp8266com_index.json

Image 2

 

Click OK to close the Preferences Window.

Click on TOOLS –. BOARDS—> BOARDS MANAGER

Image 4

When the Boards Manager opens, scroll to the bottom. You should see the esp8266 entry.

Select the latest version & then click on INSTALL button.

Image5

It takes a while to download & install .

 

Image 6

Once installation is over , close the IDE & start again,

Under Tools –> Boards you can now see a new list of ESP8266 Modules.

Image 7

Its time to test some example code.

While using the ESP module make sure that

Power source is 3.3v DC

CH_PD & RESET pins pulled HIGH through resistor.

You can use a development board available at

http://www.alselectro.com/wifi-esp8266-esp-12-demo-board.html

Image26

An LED is connected to GPIO4 through a resistor.

Image 22

An USB-TTL board is used to connect ESP with USB port of PC.

Rx of USB-TTL board goes to Tx of ESP board

Tx of USB-TTL goes to Rx (3.3v level) of ESP board

GND is made common.

5v of USB-TTL is connected to Vcc of ESP board.As the ESP board has a built in 3.3v regulator we can connect to 5v safely.

Connect the GPIO0 pin to GND.

 IMG_20161107_080700

 

Open the Arduino IDE & select the COM port allotted to the USB-TTL board.

Other settings are done under Tools tab as seen in screenshot below :

Image23

From File —> Examples —> ESP8266 select the BLINK sketch.

As we’ve connected an LED at GPIO4 pin , change the pinMode & digitalWrite pin to 4.

Ensure that GPIO0 is connected to GND & click on UPLOAD button.

It takes a while to compile & then uploading starts.

Image25

Once the Uploading is done the LED connected at pin 4 , starts blinking.

Remember to upload another sketch, you need to ground GPIO0 and push the reset switch. The ESP8266 will be put in UPLOAD mode.

When the upload is done, the sketch will start running. If you reset with GPIO0 still grounded, the sketch will not start running because the ESP8266 will be in PROGRAMMING mode. To exit programming mode, remove the ground from GPIO0.

In the next post we shall see how to use the built in WIFI library in your code.

cooltext753793315   cooltext753790696

This post is a practical demo on controlling an LED from a browser.

Arduino ETHERNET SHIELD is used here. The Browser acts as a CLIENT & the SHIELD acts as a SERVER listening on HTTP PORT 80.

This demo is done on a Local Area Network .This means that the PC from where Browser is operated & the ETHERNET shield both are connected to the same NETWORK. You may have a Router in top of your Network.The Ethernet shield is connected to one of the RJ45 connector of the Router using a STRAIGHT Ethernet cable.The PC from where you start your browser is also connected to the same Router , to another RJ45 connecter or through WIFI , if your Router is WIFI enabled.

Once you connect the RJ45 cable to Ethernet shield, the left LED on RJ45 socket glows Green.This indicates a successful link made to Router.

 

IMG_20161030_153619

 

 

Image 5

Digital pin 2 is used to connect to an LED through a resistor.

Digital pin 13 is occupied by Ethernet shield , so the built in LED on pin13 cannot be used.

When the Ethernet shield is connected to the Router an IP address is allotted by DHCP of the Router.As it is Dynamic & keeps changing on every boot up , we assign the IP using the code :

byte ip[] = { 192, 168, 0, 150 };

Note that , this IP should be in the same range of your Network.

To know the range , Open Network sharing center

Click on your connection & then the DETAILS tab

Here you can see the Gateway IP & IPV4 of your PC.You should assign an IP in the same range

In my case the gateway IP is 192.168.0.1

So I’m assigning the IP of Ethernet shield by changing the last byte of the address , say, 192.168.0.150

Image 1

 

Here is the sketch used in this demo :

————————————————–

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 0, 150 }; // IP address in LAN – need to change according to your Network address
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port

String readString;
int ledPin = 2;

void setup(){

    pinMode(ledPin, OUTPUT); //pin selected to control
    // Test LED
    digitalWrite(ledPin, HIGH); // set pin high
    delay(500);
    digitalWrite(ledPin, LOW); // set pin low
   
    //start Ethernet
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
}

void loop(){
    // Create a client connection
    EthernetClient client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();

                //read char by char HTTP request
                if (readString.length() < 100) {

                    //store characters to string
                    readString += c;
                }

                //if HTTP request has ended– 0x0D is Carriage Return \n ASCII
                if (c == 0x0D) {
                    client.println("HTTP/1.1 200 OK"); //send new page
                    client.println("Content-Type: text/html");
                    client.println();

                    client.println("<HTML>");
                    client.println("<HEAD>");
                    client.println("<TITLE> ARDUINO ETHERNET SHIELD</TITLE>");
                    client.println("</HEAD>");
                    client.println("<BODY>");
                    client.println("<hr>");
                    client.println("<hr>");
                    client.println("<br>");
                    client.println("<H1 style=\"color:green;\">ARDUINO ETHERNET SHIELD — LED ON/OFF FROM WEBPAGE</H1>");
                    client.println("<hr>");
                    client.println("<br>");

                    client.println("<H2><a href=\"/?LEDON\"\">Turn On LED</a><br></H2>");
                    client.println("<H2><a href=\"/?LEDOFF\"\">Turn Off LED</a><br></H2>");

                    client.println("</BODY>");
                    client.println("</HTML>");

                    delay(10);
                    //stopping client
                    client.stop();

                    // control arduino pin
                    if(readString.indexOf("?LEDON") > -1) //checks for LEDON
                    {
                        digitalWrite(ledPin, HIGH); // set pin high
                    }
                    else{
                        if(readString.indexOf("?LEDOFF") > -1) //checks for LEDOFF
                        {
                            digitalWrite(ledPin, LOW); // set pin low
                        }
                    }
                    //clearing string for next read
                    readString="";

                }
            }
        }
    }
}

——————————————————————————

  The Arduino talks to Ethernet shield over SPI Serial Peripheral Interface. So to work with the shield you need to include both the Ethernet & SPI libraries in the top of the sketch.

#include <SPI.h>

#include <Ethernet.h>

 

The next piece of information is the MAC address of the shield , usually expressed as 6 bytes.

If your Shield has the address printed , use that MAC address.Otherwise you can settle for a random 6 bytes , as it is unlikely that another device of same address exists in the same network.

The MAC address is typically included in the Arduino sketch as global array of bytes.

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

The server is assigned on  HTTP port 80

EthernetServer server(80);

PIN 2 is assigned to LED & a string variable readString is assigned to store the request.

Under void SETUP

The method begin() in the Ethernet class attempts to connect to the Network using the details passed into its arguments.

Here we pass an IP address & the Ethernet shield makes a Network connection using a STATIC IP address.

Ethernet.begin(mac, ip, gateway, subnet);

server.begin()

starts listening on the HTTP port 80

To check the IP connection press WIN Logo key +R & then type in CMD

Ping the IP address of the Shield.

If you get back result , then you’re ready to connect the client.

Image 6

On computer Networks the machines or devices play 2 different roles : CLIENT & SERVER.

For e.g a web browser is a CLIENT that connects to other machines to request web pages or files.

The device or machine that serves the information is the SERVER.

SERVERs wait until a CLIENT connects & starts conversation with them.

PORTS allow different types of messages to be received by different pieces of software running on same server.For e.g Server software that accepts connection over FTP will usually run on port 21.WEB server software usually accepts connection over HTTP on port 80. In this demo we use he WEB SERVER.

Now open up the browser on a PC which is in the same network as Shield.

Type in the address 192.168.0.150

The following CLIENT REQUEST & SERVER RESPONSE happens in the background.

Client Request :

When you surf to the IP address of the Arduino server, the web browser (client) will send a request, such as the one shown below, to the server.

GET / HTTP/1.1\r\n

Host: 10.0.0.20\r\n

The information in the request will differ, depending on the browser and operating system that the request is sent from.

The \r\n characters that you see at the end of every line of text in the request are non-visible characters (non-printable characters). \r is the carriage return character and \n is the linefeed character (or newline character).

The last line of the request is simply \r\n without and preceding text. This is the blank line that the Arduino sketch checks for before sending a response to the client web browser.

In other words, the sketch reads every character from the above request and knows when the end of the request has been reached because it finds the blank line.

Server Response :

After receiving the request for a web page from the client, the server first sends a standard HTTP response and then the web page itself.

The response sent from the Arduino is as follows:

HTTP/1.1 200 OK\r\n

Content-Type: text/html\r\n

Connection: close\r\n

\r\n

Again the non-visible characters \r\n are shown in the above response.

The println() function in the the sketch automatically adds the \r\n characters to the end of each line. The empty println() function at the end of the HTTP response simply sends the \r\n with no text in front of it.

The above request and response are part of HTTP

Web Page

After the server has sent the HTTP response, it sends the actual web page which is then displayed in the browser.

The web page consists of text with HTML tags. You do not see the tags in the browser as these tags are interpreted by the browser.

The actual HTML markup tags are shown below.

————————————————-

<html><head>

<title> ARDUINO ETHERNET SHIELD</title>

</head>

<body>

<hr>

<br>

<h1 style="color:green;">ARDUINO ETHERNET SHIELD — LED ON/OFF FROM WEBPAGE</h1>

<hr>

<br>

<h2><a href="/?LEDON" "="">Turn On LED</a><br></h2>

<h2><a href="/?LEDOFF" "="">Turn Off LED</a><br></h2>

</body></html>

—————————————————–

In the Arduino sketch you can see these HTML tags sent using

client.println command

Now the browser displays the WEB PAGE sent as response from the Server.

Click on

Turn On LED   -  to see the LED going ON

Turn Off LED   – to make the LED OFF

indexOf String function is used to search for the string LEDON or LEDOFF.

The indexOf function returns a –1 if it doesn’t find the wanted string.This function is used to make the LED ON or OFF accordingly.

0Image 2

 

Image 3

 

Image 4

 

Instead of LED you can connect a Relay board & then control any home device through the contacts of the Relay.The above setup is the basic to start with Home Automation.

This demo is done on Local Area Network .It can be extended to Internet of Things through Port Forwarding & DDNS set up which is explained in another post.

In the previous post PART 1  we explored the ways to make the local IP address of PC/ESP8266 STATIC.

In this part 2 we shall see how to make your Dynamic Public IP as STATIC using NO-IP account & then Port forward to the server started on port 350 of ESP.

PORT FORWARDING

First let us do the PORT FORWARD  settings.

For this , type in your Router’s Gateway IP in the browser & log in to Router’s Settings.Here my Router’s gateway is 192.168.1.1

The PORT Forwarding is done under VIRTUAL SERVER.

For different Router , you can check out this excellent link which guides settings for almost all types of Routers in the World.

https://portforward.com/router.htm

In my case the VIRTUAL SERVER is under ADVANCED —> NAT

 

image1

Under Virtual Server feed in the WAN & LAN ports as 350.

Under LAN IP feed in the static IP of our ESP8266.Here it is 192.168.1.10 which we made static as described in part 1.

Once the APPLY CHANGES button is clicked , the entry appears under Forwarding Table.

Image 2

 

WINDOWS FIREWALL SETTINGS

 

Next is the Windows firewall settings to allow communication through port 350.

Open Windows Firewall with Advanced Security.

Click on Inbound Rules & then New Rule.

 

Image 3

 

Select Rule Type as PORT.

protocol as TCP.

 

Image 4

Under Action select “Allow the Connection”

& tick mark all under the Profile.

Provide a Name for the Rule & save it.

Image 5

 

START SERVER ON ESP8266

Now open the Putty window where you’ve connected ESP8266 ( refer part 1 for details)

Before starting server , issue the command

AT+CIPMUX=1

Then start the server on port 350 using

AT+CIPSERVER=1,350

Image 111

Now the Server starts listening on PORT 350.

 

Convert Public IP to STATIC

The external world communicates with your ESP server using the Public IP of your Network.This IP is generally DYNAMIC which means it changes on every boot of your Router.

To make it STATIC we shall use a service called NO-IP which converts your public IP to a Domain name & follows the changes.

Visit www.noip.com

Sign up by providing your EMAIL.

Image 6

LOG IN  your NO-IP account.

Under Dynamic DNS click on ADD HOSTNAME.

Image 7

Enter the host name, for e.g , as   testmyiot  & from the dropdown select a domain , say, ddns.net.

Now your new host name is

testmyiot.ddns.net

 

Image 8

Next , click on Device Configuration Assistant.

Image 9

 

Under the dropdown select the host name we created , testmyiot.ddns.net

 

Image 10

Next step is to fill in the Device details.

Device type is SERVER

Device Brand is WEB SERVER

Router make – select your router name .If not found in list then select other

& then enter Router type as Home.

Image 12

On the Next window answer NO

We shall come back to this window shortly after setting the Router for NO-IP.

Image 13

 

On the next window , before clicking YES to log in device, go to the Router settings in browser where you typed in 192.168.1.1

Image 14

 

Click on SERVICE & then DDNS.

Most of the Routers support NO-IP & is listed on the drop down.

Select NO-IP

Image 15

Feed in the Host Name as testmyiot.ddns.net

Provide the email & password you used to create the NO-IP account.

Image 17

Click on ADD to save to DDNS Table of Router.

Now go back to your NO-IP account window.

Click YES to log in device.

Image 18

On next window click on TEST CONNECTION

Image 19

After a short time you should see SUCCESS.

Now you’re done with DDNS settings.You need not go further to Port forward tab, as we’ve already done it.

Image 20

 

Following is the procedure , in case your Router doesn’t support NO-IP .

If you do not see NO-IP under drop down of DDNS settings of Router,

go back to your NO-IP account & click YES to the question “Is there a computer always running on your Network?”.

 

Image 22

 

You’ll be taken to next window to download DUC.

DUC- Dynamic Update Client is a software which runs in the background of your PC to follow your public IP.

Download it & install.

Image 23

Before FINISH ensure to tick mark “Run DUC in the background”

Image 24

Now you’ll be asked to login your NO-IP account again

Image 25

Once you log in, the following windows appear.

Select the host name you created & click save.

Image 26

Now you can see all TICK marks in the DUC window.

DUC runs in the background & follows your public IP to the domain name you created.

Image 28

 

You can test the access to ESP server now from a distant PC.

From anywhere in the world , make open a PUTTY window.

Select RAW & feed in the host name testmyiot.ddns.net & port as 350.

Image 29

You get CONNECTED to the ESP server

 

Watch this demo video :

 

 

 

cooltext753793315   cooltext753790696

This post is all about converting your device address in Network to STATIC & establish PORT FORWARDING.

For IOT projects it is easy to test in local setup using  the LAN IP starting with 192.x.x.x .But from outside world this IP cannot be reached.Here I will walk you through the steps to contact the local IP from outside world.This procedure is a major step needed in IOT projects  , without which external control is not possible.

Following is the setup of my Network. A ROUTER is on the top of the network for which the Internet Service Provider is Airtel . The Router is WIFI enabled so that I can connect multiple devices wirelessly.

Total 3 devices are connected to the Router as shown below.

 

setup_ok

 

On switching on the power , the Router (DHCP enabled) assigns local IP addresses to all the devices connected.The IP address assigned is DYNAMIC which means , it changes every time I switch on the Router.

There are two types of IP addresses: STATIC & DYNAMIC

STATIC addresses are just that – unchanging

Dynamic IP addresses are assigned on-the-fly & keeps on changing by every reboot.

Because most home users tend to turn their computers off, even broadband connections, such as DSL and cable, continue to use dynamic addresses. If your computer is off, you don’t need an IP address so someone else might get to use it.

Each time you connect to the internet, your ISP assigns you an IP address to use. This IP address is the Public IP which others use to communicate to your PC.This IP address is DYNAMIC which changes every time you newly connect to web.

The next time you connect, you might get a different address. If you’re only connecting out to the internet, that’s all you need.

If you expect people to connect in, say you want to run a web server that you want people to be able to find and visit, you’ll most likely need a STATIC IP address. A static IP is assigned by your ISP at an extra cost which is unnecessary for a home network.

In this post I shall explain the ways of changing the LOCAL IP address  as well as the PUBLIC IP address to STATTIC.Suppose you run a web server on your ESP or Raspberry PI & wish to connect from external world.It will work only for the first time , as you use Dynamic IP to communicate.

Next time you power up , the IP address might have changed.So using a STATIC IP is a must .

 

SETTING the Local IP of PC / Laptop to STATIC :

 

In my network the PC assigned a Dynamic IP of  192.168.1.10

Run –> CMD –> ipconfig /all       reveals the  address details as seen below :

ipconfig

 

Here you can see the Default Gateway is 192.168.1.1 which is the IP of the Router .To port forward settings we need to use this IP on a browser to enter the settings , which we will see later in the post.

Local IP assigned to the PC is the IPV4 address 192.168.1.10

Let us change this to STATIC now.

Open the CONTROL PANEL –> NETWORK and Internet  –> Network and Sharing center

Click on “Change adapter settings”

Image 10

 

Right Click on the Network connection & select Properties

Image 11

 

Select the Internet Protocol Version 4 & double click on it.

Image 12

Now you see the following screen where selection is done by default to obtain IP automatically.

Change this selection o “USE the following IP address “ & enter the IP as 192.168.1.150

The first three bytes must match that of the default gateway address which is 192.168.1.1

The last byte can be assigned at your will , within the IP range allowed by the router.

Here I change the IP to 192.168.1.150.  Note that only the last byte I’ve changed.

Subnet mask & Default gateway are entered as seen in the ipconfig /all window above.

 

Image 13

 

DNS server address also changed as seen in the screen shot below

Image 14

Image 15

Reboot your PC to see the changes effective.

Now the IP address of my PC will be 192.168.1.150 & remains STATIC even after reboot.

The above task can also be done automatically by a trial software :

PF_1

 

You can download the trial version here :

http://portforward.com/store/download-instructions/pfconfig/

The trial version allows all other tools except port forwarding.Open the tool & click on STATIC IP Address & follow the guidelines to fix your PC’s IP as STATIC.

 

STATIC IP for other devices ESP & Raspberry PI:

 

For making the Raspberry Pi’s Local IP to STATIC you can follow this blog :

https://www.modmypi.com/blog/tutorial-how-to-give-your-raspberry-pi-a-static-ip-address

 

Regarding the IP of ESP8266 we need not change anything.Once the STATION IP is assigned to ESP8266 , the module remembers the Access Point it has connected & the STA IP assigned .

or issue the command

AT+CIPSTA=”192.168.1.5”

Image 16

The ESP module remembers the Access Point it has joined with & the IP till you quit the AP.

But on Reset it seems to get changed.

The only way to assign STATIC IP to ESP module is through the Router settings.

In your browser type in the IP address of your Gateway , here it is 192.168.1.1

Under LAN setup look out for DHCP settings.

In latest Routers you see a setting called DHCP RESERVATIONS.

In the IP Address field, type the IP address to assign to the computer or server.
Choose an IP address from the router’s LAN subnet, such as 192.168.1.x.

Type the MAC address of the ESP MODULE server.
As the ESP has already joined the AP, it  is already on your network, you can copy its MAC address from the Attached Devices screen and paste it here.

Here I will show an example of setting the Static IP in DHCP Reservation under BEETEL Router

In almost all the Routers the settings are the same.Just look out for the wordings Open-mouthed smileHCP RESERVATION” or “DHCP STATIC “ under the LAN setup.

 

dhcp1

 

Under DHCP STATIC tab , enter the IP address you want to fix for the ESP module

dhcp2

 

Feed in the MAC ADDRESS of the ESP device.

dhcp3

You can learn the MAC address from the AT command AT+CIFSR of ESP module.

dhcp4

The MAC address to be entered without any special character like colon.Please check out your Router settings for entering the MAC address (generally given near the MAC address box , how to feed in the address).

dhcp5

Click on ADD to save the settings

dhcp6

Now RESET or power back the ESP module.

The IP address will be the same for ever.The Router will always assign the IP you’ve set for the ESP module.

dhcp7

 

In a  D-Link router, it is under  the setup.Go to Setup / Network settings / DHCP reservation. You can then ask the router to give a given MAC address a fixed IP address.
Alternatively, the ESP can request a certain IP address from the router which we’ve seen in the example of Beetel Router above.

Now that the STATIC IP is assigned, let us see the methods of PORT FORWARDING & converting your public IP to STATIC using NO-IP account in PART 2.

 

In the previous post part-1 I explained the initial setup of starting a Server on PC on a port , setting the Windows firewall to allow the port for external communication , PORT FORWARDING set up in the Router config, etc..

https://alselectro.wordpress.com/2016/09/25/gsm-connecting-to-a-server-on-a-port-by-tcpip-part-1/

In this part 2 I’ll show a practical demo of sending Temperature data to the Server.

As given in part 1 , start a server on distant PC on port 350 & do the port forwarding settings in Router config as explained.

A LM35 sensor is connected to pin A0 of Arduino & a GSM SIM900A is connected to pins 7 , 8 , Gnd of Arduino. As Soft Serial library is used in the code , pins 7 & 8 are declared as soft Rx & Tx.

The Rx pin goes to Tx of GSM , Tx connected to Rx of GSM , GND is made common.An external power source of 12v 1A is used for the GSM.

Download the Arduino code HERE

————————————-

#include <SoftwareSerial.h>
SoftwareSerial myGsm(7,8);
float temp;
int tempPin = 0;
void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);

myGsm.println(“AT+CIPSHUT”);
delay(1000);
printSerialData();

myGsm.println(“AT+CIPMUX=0”);
delay(2000);
printSerialData();

myGsm.println(“AT+CGATT=1”);
delay(1000);
printSerialData();

myGsm.println(“AT+CSTT=\”bsnlnet\”,\”\”,\”\””);//setting the APN,username & password
delay(5000);
printSerialData();

myGsm.println();
myGsm.println(“AT+CIICR”);
delay(6000);
printSerialData();

myGsm.println(“AT+CIFSR”); //get IP address
delay(2000);
printSerialData();

myGsm.println(“AT+CIPSTART=\”TCP\”,\”122.178.80.228\”,\”350\””);
delay(5000);
printSerialData();
delay(5000);

myGsm.println(“AT+CIPSEND”);
delay(2000);
printSerialData();

sendtemp();
delay(3000);
myGsm.println(“AT+CIPCLOSE”);
printSerialData();

myGsm.println(“AT+CIPSHUT”);
delay(1000);
printSerialData();
}

void loop()
{
}

void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

 

void sendtemp()
{
temp = analogRead(tempPin);
temp = temp * 0.48828125;
Serial.print(“TEMPERATURE = “);
Serial.print(temp);
Serial.print(“*C”);
Serial.println();
delay(5000);
myGsm.println(temp);
delay(3000);
printSerialData();
myGsm.write(0x1A);
delay(3000);
printSerialData();

}

———————————————-

The Analog pin A0 is assigned as tempPin to read the LM 35 sensor data.

Initially any previous IP connection is SHUT  using the command

AT+CIPSHUT

This is essential to start a fresh TCP/IP comnnection.

Single IP connection mode is set by

AT+CIPMUX=0

GPRS is attached using

AT+CGATT=1

Task is started with the command

AT+CSTT=”APN”,”USER NAME”,”PASSWORD”

The Access Point Name of the mobile service provider can be known  by placing the SIM on your Android mobile. It’s shown under

Settings  –> More..  –>  Cellular Networks –> Access Point Names

In my case the APN is bsnlnet , user name & password are empty

AT+CSTT=”bsnlnet”,””,””

 

Then we bring up the Wireless connection with GPRS using

AT+CIICR

This takes a little moment , so a delay of 6 secs is a must in the code.

The IP address assigned by GPRS is obtained by

AT+CIFSR

Now we start up TCP connection with Server IP address & Port number of distant server

AT+CIPSTART=”TCP”,”122.178.80.228″,”350”

Once the connection is established , we send data using

AT+CIPSEND

A CTRL+Z is required to send data which is executed using hex 1A

 

Upload the code to Arduino & open the Serial monitor to watch the AT commands executed

tcp_list

 

Following is the screen shot at the Server side.

 

Image 3

 

 

cooltext753793315

This tutorial is of 2 parts.

First part explains the following :

–Starting a Server on your PC  & start listening on a port (say 350) . For this we use SOCKET TEST or HERCULES software

— Once the port is listening , we test communication locally using PuTty

— Windows Firewall setting has to be done for a NEW INBOUND RULE allowing port 350 for communication.

— For connecting to this port from external world , PORT FORWARDING to be done in Router’s Virtual Server setting so that any contact to the public IP is routed to the PORT 350 .

 

Second part is practical demo using GSM SIM900 or ESP8266 with Arduino.

 

The following picture shows my simple home network connections.A BINATONE make Router is used to connect to the Internet provider Airtel Broadband.The IP address of the Router is

192.168.1.1

which is the Gateway IP address used to access the settings on Router.My Laptop is connected over WIFI to this Router.The Router assigns a local IP address to my PC which is

192.168.1.150

Apart from these, the Internet Provider assigns a Public IP to my Network which is

122.178.80.228

This is the IP by which external world can contact my network.

Note that all these IP addresses are DYNAMIC & changes every time I power up the Router.

In another post I’ll explain how to make these IP addresses STATIC , so that the IP remain the same always.

set1

 

All the Network Tools I’ve used for this demo can be downloaded HERE.

Let us start  a server on port 350 using the SOCKET TEST tool.

This tool allows us to start a server easily.Click on the SERVER Tab & then feed in the port number where you want to listen.

Click on START LISTENING.

soc1

Now the server is up & running.It starts listening on port 350.

Remember to avoid the standard ports like 80 ( http) , 21 (FTP), 23 (TELNET), 22 (SSH) ,etc which are well known ports ,pre assigned for the particular protocol.

The dynamic range of port number you can assign goes up to 65535 or 2^16-1 (16 bits).

The IP address of the router can be known from the command window

RUN –> CMD –> ipconfig

The Default Gateway IP is the address of the Router.

RUN1

 

LOCAL TESTING TOOLS (optional)

 

Once the port is assigned for the server , you can use the ADVANCED PORT SCANNER tool to verify the port on the particular IP.

In the screen shot below you can see that the port number 350 is discovered as a TCP Server port on my PC whose local IP is 192.168.1.150

 

port_scanner

While the port scanner is scanning , you get messages on your SOCKET TEST window.

Here you can see the Port scanner software connecting to the port & then disconnecting after scanning.

port_message

 

Alternatively you can use a PUTTY serial port tool to test local communication.

Select the connection type as RAW & provide the host IP which is 192.168.1.150 & thtn the port number 350

putty1

Click on open , to see the New client connection on the Socket test window.

putty4

 

Now you can test two way communication between  socket test (server) & putty ( client).

putty2

 

WINDOWS FIREWALL SETTINGS

 

The Windows Firewall settings has to be done to allow the port 350 to listen from outside.

Open the Windows Firewall & Advanced Security window.

Click on Inbound Rules & then New Rule.

windows1

 

Select the Rule Type as PORT & in the next screen select protocol as TCP.

Under Specified local ports feed the port number as 350

windows2

 

Under Action window select Allow the Connection

Next window is Profile window , here tick mark all – Domain,Public & Private.

Provide a name to the Rule & save it.

Now your PORT 350 is allowed to listen by the Windows Firewall.

windows3

 

PORT FORWARDING

This step is final where you redirect the incoming request to the port number of local IP where the server is started.

Here my local PC’s IP is 192.168.1.150   &  server is started on port 350.

Anyone from external world connecting to my public IP has to be directed to the port 350 on local IP 192.168.1.150.

This is called PORT FORWARDING , which is very widely used in CCTV Remote viewing & in Gaming.

The setting has to be done in your Router.

Type in the Gateway IP of your Router , here it is 192.168.1.1 , on your browser & provide the user name & password.

Here is an excellent website showing all screen shots of almost all Routers in the world

https://portforward.com/router.htm

 

Mine is BINATONE Router.

You’ve to search for something called VIRTUAL SERVER on the router setting.

 

ROUTER1

 

For my Router it’s hidden under ADVANCED SETUP –> NAT –> VIRTUAL SERVER

For more details you can visit the above portforward link

Create a new Virtual server listing by entering the

— Port number , which is 350 .Enter same number at all fields like start & stop.

— Local IP address , here you provide the IP where server is started , 192.168.1.150

— save the listing

router3

 

Once saved , the port number 350 is open to outside world.

Online port open test tools are available

www.canyouseeme.org

www.yougetsignal.com

 

Once you open the link , your public IP will be automatically shown.

Fill in the PORT number to be checked & click on CHECK button.

If you see SUCCESS , then you’re done with PORT FORWARDING

 

canyou1

 

port_open

 

Following is the list of AT commands used by the GSM SIM900A to contact the server.

This is for part 2 of the post.PART 2 LINK HERE

gsm1

gsm2

cooltext753793315   cooltext753790696

 

 

This post is on retrieving particular Data from a web page using SIM900A & Arduino.

For e.g we shall retrieve the Blog Status hits of my blog in which you’re reading this.

We’ve to create an API link for this data so that data can be retrieved using SIM900A.

To create API link we use the THINGSPEAK.com website.

First let us read the XPATH details of the data wanted as below :

The procedure is related to Google Chrome WebBrowser

 

Image 1

 

Right click on the data to be retrieved & click on INSPECT .

 

inspect

 

A highlighted code will be displayed on which Right click & then select COPY  –> COPY XPATH

XPATH

 

The copied XPATH detail has to be used in THINSPEAK account to create the API link.

Open your thingspeak account & click on APPS –> THINGHTTP

 

thing1

Click on NEW THINGSPEAK to create a new “thing”.

thing2

 

You can provide a suitable Name for the App & under URL provide the website link from where you want the data from.

Method is GET & version is 1.1

thing3

 

Scroll down to bottom & under the PARSE STRING field paste the XPATH copied from the website.

thing4

Click on SAVE & you see the API LINK generated.

thing5

 

You can use this API link in your browser to confirm the data retrieved.

Image 15

Now let us see the practical application using SIN900A GSM & ARDUINO.

The connections between Arduino & GSM are :

Rx of GSM —> pin 8 (Tx) of Arduino   (since we use the SoftSerial in Arduino code , we declare pins 7 & 8 for Serial communication)

Tx of GSM –> pin 7 (Rx) of Arduino

GND –> GND

A separate power source is required for the GSM.

Following are the AT commands used

http

DOWNLOAD Arduino code HERE

————————————————————

#include <SoftwareSerial.h>
SoftwareSerial myGsm(7,8);

void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);

myGsm.println(“AT+CGATT=1”);
delay(200);
printSerialData();

myGsm.println(“AT+SAPBR=3,1,\”CONTYPE\”,\”GPRS\””);//setting the SAPBR,connection type is GPRS
delay(1000);
printSerialData();

myGsm.println(“AT+SAPBR=3,1,\”APN\”,\”\””);//setting the APN,2nd parameter empty works for all networks
delay(5000);
printSerialData();

myGsm.println();
myGsm.println(“AT+SAPBR=1,1”);
delay(10000);
printSerialData();

myGsm.println(“AT+HTTPINIT”); //init the HTTP request
delay(2000);
printSerialData();

myGsm.println(“AT+HTTPPARA=\”URL\”,\”http://api.thingspeak.com/apps/thinghttp/send_request?api_key=VV7WQ9DS19E2BNNI\””);// setting the httppara,
//the second parameter is the website from where you want to access data
delay(1000);
printSerialData();

myGsm.println();
myGsm.println(“AT+HTTPACTION=0”);//submit the GET request
delay(8000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
myGsm.println(“AT+HTTPREAD=0,20”);// read the data from the website you access
delay(3000);
printSerialData();

myGsm.println(“”);
delay(1000);
myGsm.println(“AT+HTTPTERM”);// terminate HTTP service
printSerialData();

}

void loop()
{
}

void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

—————————————————————-

AT+CGATT=1  enables the GPRS CONNECTION

AT+SAPBR is used to declare the Connection Type as GPRS

& Then the APN –Access Point Name of the mobile service provider is given.

An empty string also will work.Or you can slide the SIM into your Android mobile

under Settings –. More –> Cellular Networks  –> Access Point Names

you get the APN details

AT+SAPBR=1,1  enables the GPRS & APN settings & then HTTP is initialized with AT+HTTPINIT

HTTP parameters are then provided as “URL” & the API link we created earlier.

Note to use HTTP ( not HTTPS) in the link, as we use AT commands for HTTP only here.

AT+HTTPACTION=0 enables GET action

The GSM respons with

+HTTPACTION:0,200,12

Here 0 means GET action & 200 means OK , 12 bytes are retrieved.

If you get 600 instaed of 200 ,then it means a Network Error.

AT+HTTPREAD command is used to read the Data.

 

Image 11

cooltext753793315   cooltext753790696

 

A6 GSM  is introduced by the makers of ESP8266 , AI-THINKER.

The module is much cheaper than SIM900 & connections are quite simple.In this post we shall see how to connect with Arduino to make a call & send SMS.

A mobile adapter is enough to power up the A6 GSM module.The Vcc pin of GSM must be looped with PWR_KEY pin.This acts as a chip enable.You can leave this connected or remove after a moment.The module just requires a HIGH trigger at PWR_KEY pin while started.

A valid SIM is used at the back side of the module.The SIM slot provided is for a Micro SIM.If you ‘ve a Nano SIM you need to use a converter to fit the slot.

The RxD pin of A6 GSM is connected to Tx of Arduino

The TxD pin of A6 goes to Rx of Arduino.

GND pin of A6 to GND of Arduino.

 

Connection

 

 

PIN_DETAILS_A6

Initial TESTING

Power up the module & then after a moment make a call to the SIM number used in the GSM module from another phone.If you get the RING Back tone , it means the module is ready.As there is no LED indication provided , this initial step is required to confirm working.

 

Making a CALL

 

Connect the USB cable of PC to Arduino & upload this code for making a call.Remember to disconnect connections at Rx/Tx before uploading the code.

Image 1

 

The mobile number to be called is stored in an Array of char variable.

In the void setup() code we begin Serial communication at 9600 baud.Though the default baud rate of A6 GSM is 115200 , it is effective to use 9600 baud .

ATD command followed by the number to be called is used to make a call.

A semicolon at the end is not a must as in SIM900.The call will be made even if you do not use a semicolon.

After a delay of 8 secs ATH command is sent to terminate the call.

You can open the Serial monitor of Arduino & watch the AT commands landing.You should set the baud rate as 9600 in the Serial monitor as well.

The void loop() function is left empty.In case you try the code inside loop , the call will be repeatedly

made for ever.

 

Sending SMS

Now let us see the method to send SMS.

Following screenshot shows the code for sending SMS.

Image 2

 

DOWNLOAD Arduino code HERE

AT+CMGF=1

which will allow you to read and write SMS messages as strings instead of hexadecimal characters.

Serial.println is used to send the AT command with a New line (Enter).

After a delay of 2 seconds next command

AT+CMGS=”phone_no.”

is sent.The target phone number is to be given within double quotes. Note the usage of

Serial.write(0x22)  which is the ASCII equivalent for double quotes.

0D followed by 0A are the ASCII equivalents for  CARRIAGE RETURN & LINE FEED.

The delay of 2 seconds is a must after setting the GSM to text mode AT+CMGF=1

Try this code without the delay , you won’t get response.

After the 0D , 0A a delay of 2 seconds is provided & then the message to be sent is given.

CTRL+Z is finally given to send the message.

This is provided by the ASCII equivalent 1A or char(26)

Watch this video :

 

 

cooltext753793315    cooltext753790696

TOUCH screen LCDs are now available for use with Raspberry PI.

7 Inch LCDs work straight from the box as soon as you plug it onto your PI.No driver is required , but the touch response is poor & screen width is not full.

This post walks you through the steps of installing proper Drivers for touch to work smoothly & also installation of virtual keyboard is introduced.

The 7 inch LCD used here has a resolution of 800 x 480 pixels & the screen is Capacitive Touch.

HDMI interface is provided for Display &  USB interface for touch control. Both the HDMI & USB cables are provided in the box.

Connect the HDMI cable to the HDMI port of Raspberry PI & THE USB cable to any one port of the RPI.Slide the mini switch to ON position.

Provide a 5v 2Amp power source to the RPI , no separate power is required for the LCD

Image 2

 

7in_1    7in_3

 

Connect the RJ45 cable from the Internet providing Router to the RJ45 jack of Raspberry PI.In case of PI3 also this internet connection is a must for driver download & setup.Later you can switch on the WIFI on PI3 to connect with internet.

Insert the micro SD card with the latest RPI3 RASPBIAN Image on to the PI & switch ON the power.

You can see the initial screen is not Full screen. But interestingly , the touch will work.

Image 3

 

step 1 : CONFIG.txt editing to get FULL Screen Display :

To get the full screen display , you need to edit the CONFI.TXT file inside /boot folder.You can remove the SD card & plug it to PC using a card reader.

Open the folder & look out for the CONFIG.TXT file .Open this file using Wordpad or Notepad++.

Scroll down to the end of the file & append these lines :

Image 4

 

Setting max_usb_current=1 sets the available current over USB to 1.2A (default is 600mA)
This can help if you have a decent power supply (2A, at least) and need to power the external Touch screen display.

For supporting HDMI modes that aren’t from the official CEA/DMT list of modes
use  hdmi_mode=87

& then define the CVT – Coordinated Video Timings

The  hdmi_cvt 800 400 60 6 0 0 0
defines the timings of the component video signal

hdmi_cvt=<width> <height> <framerate> <aspect> <margins> <interlace> <rb>
width        width in pixels
height       height in pixels
framerate    framerate in Hz
aspect       aspect ratio 1=4:3, 2=14:9, 3=16:9, 4=5:4, 5=16:10, 6=15:9
margins      0=margins disabled, 1=margins enabled
interlace    0=progressive, 1=interlaced

 

Save this changes.Remove the SD card & plug it to RPI.

On rebooting you can find the FULL SCREEN display , but sadly the TOUCH performance will degrade. The touch selection will not be the one you insisted on touch.

To solve this problem you need to install the drivers.

 

step 2 : TOUCH DRIVER DOWNLOAD & Preparation

To install the Drivers , open the browser on PI & browse to

http://www.waveshare.com/wiki/5inch_HDMI_LCD

Scroll down to the driver section & download the driver which says

LCD-show-160811.tar.gz

http://www.waveshare.com/w/upload/3/3d/LCD-show-160811.tar.gz

driver

 

Click on the link to Download.

By default the tar file will be downloaded to  /root/Downloads

down_root

Using FILE MANAGER locate this folder & copy the downloaded tar file.

Now paste this file under /home/pi/Downloads

Right click the file & click on Extract Here..  to unzip the file.

down_2

 

down_3

Now you can see the unzipped folder.

Copy the PATH to this folder or note down the path , as we need it to install from within the Terminal.

unzip2

 

step 3 : DRIVER INSTALLATION

 

Open the Terminal & change directory to the PATH copied as in above step.

The path is  /home/pi/Downloads

Note the capital D in Downloads , as Linux is case sensitive.

To list the contents use ls  command

The list will display the folder LCD-show which contains the driver we need.

 

lcdshow1

Change Directory to LCD-show.

ls to list the contents

LCD-800×480-show  is the driver we need to install.

 

lcdshow2

To install use the command  dot forward slash LCD7-800×480-show

  ./LCD7-800×480-show

lcdshow_ins

The RPI will Reboot automatically & displays Full Screen.

Now try the TOUCH Functionality.It will be breeze to use the touch now, after driver installation.

 

step 4 : VIRTUAL KEYBOARD Installation

Now is the time to install the virtual keyboard .This avoids the physical keyboard & is a must for a touch screen.

Under Terminal type in

sudo apt-get install matchbox-keyboard

The keyboard installation starts.

When prompted , enter y to continue.

 

key2

Once the installation is over you can see the KEYBOARD under Accessories.

keyboard

 

If the KEYBOARD Icon is not seen under Accessories , click on

Preferences —> Main Menu Editor.

pref1

Under Main Menu Editor , put a tick mark against KEYBOARD.

A reboot is required.

pref2

Now open the KEYBOARD & enjoy.

keyboard2

 

Watch this demo VIDEO :

 

5 inch TOUCH SCREEN for RPI :

http://www.alselectro.com/7-inch-touch-screen-for-rpi–hdmi.html

 

cooltext753793315    cooltext753790696