Arduino Wi-Fi server. Arduino Wi-Fi server

ESP8266 Web Server with HTML Web Page

In this tutorial we are making ESP8266 web server with HTML web page. ESP8266 connects to Wi-Fi Network and we get web page in our phone and PC which is connected to same Wi-Fi network.

A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients. To implement web server on ESP, there are two ways to make your first web server first connect to your Wi-Fi router or make ESP as access point.

Web Server Step by Step

As we know that all web servers have a web page to be served. First make a web page using HTML and test it on your computer.

Step 1: Create a good looking Web page

Open your note pad and start writing HTML code. Save as index.htm.

My first web page Hello World.

and is used to give page title, which is visible in top of the browser.

tag is used for center alignment of text, is used to make text bold.

Test your web page

Open your web page in web browser. You can observe that at the top you see Title “My first web page”. And Web page with Hello World… message.

To see the changes in your HTML code simply change you HTML program and press refresh in browser. It will reflect immediately. This way you can make your webpage test it, then deploy it on ESP8266. It saves your lot of time.

Step 2: Creating web server on ESP8266

ESP can acts as access point and it can connect to access point or both.

First we make program to connect to Wi-Fi hot spot (Access Point)

Program to connect to Access point and Make web server

We need these libraries to make web server.

ESP8266WiFi.h is required for doing all Wi-Fi related functionalities such as connection, AP, etc.

WiFiClient.h this file is required to send request to web browser

ESP8266WebServer.h it handles all HTTP protocols

Define your SSID and Password of your Wi-Fi router, where the ESP connects

//SSID and Password of your Wi-Fi router const char ssid = your_ssid; const char password = password;

Web server is on port 80, you can use other ports also, default HTTP port is 80, to open web page with different port number you have to enter port number after IP address. Ex. For port number 81 you have to type 192.168.2.2:81 in browser.

ESP8266WebServer server(80); //Server on port 80

There are two ways to make web server one is to connect to Wi-Fi hot spot or make ESP as hot spot (Access Point).

This command is used to connect to your Wi-Fi Access point. The term Access Point (AP) is same as Wi-Fi Hot Spot. If the network is open you can remove password field from command.

Wi-Fi.begin(ssid, password); //Connect to your Wi-Fi router

After connection request we wait for Wi-Fi to get connect. ESP8266 once connected and disconnected afterwards due to signal loss or any reason, there is no need to give this command again, it will try to connect again automatically. This is handled by its OS, you may find some stack errors displayed in serial monitor, and these errors come from its internal OS.

// Wait for connection while (Wi-Fi.status != WL_CONNECTED)

To get IP address i.e. assigned to ESP8266 by your Wi-Fi router use this command

When client request a web page by entering ESP IP address which data to be sent is handled by subroutine and that subroutine name is defined in server.on(path,subroutine_name).

server.on(/, handleRoot); //Which routine to handle at root location

Example: If you have two pages you can define like this

Server.on(“/”,root); //192.168.2.2 (IP of ESP) this is root location

Server.on(“/page1”,First_page); //”192.168.2.2/page1” this is first page location

Server.on(“/page2”,Second_page); //”192.168.2.2/page2” this is second page location

You have three subroutines that handle client requests.

To start the server use this command

In main loop we handle client request

server.handleClient; //Handle client requests

This subroutine is called when you enter IP address in web browser and hit enter. This routine sends the test “hello from esp8266” to web browser.

Upload your own HTML code as web page

We have learned how to create web server and its basics, now we want to upload our HTML web page. It’s very simple, just replace “hello from esp8266” with HTML code.

server.send(200, text/plain, hello from esp8266!);

First we take webpage code in separate header file name it as “index.h”, our web page is now a array of characters stored in variable MAIN_page. Do not use Комментарии и мнения владельцев in this file. It is HTML data as a character array not a program. Now HTML code is in a header file.h not.html file.

index.h file

const char MAIN_page[] PROGMEM = R=( My first web page Hello World. ) text-align: justify;Now we import this header file in our program using #import “index.h”. Make sure that this file must be with arduino code file.ino

The changes in main programs are made in handleRoot subroutine which sends the web page to client, now we are sending html page change text/plain to text/html.

void handleRoot server.send(200, text/plain, hello from esp8266!);

Modified handleRoot subroutine

.ino File

/ Hello world web server circuits4you.com / #include #include #include #include index.h //Our HTML webpage contents //SSID and Password of your Wi-Fi router const char ssid = Circuits4you.com; const char password = 123456789; ESP8266WebServer server(80); //Server on port 80 //= // This routine is executed when you open its IP in browser //= void handleRoot String s = MAIN_page; //Read HTML contents server.send(200, text/html, s); //Send web page // // SETUP // void setup(void) Serial.begin(9600); Wi-Fi.begin(ssid, password); //Connect to your Wi-Fi router Serial.println; // Wait for connection while (Wi-Fi.status != WL_CONNECTED) delay(500); Serial.print(.); //If connection successful show IP address in serial monitor Serial.println; Serial.print(Connected to ); Serial.println(ssid); Serial.print(IP address: ); Serial.println(Wi-Fi.localIP); //IP address assigned to your ESP server.on(/, handleRoot); //Which routine to handle at root location server.begin; //Start server Serial.println(HTTP server started); // // LOOP // void loop(void) server.handleClient; //Handle client requests

Results

To see the result first get the IP address from serial monitor, Open serial monitor and press reset. It sends IP and shows its connection status, if it is not able to connect it will show “…….” dots in serial monitor. Check you ssid and password.

//SSID and Password of your Wi-Fi router const char ssid = your_ssid; const char password = password;

Once connected it will show following

Open web browser and enter this IP (192.168.2.2), to use domain name read this post, Make sure that your laptop or phone must be connected to the same network. You can see this web page which is we have created in all the devices which are connected to the Wi-Fi router, where the ESP8266 is connected.

In next post we will see how to make ESP8266 Web Server and Access point.

Advanced web server with data exchange with ESP8266

To get more information on all types of web and communication protocols used with Node MCU, Read my eBook NodeMCU: Communication methods and protocols.

There are many ways to make HTML website on ESP8266. You can find more advance examples like this here

ESP8266 Nodemcu Webserver using Arduino IDE (Example of Controlling LED over Wi-Fi)

One of the major applications of the ESP8266 is in creation of a web server to manage projects over Wi-Fi and in this tutorial, am going to show you how this can be achieved with the help of the Arduino IDE.

Before proceeding you can make reference to my other tutorial introducing the ESP8266 NodeMCU and how to prepare Arduino IDE for programming NodeMCU.

What is a Webserver?

A web server is a combination of hardware and software used for storing content for websites and delivering that content to clients that request for it. This content can be text, images, video or application data.

Web Server and Client Communication.

The transfer of data between a Web server and client is done using an internet communication protocol known as HTTP (HyperText Transfer Protocol). The content of most web pages is encoded in Hypertext Markup Language (HTML) and can be either static for example text and images or dynamic.

The web server in our case is the ESP8266 NodeMCU and the web client can be any web browser or mobile application.

To access files from the webserver from a web client, you need to send an HTTP GET request to the web server. The server also responds through HTTP protocol and sends the files to the client. These files are mostly HTML documents. If the requested files are not available on the web server or if the server is down due to some technical reasons, you will see a message of error 404 on the web browser.

ESP8266 Operating Modes

ESP8266 can act as a web server either when connected to an existing Wi-Fi network or as a network of its own allowing other devices to connect directly to it to access web pages. This means ESP8266 can work as a web server in three modes; Station mode, Soft Access Point mode and a combination of the previous two modes.

Station (STA) Mode

In this mode, the ESP8266 is connected to a pre-existing Wi-Fi network like a wireless router. The IP address used for the ESP8266 is assigned by the router and other connecting devices have to be connected to the same network as the ESP8266.

Soft Access Point (AP) Mode

In this mode the ESP8266 creates its own Wi-Fi network, allowing other stations to connect to it. The created network has its own SSID and IP address that is used to deliver web pages to all devices connected to this network.

arduino, wi-fi, server

It is called a Soft Access Point because it lacks the hardware infrastructure of a common AP for example it does not have access to a wired network like a Wi-Fi router. It’s like a Virtual AP and this impacts performance.

The main limitation of this mode of operation is the number of connections it can manage which is five and if your application has a heavy data flow, I recommend that you limit it to 4 connections.

Also, the created network is not connected to the internet therefore it is used in applications on local networks with a few devices.

Controlling LEDs over Wi-Fi using ESP8266 NodeMCU Webserver in STA mode.

I will now demonstrate a simple application of the ESP8266 NodeMCU as a web server where I’ll be turning an LED on and off via a webpage using a mobile phone or any other device that can access internet.

Since am using ESP8266 in Station (STA) mode, the ESP8266 module and other devices accessing the web server created must use the same Wi-Fi network.

Connecting LED to ESP8266 NodeMCU.

This setup is very simple and only involves connecting the LED to the NodeMCU pin D2 which is GPIO4.

Code for ESP8266 NodeMCU web server to control LEDs.

The code is written using Arduino IDE therefore before proceeding make sure you know how to set up Arduino IDE to use ESP8266 NodeMCU.

#include #define LED D2 //LED at GPIO4 D2 const char ssid = YOUR Wi-Fi ID; const char password = Wi-Fi password; unsigned char status_led=0; WiFiServer server(80); void setup Serial.begin(115200); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); // Connect to Wi-Fi network Serial.println; Serial.println; Serial.print(Connecting to ); Serial.println(ssid); Wi-Fi.begin(ssid, password); while (Wi-Fi.status != WL_CONNECTED) delay(500); Serial.print(.); Serial.println; Serial.println(Wi-Fi connected); // Start the server server.begin; Serial.println(Server started at. ); Serial.println(Wi-Fi.localIP); void loop // Check if a client has connected WiFiClient client = server.available; if (!client) return; // Wait until the client sends some data Serial.println(new client); while (! client.available) delay (1); // Read the first line of the request String req = client.readStringUntil(‘\r’); Serial.println(req); client.flush; // Match the request if (req.indexOf(/ledoff) !=.1) status_led=0; digitalWrite(LED, LOW); Serial.println(LED OFF); else if(req.indexOf(/ledon) !=.1) status_led=1; digitalWrite(LED,HIGH); Serial.println(LED ON); // Return the response client.println(HTTP/1.1 200 OK); client.println(Content-Type: text/html); client.println(Connection: close); client.println; // Display the HTML web page client.println; client.println; client.println; client.println; // CSS to style the on/off buttons client.println(html font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;); client.println(.button background-color: #FF0000; border: none; color: white; padding: 16px 40px;); client.println(text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;); client.println(.button2 ); // Web Page Heading client.println(LED CONTROL); // Display and ON/OFF buttons client.println(

Code description

First, you need to include the ESP8266WiFi.h Library which includes the necessary functions for connecting the ESP8266 NodeMCU with a Wi-Fi network. You can be download this library from here.

#include #define LED D2 //LED at GPIO4 D2 const char ssid = YOUR Wi-Fi ID; const char password = Wi-Fi password; unsigned char status_led=0; WiFiServer server(80);

Then declare the GPIO pins to connect LEDs. I have used GPIO4.

Add the SSID and Password of your Wi-Fi Network.

I have also declared an auxiliary variable to store the current state of the output pin using unsigned char status_led=0;

Since am creating an HTTP Server, I’ll use Port 80 which is the default port for HTTP servers. It is the port from which a computer sends and receives Web client-based communication and messages from a Web server and is used to send and receive HTML pages or data.

In the setup function, begin serial communication with baud rate of 115200 and configure the GPIO4 pin as OUTPUT and set the output pin to LOW.

Serial.begin(115200); pinMode(LED, OUTPUT); digitalWrite(LED, LOW);

The next code snippet is for starting the Wi-Fi connection using the network credentials given earlier and if the connection is successful, the web server connection is made and a message “Server started at…” followed by the IP address of the ESP8266 is printed on the serial monitor. This IP address acts as a URL used in a client’s web browser to access the Web Server.

Serial.println; Serial.println; Serial.print(Connecting to ); Serial.println(ssid); Wi-Fi.begin(ssid, password); while (Wi-Fi.status != WL_CONNECTED) delay(500); Serial.print(.); Serial.println; Serial.println(Wi-Fi connected); server.begin; Serial.println(Server started at. ); Serial.println(Wi-Fi.localIP);

In the loop function, the first code snippet is for having the server check for available client requests and if there is none, it keeps on checking. If there is a request from a client then the server will proceed with a response to the request.

WiFiClient client = server.available; if (!client) return; // Wait until the client sends some data Serial.println(new client); while (! client.available)

The next part of the code is for determining how the server handles the client’ request. I have used the variable ‘req’ to store the HTTP request.

In this application, if the LED is OFF and you click the button, the client sends a request to turn ON the LED and if the LED is OFF then a request is sent to turn it ON.

String req = client.readStringUntil(‘\r’); Serial.println(req); client.flush; if (req.indexOf(/ledoff) !=.1) status_led=0; digitalWrite(LED, LOW); Serial.println(LED OFF); else if(req.indexOf(/ledon) !=.1)

I have used two URLs to differentiate between the two requests, that is, ‘/ledoff’ and ‘/ledon’. Each of these URLs will be attached to a button so that when that button is clicked, the linked URL is sent to the server based on the status of the LED.

The request sent by the client to the server will be in the format GET /ledon HTTP/1.1 or GET /ledoff HTTP/1.1 and you can observe these URLs in the serial monitor.

The server then resolves this request from the client and after performing the required action, it sends the necessary HTTP response to the client.

HTTP headers always start with a response code ( HTTP/1.1 200 OK) and a content-type so the client knows what’s coming, then a blank line:

client.println( ) method is used to send a webpage to the client.

client.println(HTTP/1.1 200 OK); client.println(Content-Type: text/html); client.println(Connection: close); client.println;

Displaying the Web page.

The server response is in form of a web page which is essentially an HTML document and the next snipppet of code is for rendering the webpage onto a web browser with the corresponding HTML elements and CSS styling for building our webpage.

client.println; client.println; client.println; client.println; // CSS to style the on/off buttons client.println(html font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;); client.println(.button background-color: #FF0000; border: none; color: white; padding: 16px 40px;); client.println(text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;); client.println(.button2 ); // Web Page Heading client.println(LED CONTROL); // Display and ON/OFF buttons client.println(

The connection with the client is finally closed using client.stop;

When this code is uploaded to the ESP8266 NodeMCU board and you open the Arduino IDE serial monitor, the IP address of the available Wi-Fi network will be shown. For example, in my case the address is 192.168.1.11 as shown below;

You can now be able to control the LED by entering this IP address in a browser using any device that can access internet using the Wi-Fi network of the NodeMCU for example your phone or computer. The web page will appear as shown below.

The LED can be is then turned on and off from the webpage above. Whenever a given button is pressed the corresponding status of the LED is shown on the serial monitor.

How to Send Data from Arduino to Webpage using Wi-Fi

Wireless communication between Electronic devices and modules is very important, to make them ‘Fit’ in the World of Internet of Things. HTTP protocol and HTML language have made it possible to transfer the Data anywhere in the world, over the web. We have already covered some projects which use Wi-Fi with Arduino, have a look at them to Getting started :

Now in this tutorial, we are building a program to Send Data to Web using Arduino and Wi-Fi module. For this we first need an IP address of either Global or Local server, here for the ease and demonstration purpose, we are using Local Server.

Components Required:

  • Arduino UNO
  • ESP8266 Wi-Fi Module
  • USB Cable
  • Connecting wires
  • Laptop
  • Power supply

Wi-Fi Module ESP8266:

Circuit Connections:

Circuit Diagram for “Post Data from Arduino to Web” is given below. We mainly need a Arduino and ESP8266 Wi-Fi module. ESP8266’s Vcc and GND pins are directly connected to 3.3V and GND of Arduino and CH_PD is also connected with 3.3V. Tx and Rx pins of ESP8266 are directly connected to pin 2 and 3 of Arduino. Software Serial Library is used to allow serial communication on pin 2 and 3 of Arduino. We have already covered the Interfacing of ESP8266 Wi-Fi module to Arduino in detail.

By using Software Serial Library here, we have allowed serial communication on pin 2 and 3, and made them Rx and Tx respectively. By default Pin 0 and 1 of Arduino are used for serial communication but by using SoftwareSerial library, we can allow serial communication on other digital pins of the Arduino.

Note: To watch the response of ESP8266 on serial monitor, please open Serial Monitor of Arduino IDE.

Working Explanation:

First of all we need to connect our Wi-Fi module to Wi-Fi router for network connectivity. Then we will Configure the local server, Send the data to Web and finally Close the connection. This process and commands have been explained in below steps:

First we need to test the Wi-Fi module by sending AT command, it will revert back a response containing OK.

After this, we need to select mode using command ATCWMODE=mode_id. we have used Mode Mode ids:

1 = Station mode (client) 2 = AP mode (host) 3 = AP Station mode (Yes, ESP8266 has a dual mode!)

Now we need to disconnect our Wi-Fi module from the previously connected Wi-Fi network, by using the command ATCWQAP, as ESP8266 is default auto connected with any previously available Wi-Fi network

After that, user can Reset the module with ATRST command. This step is optional.

Now we need to connect ESP8266 to Wi-Fi router using given command

Now get IP Address by using given command:

It will return an IP Address.

Now enable the multiplex mode by using ATCIPMUX=1 (1 for multiple connection and 0 for single connection)

Now configure ESP8266 as server by using ATCIPSERVER=1,port_no (port may be 80). Now your Wi-Fi is ready. Here ‘1’ is used to create the server and ‘0’ to delete the server.

Now by using given command user can send data to local created server:

ATCIPSEND =ID, length of data

no. of transmit connection

Length = Max length of data is 2 kb

After sending ID and Length to the server, we need to send data like : Serial.println(“circuitdigest@gmail.com”);

After sending data we need close the connection by given command:

Now data has been transmitted to local server.

Now type IP Address in Address Bar in web browser and hit enter. Now user can see transmitted data on webpage.

Check the Video below for complete process.

Steps for Programming:

Include SoftwareSerial Library for allow serial communication on PIN 2 3 and declare some variables and strings.

#include SoftwareSerial client(2,3); //RX, TX String webpage=; int i=0,k=0; String readString; int x=0; boolean No_IP=false; String IP=; char temp1=’0′;

After this, we have to define some functions for performing our desired tasks.

In Setup function, we initialise inbuilt serial UART communication for ESP8266 as client.begin(9600); at the baud rate of 9600.

In wifi_init function, we initialize the Wi-Fi module by sending some commands like reset, set mode, connect to router, configure connection etc. These commands have also been explained above in description part.

In connect_wifi function, we send commands data to ESP8266 and then read response from ESP8266 Wi-Fi module.

void connect_wifi(String cmd, int t) int temp=0,i=0; while(1) Serial.println(cmd);

sendwebdata( ) function is used for sending data to Local Server or Webpage.

void sendwebdata(String webPage) int ii=0; while(1) unsigned int l=webPage.length; Serial.print(ATCIPSEND=0,); client.print(ATCIPSEND=0,);

void send function is used for sending data strings to sendwebdata function. That will be further sent to webpage.

void Send webpage =

Welcome to Circuit Digest

; sendwebdata(webpage); webpage=name; webpage=dat;

get_ip function is used for getting IP address of Local created server.

In void loop function, we send instruction to user for refreshing the page and check whether the server is connected of not. When user refresh or request the webpage, data automatically transmitted to the same IP address.

We can display any data from Arduino to Webpage using this process, like Room Temperature Humidity, Clock time, GPS coordinates, Heart beat Rate etc.

#include SoftwareSerial client(2,3); //RX, TX

String webpage=; int i=0,k=0; String readString; int x=0;

boolean No_IP=false; String IP=; char temp1=’0′;

String name=

Circuit Digest

; //22 String dat=

Data Received Successfully.

; //21

void check4IP(int t1) int t2=millis; while(t2t1millis) while(client.available0) if(client.find(Wi-Fi GOT IP)) No_IP=true;

void get_ip IP=; char ch=0; while(1) client.println(ATCIFSR); while(client.available0) if(client.find(STAIP,)) delay(1000); Serial.print(IP Address:); while(client.available0) ch=client.read; if(ch”) break; IP=ch; if(ch”) break; if(ch”) break; delay(1000); Serial.print(IP); Serial.print(Port:); Serial.println(80);

void connect_wifi(String cmd, int t) int temp=0,i=0; while(1) Serial.println(cmd); client.println(cmd); while(client.available) if(client.find(OK)) i=8; delay(t); if(i5) break; i; if(i8) Serial.println(OK); else Serial.println(Error);

void wifi_init connect_wifi(AT,100); connect_wifi(ATCWMODE=3,100); connect_wifi(ATCWQAP,100); connect_wifi(ATRST,5000); check4IP(5000); if(!No_IP) Serial.println(Connecting Wi-Fi. ); connect_wifi(ATCWJAP=\1st floor\,\muda1884\,7000); //provide your Wi-Fi username and password here // connect_wifi(ATCWJAP=\vpn address\,\wireless network\,7000); else Serial.println(Wi-Fi Connected); get_ip; connect_wifi(ATCIPMUX=1,100); connect_wifi(ATCIPSERVER=1,80,100);

void sendwebdata(String webPage) int ii=0; while(1) unsigned int l=webPage.length; Serial.print(ATCIPSEND=0,); client.print(ATCIPSEND=0,); Serial.println(l2); client.println(l2); delay(100); Serial.println(webPage); client.println(webPage); while(client.available) //Serial.print(Serial.read); if(client.find(OK)) ii=11; break; if(ii11) break; delay(100);

void setup Serial.begin(9600); client.begin(9600); wifi_init; Serial.println(System Ready.);

void loop k=0; Serial.println(Please Refresh your Page); while(k 1000) k; while(client.available) if(client.find(0,CONNECT)) Serial.println(Start Printing); Send; Serial.println(Done Printing); delay(1000); delay(1);

void Send webpage =

Welcome to Circuit Digest

; sendwebdata(webpage); webpage=name; webpage=dat; sendwebdata(webpage); delay(1000); webpage = http://circuitdigest.com/; webpage=\Click Here for projects; sendwebdata(webpage); client.println(ATCIPCLOSE=0);

Introduction: Simple Webserver Using Arduino and ESP8266

The main aim of this instructable is to show how you can create a simple web server using Arduino and Wi-Fi module which displays the sensor data in the webpage.

Step 1: Things You Need

Wi-Fi module ESP8266- 01/12.

3.3V voltage regulator. (LM390/LD117)

LM35 Temperature Sensor.

External 5V source (optional).

Step 2: Pin Configurations and Preparing ESP8266

Things to know before starting with ESP8266The ESP8266 Wi-Fi Module is a self contained SOC with integrated TCP/IP protocol stack that can give any microcontroller access to your Wi-Fi network. The ESP8266 is capable of either hosting an application or offloading all Wi-Fi networking functions from another application processor. Each ESP8266 module comes pre-programmed with an AT command set firmware, meaning, you can simply hook this up to your Arduino device and get about as much Wi-Fi-ability as a Wi-Fi Shield offers.

Before you go for programming we have to prepare ESP module to work with arduino.

For ESP8266-01 the VCC pin and CH_PD pin should be short-circuit as shown in the image above.

Same way in ESP8266-12 there a certain pins which are to be short i.e CH_PD and GPIO0 with VCC, GPIO15 with GND

For ESP8266-12 without base board we have to solder it on perfboard or with connecting wires for making it breadboard compatible.

AT commands for ESP8266 is attached below.

Step 3: Circuit Connections

Voltage Regulator

The circuit for voltage regulator is shown in the above diagram. Capacitors are connected at the input and output terminal of regulator for smoothing. The capacitors used is ceramic type connected at input side and electrolytic type at the output side.

NOTE: It is not advisable to give 5v source from Arduino as ESP requires more current for its operation. Doing so can cause malfunction of Wi-Fi module. Schematics shown above is just for representation.

ESP8266 connections

VCC should be connected to the 3.3v voltage regulator and GND should be common for both Arduino and for ESP same follows for any sensors used.

If using Arduino Mega we can use Serial Port 1, i.e. Pin 18 and 19, for connecting to ESP as Serial Port 0 is used by serial monitor.

For Arduino UNO we have to assign software serial which is declared in the program. Here we are using Arduino pin 2 and 3 as Rx and Tx

Temperature Sensor

the VCC of the sensor is connected to 5v source from Arduino and GND is connected to the common ground. the Output pin is connected to Arduino‘s analog pin (A0).

Step 4: Arduino Sketch and Explanation.

Arduino sketch for this tutorial is attached below, Program is self-explanatory and contains Комментарии и мнения владельцев for all operations.

If you are using Arduino Uno then follow this.

#define DEBUG true

SoftwareSerial esp8266(2,3);

REPLACE the above text in bold with the content above the void setup ,and also Serial1 with esp8266 in program.

The above Code is to assign UNO pins 2 and 3 as RX and TX. This means that you need to connect the TX line from the esp to to Arduino’s pin 2 and the RX line from the ESP to the Arduino’s pin 3.

Step 5: Final Outcome.

As we are using ESP8266 in Mode 2 i.e. Access Point ,it will create a Wi-Fi hotspot with ssid AI-THINKER.

By default there is no password for the network. We can change SSID and PASSWORD by sending the AT commands from the program.

Accessing the Web page

First connect to the network by your device.

Open a web browser such as Google Chrome.

Go to the Address bar and enter the IP Address of your ESP8266 then press Enter. By default the IP address is 192.168.4.1.Now you will get the webpage as shown in the image.

This is just the basic work with ESP8266,but you can get more out of it, just be creative and Think out of the Box 🙂

Person Made This Project!

Did you make this project? Share it with us!

Metal Contest

Wear It Contest

Комментарии и мнения владельцев

I am unable to get this project working. during compilation an error comes up :

in void setup, Serial1 was not declared in this scope. I am a newbie and cannot figure out what is happening. When I use the IDE Serial Terminal mode what is printed is a series of AT, error, series of ATCWMODE=3, error, etc. I am completely lost. Can anyone suggest what I should do. Thanks.

Hola que tal comprobe que el codigo esta hecho ppara Arduino Mega y unos pequeños cambios para Arduino Uno, pero que puedo hacer para utilizarlo con Arduino nano ya que me genera este error exit status 1’Serial1′ was not declared in this scope

Hey! Iam using arduino UNO for this but getting errors like espcomm_sync failed,espcomm_open failed, espcomm_upload_mem failed

webpage =

Welcome to Circuit Digest

;

sendwebdata(webpage); // exzample works well just 1 small error

Thanks for lesson to Author it help me a lot to start with esp8266.

Ok, thanks for this very complete tutorial.

I try to obtain POST data from the calling request, is that possible ? How to do this ?

hello world if i want to use this vode for iot project for home automation how to turn on TV fan light relay using switch button in iot if code is available plz share that part

What are the changes need to make while using UNO R3 in this project both in circuit and code ?

With Arduino UNO and ESP8266, how to connect camera that should continuously monitor and analyze image via code and send images to webpage via Wi-Fi whenever required

thanks for the help, got it working! but I can’t get the temperature value refreshed every, lets say 5 seconds. have you tried such thing?

Hi, Works perfectly, thanks!

how can I do to send the values that I got from pin= in the webserver to another php page, like http://192.168.1.123/index.php?pin js-edit-container

I’ve made it but i want to upload value to web server so can you help me

I am trying to use ESP8266 with Arduino UNO R3. But I can’t sent the AT command as I am getting loop of FatalException(0) as below as soon as I connect to ESP8266 module: (Can’t make out what does this mean)

arduino, wi-fi, server

Fatal exception 0(IllegalInstructionCause):epc1=0x40201364, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 etsJan 8 2013,rst cause:2,boot mode:(3,6) load 0x40100000,len 1856,room 16 tail 0chksum 0x63load 0x3ffe8000,len 776,room 8 tail 0chksum 0x02load 0x3ffe8310,len 552,room 8 tail 0chksum 0x79csum 0x792nd boot version : 1.5SPI Speed : 40MHzSPI Mode : DIOSPI Flash Size Map: 8Mbit(512KB512KB)jump to runuser1 @ 1000

Following are my ESP8266 connection details:1. Vcc – 3.3v external supply (GND connected to GND of 3.3v and GND of 5v of Arduino)2. CH_PD – 3.3v3. GPIO0 – Tried keeping 3.3v (Same Error)disconnected (Same Error)GND (Same Error)–(Just tried. I know this will be the programming mode)4. Rx – Rx of Arduino UNO via voltage divider5. Tx – Tx of Arduino(Tried with exchanging Rx and TX)6. RST – Disconnected (Same Error)3.3v (Same Error)(Used the GND pulse to reset the ESP8266)

I also tried connecting RESET of Arduino UNO to GND with no success ;(.

I checked the output with all the baud rates keeping “Both NL CR” option selected. For baud rate 115200 I am getting the above exception. For rest it showing some garbage values.

I have uploaded bareMinimum example in the Arduino UNO to start with.

Any suggestion, pointer will be really appreciated.

Is my module damaged? Never used it with anything other than 3.3v though.

Wi-Fi Shield V2.0

This Wi-Fi shield features the RN171 TCP/IP module to allow your Arduino/Seeeduino to connect with up to 802.11b/g wireless networks.

The shield’s default communication protocol with the Arduino is UART/Serial, and you may select which digital pins (D0 to D7) to use for RX and TX with two jumper rows we’ve incorporated. The shield also has two on-board Grove connectors for I2C and Serial to allow the shield to be used with any of our Grove devices.

An on-board antenna allows the shield to cover a wider range and transmit stronger signals. The RN171 module supports TCP, UDP, FTP, and HTTP communication protocols to meet the needs of most wireless and Internet of Things (IoT) network projects e.g. Smart home networks, robots control, personal weather stations.

The shield is very well documented with our examples below and its user manual.

Specifications​

Hardware Overview​

The Wi-Fi shield is compatible with any Arduino/Seeeduino development board as it only requires two digital pins of your choice between D0-D7 for UART/serial communication. To install, simply stack the shield on the Arduino/Seeeduino board.

  • Serial Peripheral Interface (SPI) Connections (MOSI, SCK, MISO): These pins are not connected to any of the Arduino’s pins, they are independent and the logic level output/input of them is 3.3V. They can be used to communicate with the Arduino via SPI but a 3.3V logic converter between these pins and the Arduino’s will be needed. The data rate in SPI mode can reach up to 2Mbps. RES_Wifi: The Wi-Fi shield has an on-board Rest Button for the RN-171 module, you may also reset the RN-171 via software by sending the reset command. Additionally, if you would like to connect this pin to the Arduino’s digital 6 pin, simply solder the pad labeled P5 on the shield.
  • RN171: A super low power consumption wireless module with TCP/IP stack built in.
  • Antenna: I.PEX connector.
  • RN171 breakout section: The RN171 module has its own analog input and GPIO pins, which the shield provides access to via this breakout section. The GPIO pins (IO3, IO7, IO8, and IO9) are 3.3V tolerant while the analog input pins (S_0 and S_1) can read 0-400mV (Do not exceed 1.2V). The RN171 can be configured to use these pins by software or they may connected to other pins to use other RN171 functions such as adhoc mode. The voltage of VCC is dependent on the supply power of the Wi-Fi shield.
  • UART/Serial Select area: Two jumper rows to let you select which RX and TX pins you want to use to communicate with the Arduino.
  • Grove connectors: Analog I2C Grove (if using Arduino UNO or Seeeduino) for pins A4A5 and Digital Serial Grove for D8D9. The voltage VCC is dependent on the power supply of the board.

Pins Used / Shield Compatibility​

The Wi-Fi shield uses any two digital pins of your choice between D0 and D7 to communicate with the RN171 Wi-Fi module, however keep in mind that D0 and D1 are used by the Arduino for programming and serial communication purposes and using them might interfere with these two functions.

In the example codes in this page we use D2 and D3 as RX and TX for the shield. In this case, the jumper hats should be connected as shown below:

D2 selected for WIFI_TX, D3 selected for WIFI_RX

RN171 Wi-Fi Module​

The RN-171 is a standalone complete TCP/IP wireless networking module. Due to its small form factor and extremely low power consumption, the RN-171 is perfect for mobile wireless applications. It incorporates a 2.4GHz radio, 32-bit SPARC processor, TCP/IP stack, real-time clock, crypto accelerator, power management, and analog sensor interfaces.

In the simplest configuration the hardware only requires four connections (PWR, TX, RX and GND) to create a wireless Wi-Fi data connection. Additionally, the analog sensor inputs of the RN171 can be used as analog input pins, their rating is 0-400 mV (Do not exceed 1.2V DC).

Power: The operating voltage of the RN-171 module is 3.3VDC typically, so a voltage regulator and logic level translator are designed on the Wi-Fi shield. The LD1117 regulator on the shield converts to 3.3VDC, which supplies the RN171 module. However, due to the auto judgement schematic of power supply, the RN-171 can be powered via both 3V3 pin and 5V pin. But the supply power would be 5v if providing both 3.3v and 5v to the board. If using with an Arduino/Seeeduino board simply stack the Wi-Fi shield on the board.

Diagram of how the RN171 module is interfaced to the Arduino

GPIO_6 : The GPIO6 pin of the RN171 Wi-Fi module is by default only connected to the LED labeled D5 on the Wi-Fi shield. This LED is used to display the status of the Access Point (AP) connection. If however, you would like to connect GPIO6 to digital pin 5 of the Arduino, simply solder the pad labeled P6 on the Wi-Fi shield.

LED Status Indicators​

Fast Toggle (2 times/second): No IP address or module is in command mode.

Slow Toggle (once/second): IP address is OK.

Wi-Fi Library​

We have created a library to help you interface with the shield, in this section we’ll show you how to set up the library and introduce some of the functions.

Setup​

  • Download the library code as a zip file from the Wi-Fi Shield github page.
  • Unzip the downloaded file into your …/arduino/libraries/ folder.
  • Rename the unzipped folder WifiShield
  • Start the Arduino IDE (or restart if it is open).

Functions​

These are the most important/useful function in the library, we invite you to look at the.h files yourself to see all the functions available.

join​

  • Description:
  • Used to join a Wi-Fi access point
  • join(const char ssid, const charphrase, int auth)
  • ssid: The name of the access point you want the shield to connect to
  • phrase: The password/phrase of the access point you want the shield to connect to
  • auth: The authentication type of the access point you want the shield to connect to. Can be one of the following constants:
  • WIFLY_AUTH_OPEN
  • WIFLY_AUTH_WEP
  • WIFLY_AUTH_WPA1
  • WIFLY_AUTH_WPA1_2
  • WIFLY_AUTH_WPA2_PSK
  • WIFLY_AUTH_ADHOC
  • boolean: true if the connection to the access point was successful, false otherwise.

#include #include WiFly.h SoftwareSerial uart(2, 3); // create a serial connection to the Wi-Fi shield TX and RX pins. WiFly wifly(uart); // create a WiFly library object using the serial connection to the Wi-Fi shield we created above. void setup uart.begin(9600); // start the serial connection to the shield Serial.begin(9600); // start the Arduino serial monitor window connection wifly.reset; // reset the shield while(wifly.join(mySSID,mySSIDpassword,WIFLY_AUTH_WPA2_PSK) false) Serial.println(Failed to connect to accesspoint. Will try again.); Serial.println(Connected to access point!); void loop

The examples is based on Arduino UNO and we take D2/D3 as the SoftwareSerial pins. If you are using an Arduino Mega, D2 is not available anymore. details please refer to Arduino Software Serial Here’s an example.

As for the code, you need to do some change as well:

SoftwareSerial uart(10, 3); // create a serial connection to the Wi-Fi shield TX and RX pins.

receive​

  • Description:
  • Can be used to read data from the shield, an alternative for the Arduino’s read function.
  • receive(uint8_t buf, int len, int timeout)
  • buf: A buffer array where the bytes read from the shield is stored.
  • len: The length/size of the buffer array
  • timeout: A timeout value to know when to stop trying to read.
  • int: The number of bytes read from the shield.

char c; while (wifly.receive((uint8_t )c, 1, 300) 0) Serial.print((char)c);

See File-Examples-WiFi_Shield-wifly_test sketch for a complete example.

sendCommand​

  • Description:
  • Some our functions (e.g. join, reboot, save) act as wrappers for the text commands listed in the user manual of the RN171 module. The function sendCommand allows you to come up with your own wrapper function if ours do not meet your needs.
  • sendCommand(const char cmd, const charack, int timeout)
  • cmd: Any command from the RN-171’s user manual.
  • ack: The expected return string from the command
  • timeout: The time allowed before considering the output a bad request/response
  • boolean: true if the Wi-Fi shield responded with the ack string, false otherwise.

// our join function is wrapper for the join command, as seen below. //The string Associated is what the user manual says the RN171 will return on success. if(sendCommand(join\r, Associated,DEFAULT_WAIT_RESPONSE_TIME10)) // joined else // not able to join

See File-Examples-WiFi_Shield-wifly_test sketch for a complete example.

Wi-Fi Shield Examples/Applications​

Example 1: Send Commands to Wi-Fi Shield and Receive Response Via The Arduino Serial Monitor Window​

The Wi-Fi shield’s RN-171 module is configured by sending it the commands found in its datasheet. You may write a sketch to send the commands automatically, but this is a great example that we recommend you go through because it will teach you exactly how the Wi-Fi shield and RN-171 works.

To proceed follow the steps below, we have also created a video if you prefer to watch that

Step 1: Wi-Fi Shield Jumpers Configuration

Position the jumpers in the Wi-Fi shield such that digital pin 2 (D2) is selected for WIFI_TX, and digital pin 3 (D3) is selected for WIFI_RX as shown in the photo below. These are the pins we will use to send and receive information from the RN-171.

Pins D2 for TX, and D3 for RX

Step 2: Software/Code

In the sketch below we have created a UART object to allow us to send and receive data from the RN-171/Wi-Fi Shield. We then use this object in conjunction with the WiFly library to send data to the shield. The Arduino’s Serial object is used to print the data we receive from the shield, and to receive the commands we want to send to the shield via the WiFly/UART object.

Upload the following code to your Arduino board:

#include #include #include WiFly.h // set up a new serial port. SoftwareSerial uart(2, 3); // create a serial connection to the Wi-Fi shield TX and RX pins. WiFly wifly(uart); // create a WiFly library object using the serial connection to the Wi-Fi shield we created above. void setup uart.begin(9600); // start the serial connection to the shield Serial.begin(9600); // start the Arduino serial monitor window connection delay(3000); // wait 3 second to allow the serial/uart object to start void loop while (wifly.available) // if there is data available from the shield Serial.write(wifly.read); // display the data in the Serial monitor window. while (Serial.available) // if we typed a command wifly.write(Serial.read); // send the command to the Wi-Fi shield.

Step 3: Entering Command Mode

The WiFly RN-171 module in the Wi-Fi shield can operate in two modes: data, and command. When in data mode, the shield is able to receive and initiate connections. When in command mode, we are able to configure the module using the commands listed in its datasheet.

To enter command mode, follow these steps:

  • Open the Arduino Serial monitor.
  • Set the serial monitor to “No line ending”, baud rate to 9600.
  • Type into the Arduino Serial Monitor and press enter.
  • The module will respond with the letters “CMD”, indicating that it has entered command mode.

Let’s go ahead and test some commands, do the following:

  • In the Arduino Serial monitor window, select “Carriage return” and a baud rate of 9600.
  • Now type each of the commands in the table below into the Arduino Serial Monitor and press enter.
  • The module will output a response, as described in the table, for each command.

For a complete list of configuration commands, please see the RN-171 Reference Guide starting on page 11.

Example 2: Connect to An Access Point / Internet Router​

In this example we will show you how to connect the Wi-Fi shield to an access point (your internet router) with and without you typing the commands required:

Connecting By Typing Commands​

This section will teach you how to connect the Wi-Fi shield to an access point using commands from the RN-171 datasheet, by going through this section you will then know exactly what is happening in the background when you use our Wi-Fi Arduino libraries.

  • Upload the code in Example One to your Arduino board
  • Enter command mode:
  • Set the serial monitor to “No line ending”, baud rate to 9600.
  • Type into the Arduino Serial Monitor and press enter.
  • Type scan and press enter. The Arduino serial monitor window will output a list of comma separated values for each access point the Wi-Fi shield has found. From left to right the third value is the security mode, the last value is the SSID. This example shows a security mode of 4 with an SSID name MySSID: 01,01,-88,04,1104,1c,00,45:56:78:be:93:1f,MySSID
  • Type set wlan auth m. Replace m with the security mode number (in this example that would be 4) of the access point you wish to connect to.
  • The security modes supported by the Wi-Fi shield are listed in Figure 1 below.
  • Type set wlan phrase myPhrase. Replace myPhrase with your access point’s password/security key.

If your access point’s security type is WEP use key instead of phrase in the command above.

  • The access point’s (internet router) phrase is the password you use to connect to it from your PC. In Windows you can find it as shown in the animated image below: How to find a networks’ security key/password
  • Now that we have set the security type and phrase of the access point, we may connect to it.
  • Type join MySSID. Replace MySSID with your access point’s broadcast name.
  • The word Associated! will be displayed in the Arduino serial monitor window if successful.

A description of the commands you entered in the steps above is available in the table below. A more detailed description of each command can be found in the RN171’s user manual.

Connecting Using Our Wi-Fi Libraries​

Now that you know how to connect to an access point by typing each command it’s time to use the libraries and examples we provide.

To see code required to connect to an access point go to “File. Examples. Wifi_Shield. wifi_test”. Change the code to use your own SSID (access point name), and KEY (your access point’s password), then upload the sketch to your Arduino IDE.

#define SSID SEEED-MKT #define KEY seeed-mkt

With the sketch uploaded to your Arduino board, open the serial monitor window. If the shield was successful in joining the access point an OK message will be displayed along with the connection information resulting from the get everything command. If the shield failed to join the access point a Failed message will be displayed.

Configuring The Shield to Connect On Power-Up​

The shield can be configured to connect on power up, you only have to do this once:

  • Send the set wlan ssid mySSID command replacing mySSID with your SSID
  • Send the set wlan join 1 command.
  • Send the save command.

Now the shield will connect to the access point automatically on power up.

A description of what each command does can be found in the RN-171 datasheet and in the table below.

Setting a Static IP Address​

To have the shield obtain a static IP address from the access point, once connected to the access point, send the following commands:

Example 3: Communicating With the Network ​

This example will show you how a device such as your PC and/or phone may talk to the Wi-Fi shield.

  • Configure the module with step1-7 in Example 2’s section Connecting By Typing Commands
  • Set the listening IP port to 80 by sending the commands set IP local 80
  • Connect/Join your shield to an access point as shown in the step 8 in Example 2’s section Connecting By Typing Commands
  • Save these setting by sending the save command
  • Get the IP address of your shield with the command get ip. The IP address and port will be displayed to the right of IP= in the response (e.g. IP=192.168.0.10:80)
  • Open your web browser and type your shield’s IP address in your web browser’s URL bar and press Enter to visit it.
  • Your Arduino’s serial monitor window will display an HTTP response similar to the one below. This is the information that your browser sent to the shield to request data.

OPENGET / HTTP/1.1 Host: 192.168.0.10 Connection: keep-alive Accept: text/html,application/xhtmlxml,application/xml;q=0.9,image/webp,/;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8

The browser is now waiting for data, the Wi-Fi module can send sensor values, serve web pages, or any other data straight back to the browser! In this case, the browser is waiting for a web page. If the Wi-Fi module responds with an HTML-formatted page, the browser will display it. The next examples will teach you how to do all this fun stuff.

Example 4: Using the Wi-Fi Shield as Webserver (Serving Webpages From the Shield)​

As you saw in Example 3, an internet/web browser is able to connect to the Wi-Fi shield. Once a connection has been established (when the browser sends its HTTP request), the Wi-Fi shield may then send back HTML code for the browser to display as a webpage. In this example you will learn what is needed for the shield to reply to a web browser.

Step One: Arduino Code

Upload the following code to your Arduino board replacing myssid and mypassword with your accesspoint’s values respectively:

#include #include WiFly.h #define SSID myssid #define KEY mypassword // check your access point’s security mode, mine was WPA20-PSK // if yours is different you’ll need to change the AUTH constant, see the file WiFly.h for avalable security codes #define AUTH WIFLY_AUTH_WPA2_PSK int flag = 0; // Pins’ connection // Arduino WiFly // 2 TX // 3 RX SoftwareSerial wiflyUart(2, 3); // create a Wi-Fi shield serial object WiFly wifly(wiflyUart); // pass the Wi-Fi siheld serial object to the WiFly class void setup wiflyUart.begin(9600); // start Wi-Fi shield uart port Serial.begin(9600); // start the arduino serial port Serial.println(- WIFLY Webserver.-); // wait for initilization of wifly delay(1000); wifly.reset; // reset the shield delay(1000); //set WiFly params wifly.sendCommand(set IP local 80\r); // set the local comm port to 80 delay(100); wifly.sendCommand(set comm remote 0\r); // do not send a default string when a connection opens delay(100); wifly.sendCommand(set comm open OPEN\r); // set the string that the Wi-Fi shield will output when a connection is opened delay(100); Serial.println(Join SSID ); if (wifly.join(SSID, KEY, AUTH)) Serial.println(OK); else Serial.println(Failed); delay(5000); wifly.sendCommand(get ip\r); char c; while (wifly.receive((uint8_t )c, 1, 300) 0) // print the response from the get IP command Serial.print((char)c); Serial.println(Web server ready); void loop if(wifly.available) // the Wi-Fi shield has data available if(wiflyUart.find(OPEN)) // see if the data available is from an open connection by looking for the OPEN string Serial.println(New Browser Request!); delay(1000); // delay enough time for the browser to complete sending its HTTP request string // send HTTP header wiflyUart.println(HTTP/1.1 200 OK); wiflyUart.println(Content-Type: text/html; charset=UTF-8); wiflyUart.println(Content-Length: 244); // length of HTML code wiflyUart.println(Connection: close); wiflyUart.println; // send webpage’s HTML code wiflyUart.print; wiflyUart.print; wiflyUart.print(My Wi-Fi Shield Webpage); wiflyUart.print; wiflyUart.print; wiflyUart.print(

Hello World!

); wiflyUart.print(

This website is served from my Wi-Fi module

); wiflyUart.print(Yahoo! Google); wiflyUart.print(My Button); wiflyUart.print; wiflyUart.print;

Step Two: Get the Shield’s IP Address

Open the serial monitor window and wait for the Web server ready message to display. The serial monitor will also display the Wi-Fi shield’s IP address:

Arduino program serial comm output. The IP address of the shield is highlighted.

Step Three: Visiting the webpage

Now visit that IP address in your web browser. The webpage below should be displayed, it contains a link to Yahoo! and Google and a button that doesn’t do anything (yet):

A simple webpage with two links and one button served from the Wi-Fi shield.

When the webpage is visited the serial monitor window will also display a New Browser Request! string as shown below:

The Arduino serial comm window showing that it detected a new browser connection/request.

In case of some browsers, like Google Chrome, even typing the URL in the bar sends a webpage request, this is because these browsers try to get the webpage’s title for the user’s convenience even before he/she visits the webpage.

Example 5: Controlling The Arduino Digital Pins From a Webpage (Toggling LEDs From an Webpage)​

In this example we will create a webpage with three buttons to control three different digital pins in the Arduino.

For this tutorial follow the steps below. We have also created a video where we explain the code in more detail.

Step 1: Hardware

arduino, wi-fi, server

Connect three LEDs and resistor to digital pins 11, 12, and 13 as shown in the schematic below:

Three LEDs and 1k resistors connected to pins 11, 12, and 13.

Step 2: Arduino Sketch

Upload the following code to your Arduino board but replace mySSID and myPassword with your access point’s SSID name and password:

#include #include WiFly.h #define SSID mySSID #define KEY myPassword // check your access point’s security mode, mine was WPA20-PSK // if yours is different you’ll need to change the AUTH constant, see the file WiFly.h for avalable security codes #define AUTH WIFLY_AUTH_WPA2_PSK int flag = 0; // Pins’ connection // Arduino WiFly // 2 TX // 3 RX SoftwareSerial wiflyUart(2, 3); // create a Wi-Fi shield serial object WiFly wifly(wiflyUart); // pass the Wi-Fi siheld serial object to the WiFly class char ip[16]; void setup pinMode(11,OUTPUT); digitalWrite(11,LOW); pinMode(12,OUTPUT); digitalWrite(12,LOW); pinMode(13,OUTPUT); digitalWrite(13,LOW); wiflyUart.begin(9600); // start Wi-Fi shield uart port Serial.begin(9600); // start the arduino serial port Serial.println(- WIFLY Webserver.-); // wait for initilization of wifly delay(1000); wifly.reset; // reset the shield delay(1000); //set WiFly params wifly.sendCommand(set IP local 80\r); // set the local comm port to 80 delay(100); wifly.sendCommand(set comm remote 0\r); // do not send a default string when a connection opens delay(100); wifly.sendCommand(set comm open OPEN\r); // set the string that the Wi-Fi shield will output when a connection is opened delay(100); Serial.println(Join SSID ); if (wifly.join(SSID, KEY, AUTH)) Serial.println(OK); else Serial.println(Failed); delay(5000); wifly.sendCommand(get ip\r); wiflyUart.setTimeout(500); if(!wiflyUart.find(IP=)) Serial.println(can not get ip); while(1);; else Serial.print(IP:); char c; int index = 0; while (wifly.receive((uint8_t )c, 1, 300) 0) // print the response from the get IP command if(c ‘:’) ip[index] = 0; break; ip[index] = c; Serial.print((char)c); ? Serial.println; while (wifly.receive((uint8_t )c, 1, 300) 0);; Serial.println(Web server ready); void loop if(wifly.available) // the Wi-Fi shield has data available if(wiflyUart.find(OPEN)) // see if the data available is from an open connection by looking for the OPEN string Serial.println(New Browser Request!); delay(1000); // delay enough time for the browser to complete sending its HTTP request string if(wiflyUart.find(pin=)) // look for the string pin= in the http request, if it’s there then we want to control the LED Serial.println(LED Control); // the user wants to toggle the LEDs int pinNumber = (wiflyUart.read-48); // get first number i.e. if the pin 13 then the 1st number is 1 int secondNumber = (wiflyUart.read-48); if(secondNumber=0 secondNumber9) pinNumber=10; pinNumber =secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin // Build pinstate string. The Arduino replies to the browser with this string. String pinState = Pin ; pinState=pinNumber; pinState= is ; if(digitalRead(pinNumber)) // check if the pin is ON or OFF pinState=ON; // the pin is on else pinState=OFF; // the pin is off // build HTTP header Content-Length string. String contentLength=Content-Length: ; contentLength=pinState.length; // the value of the length is the lenght of the string the Arduino is replying to the browser with. // send HTTP header wiflyUart.println(HTTP/1.1 200 OK); wiflyUart.println(Content-Type: text/html; charset=UTF-8); wiflyUart.println(contentLength); // length of HTML code wiflyUart.println(Connection: close); wiflyUart.println; // send response wiflyUart.print(pinState); else // send HTTP header wiflyUart.println(HTTP/1.1 200 OK); wiflyUart.println(Content-Type: text/html; charset=UTF-8); wiflyUart.println(Content-Length: 540); // length of HTML code wiflyUart.println(Connection: close); wiflyUart.println; // send webpage’s HTML code wiflyUart.print; wiflyUart.print; wiflyUart.print(Wi-Fi Shield Webpage); wiflyUart.print; wiflyUart.print; wiflyUart.print(

LED Toggle Webpage

); // In the tags, the ID attribute is the value sent to the arduino via the pin GET parameter wiflyUart.print( ); // button for pin 11 wiflyUart.print( ); // button for pin 12 wiflyUart.print( ); // button for pin 13 wiflyUart.print; wiflyUart.print; wiflyUart.print((document).ready(function); wiflyUart.print((\.led\).click(function); wiflyUart.print(var p = (this).attr(‘ID’);); // get ID value (i.e. pin13, pin12, or pin11) // send HTTP GET request to the IP address with the parameter pin and value p, then execute the function // IMPORTANT: dont’ forget to replace the IP address and port with YOUR shield’s IP address and port wiflyUart.print(.get(\http://); wiflyUart.print(ip); wiflyUart.print(:80/a\, ,function(data)););// execute get request. Upon return execute the function (display an alert with the data send back to the browser. wiflyUart.print;); wiflyUart.print;); wiflyUart.print; wiflyUart.print; wiflyUart.print; Serial.println(Data sent to browser);

Step 3: Serial Monitor Window

Open the serial monitor window and wait for the Web server ready message to display. The serial monitor will also display the Wi-Fi shield’s IP address:

Arduino program serial comm output. The IP address of the shield is highlighted.

Step 4: Visit The Webpage

Visit the IP address in a web browser. A webpage with three buttons, like the one below, should display. Click on the buttons to control the LEDs.

LED control webpage served from the Wi-Fi shield.

The Arduino will also respond back to the web browser with the pin’s state, the browser will display this in an alert window.

Alert dialog displaying the state of Pin12, The string Pin12 is ON was sent from the Arduino.

The serial monitor window will also show when a browser sends a request to either visit the webpage or control the LED pins.

Arduino serial comm output when an HTTP request is sent to the shield.

Example 6: Wi-Fi Shield and Android App​

The Android app you can use to control the Arduino’s pins through the Wi-Fi or Ethernet Shield.

Android Application

We’ve created an Android app that can toggle the digital pins in the Arduino through the Wi-Fi shield, to see how the app works and learn about the code watch the video in this link:

Download the Android Studio project/source form this link:

Example 7: Sending Data To and Retrieving Data From an External Server​

The RN-171 module in the Wi-Fi shield has the ability to act as an HTML client (a text based web browser essentially), this means that we can use the shield to send and receive data from a web server. In this example you will learn to use the shield with a web Application Programming Interface (API) that displays any city’s weather data (i.e. temperature, humidity, etc).

The name of the API we’ll use is OpenWeatherMap, when you send the name of a city and country to this website it returns a JSON string with weather information. If you want to display the weather for London UK for example, please refer to the toturial in this link http://openweathermap.org/appid.Starting from 9 Oct 2015, the website requires users to sign up for a API key before visiting the API. Once you have got the API key, you will be able to visit the following URL http://api.openweathermap.org/data/2.5/weather?q=London,uk which would return a JSON string like the following, where the weather data and other information is embedded.

coord:, sys:, weather:[], base:cmc stations, main: temp:277.25,humidity:79,pressure:998.4, temp_min:277.25,temp_max:277.25. wind: speed:2,gust:5,deg:180, rain:,clouds:, dt:1421372140,ID:2643743,name:London,cod:200

Step 1: The URL

Let us go ahead and retrieve the weather JSON string for San Francisco, US. The URL our Wi-Fi shield needs to visit is the following (you may test it in your web browser):

http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,US

Step 2: The Arduino Code

Section 13 of the WiFly manual teaches you different ways to connect to a web server, but in all cases we need to specify the name of the server (or IP address if the server does not have a domain name), and then the data we wish to send.

The commands we need to send to the Wi-Fi shield to receive the JSON string from the OpenWeatherMap server are the following:

set IP proto 18 //enable html client set dns name api.openweathermap.org //name of your webserver set IP address 0 // so WiFly will use DNS set IP remote 80 // standard webserver port set com remote 0 // turn off the REMOTE string so it does not interfere with the post open // to open the connection GET /data/2.5/weather?q=San%20Francisco,US \n\n // to send the data

This is the arduino code that will send the commands:

#include #include WiFly.h #define SSID mySSID #define KEY myPassword // check your access point’s security mode, mine was WPA20-PSK // if yours is different you’ll need to change the AUTH constant, see the file WiFly.h for avalable security codes #define AUTH WIFLY_AUTH_WPA2_PSK // Pins’ connection // Arduino WiFly // 2 TX // 3 RX SoftwareSerial wiflyUart(2, 3); // create a Wi-Fi shield serial object WiFly wifly(wiflyUart); // pass the Wi-Fi siheld serial object to the WiFly class void setup wiflyUart.begin(9600); // start Wi-Fi shield uart port Serial.begin(9600); // start the arduino serial port Serial.println(- OpenWeatherMap API.-); // wait for initilization of wifly delay(3000); wifly.reset; // reset the shield Serial.println(Join SSID ); if (wifly.join(SSID, KEY, AUTH)) Serial.println(OK); else Serial.println(Failed); delay(5000); wifly.sendCommand(set IP proto 18\r); //enable html client delay(100); wifly.sendCommand(set dns name api.openweathermap.org\r); // name of the webserver we want to connect to delay(100); wifly.sendCommand(set IP address 0\r); // so WiFly will use DNS delay(100); wifly.sendCommand(set IP remote 80\r); /// standard webserver port delay(100); wifly.sendCommand(set com remote 0\r); // turn off the REMOTE string so it does not interfere with the post delay(100); wifly.sendCommand(open\r); // open connection delay(100); wiflyUart.print(GET /data/2.5/weather?q=San%20Francisco,US \n\n); delay(1000); void loop //As soon as the data received from the Internet ,output the data through the UART Port. while (wifly.available) Serial.write(wifly.read);

Step 3: Result

Open the serial monitor window, you should be able to see the same JSON string you saw in the browser.

JSON weather string shown in the Arduino serial monitor window.

Example 8: TCP Communication With Terminal​

In this example we’ll show you how to send information from the Wi-Fi shield to a PC terminal program. We’ll make a simple Arduino console with menus that will give you the option to see the Arduino digital pin’s state and toggle them.

Step 1: Download a TCP Terminal

Download and install RealTerm, a utility terminal that will allow us to connect to the Wi-Fi shield.

Step 2: Arduino Code

Upload the code below to your Arduino board replacing mySSID, myPassword, and authentication code with your own access point’s information:

#include #include WiFly.h #define SSID mySSID #define KEY myPassword // check your access point’s security mode, mine was WPA20-PSK // if yours is different you’ll need to change the AUTH constant, see the file WiFly.h for avalable security codes #define AUTH WIFLY_AUTH_WPA2_PSK #define FLAG_MAIN_MENU 1 #define FLAG_SUB_MENU_2 2 int flag = FLAG_MAIN_MENU; // Pins’ connection // Arduino WiFly // 2 TX // 3 RX SoftwareSerial wiflyUart(2, 3); // create a Wi-Fi shield serial object WiFly wifly(wiflyUart); // pass the Wi-Fi siheld serial object to the WiFly class void setup // define the pins we can control pinMode(11,OUTPUT); digitalWrite(11,LOW); pinMode(12,OUTPUT); digitalWrite(12,LOW); pinMode(13,OUTPUT); digitalWrite(13,LOW); pinMode(7,OUTPUT); digitalWrite(7,LOW); wiflyUart.begin(9600); // start Wi-Fi shield uart port Serial.begin(9600); // start the arduino serial port Serial.println(- TCP Communication.-); // wait for initilization of wifly delay(1000); wifly.reset; // reset the shield delay(1000); wifly.sendCommand(set IP local 80\r); // set the local comm port to 80 delay(100); wifly.sendCommand(set comm remote 0\r); // do not send a default string when a connection opens delay(100); wifly.sendCommand(set comm open \r); // set the string or character that the Wi-Fi shield will output when a connection is opened delay(100); wifly.sendCommand(set IP protocol 2\r); // set TCP protocol delay(100); Serial.println(Join SSID ); if (wifly.join(SSID, KEY, AUTH)) Serial.println(OK); else Serial.println(Failed); delay(5000); wifly.sendCommand(get ip\r); char c; while (wifly.receive((uint8_t )c, 1, 300) 0) // print the response from the get IP command Serial.print((char)c); Serial.println(TCP Ready); void loop if(wifly.available) delay(1000); // wait for all the characters to be sent to the Wi-Fi shield char val = wiflyUart.read; // read the first character if(flag FLAG_MAIN_MENU) switch(val) case ”: // search for the new connection string printMainMenu; break; case ‘1’: // the user typed 1, display the pin states printPinStates; printMainMenu; break; case ‘2’: // the user typed 2, display the sub menu (option to select a particular pin) printSubMenu2; flag = FLAG_SUB_MENU_2; // flag to enter the sub menu break; default: wiflyUart.print(INVALID SUBMENU); break; else if(flag FLAG_SUB_MENU_2) int pinNumber = val-48; // get first number i.e. if the pin 13 then the 1st number is 1 int secondNumber = (wiflyUart.read-48); if(secondNumber=0 secondNumber9) pinNumber=10; pinNumber =secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number // Create the You want to toggle pin x?? OK. string. String response = You want to toggle pin ; response=pinNumber; response=? OK. ; wiflyUart.print(response); digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin wiflyUart.print(Pin Toggled!); // let user know the pin was toggled. printMainMenu; flag = FLAG_MAIN_MENU; / Prints the main menu options / void printMainMenu wiflyUart.print; wiflyUart.print(Arduino Console Menu: ); wiflyUart.print(1. Show digital pin states); wiflyUart.print(2. Toggle a digital pin’s state); wiflyUart.print; // displays the pin states void printPinStates String pinState = Pin 7 is ; pinState=getPinState(7); pinState=; pinState = Pin 11 is ; pinState=getPinState(11); pinState=; pinState = Pin 12 is ; pinState=getPinState(12); pinState=; pinState = Pin 13 is ; pinState=getPinState(13); pinState=; wiflyUart.print(pinState); // prints the option to enter a pin number void printSubMenu2 wiflyUart.print(Enter the pin number you wish to toggle: ); ? // get a pin state as a string. String getPinState(int pinNumber) if(digitalRead(pinNumber)) // check if the pin is ON or OFF return ON; // the pin is on else return OFF; // the pin is off

Step 3: Obtain the Shield’s IP Address and Port

arduino, wi-fi, server

Open the Arduino serial monitor window to obtain the WiFiShield’s IP address and port number, highlighted in the image below.

Arduino serial monitor window output from TCP example, the IP address and port number are highlighted.

In the image above the IP Address and Port would be the following:

| Denial of responsibility | Contacts |RSS