How to connect your phone to your ESP8266 module


Andreas Lund quistBlogsTutorials

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+

It’s been roughtly a year since Hackaday published the article “New chip alert: The ESP8266 WiFi module (It´s $5)”. At the time of the publishing of that article not much was known about the cheap WiFi module – however the the module was received with open arms by the maker/hacker community and a lot of interesting community projects have been created using it.

esp8266

Today there is an Arduino-compatible SDK available and many more libraries have been written for it. If you have not heard of this module before; it is a 802.11b/g/n WiFi module. Equipped with SPI and UART interfaces; and depending on the module, a number of GPIOs. You can find the module for as low as $2 on eBay. The price point makes it perfect for makers that want to explore the Internet Of Things. We love great (and cheap) hardware and figured it was time for us to create an example where we made use of the ESP8266-module.

There exists a couple of different modules based on the ESP8266, they are named ESP-XX, where XX is a number ranging from 01 to 13 (as of publication of this tutorial). This example was developed using the ESP-01 module however it should run on any other module, but the external circuit required might differ depending on which module you use.

You can read more about that on this ESP8266 Wiki.

Source Code

You can browse the source code for this tutorial in the Evothings GitHub repository.

What you need

You will need the following hardware:

  • 1 x ESP-01 (or any other compatible module)
  • 1 x Breadboard
  • 1 x USB – Serial cable (3.3 volt)
  • 1 x Power supply (3.3 volt)
  • 2 x 10 kOhm resistors
  • 1 x LED
  • 1 x 1 kOhm resistor
  • Breadboard jumper cables
  • An iOS or Android smartphone

Step 1 – Hardware

The first step is to connect the module to your computer so that you can upload the firmware to your module. Since this module is a bit simpler than the ordinary development board you need to perform some additional work in order to connect it to your computer. Also the module runs on 3.3 volt and will fry (not good) if you try to use it with 5 volt signals. So first step is to ensure that your USB – Serial cable communicates using 3.3 volt signals. Among supported chipset you will find the FT232RL and CP2102.

The GitHub repository containing the Arduino SDK provides a guide on how to connect your module to your computer.

Connect the LED and the 1 kOhm current limiting resistor in series to the pin named GPIO2.

Step 2 – Embedded software

Preparation

Compared to a lot of other hardware vendors the community around ES8266 has really managed to simplify the installation of the SDK. Using the newly introduced board manager functionality in the Arduino IDE it is extremely simple to install the SDK. Download the environment from the Arduino website, open the Preferences window and enter the following URL

http://arduino.esp8266.com/package_esp8266com_index.jsoninto the Additional Board Manager URL field. Then open the Tools -> Board -> Boards Manager menu in the IDE and install the esp8266 platform SDK. It’s as simple as that.

The official installation guide can be found on the Github repository.

Source code

The Arduino sketch described below can be found on the Github repository.

This application connects to a WiFi network and configures a TCP-server listening to the port 1337. The server responds to the command H (High) and L (Low) which turns on respectively turns off the LED connected to GPIO 2.

The first thing you need to do is to add your WiFi credentials to the sketch. Find the ssid and password variables in the sketch and replace them with the relevant strings required for your network.

In the setup() function we configure the serial and WiFi connection. GPIO 2 is configured as OUTPUT so that it can control the connected LED. Finally the application starts to listen for connections on port 1337. The entire setup() function is provided below.

void setup(void) {
  
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  // Configure GPIO2 as OUTPUT.  
  pinMode(ledPin, OUTPUT);  
  
  // Start TCP server.
  server.begin();
}

In the loop() method we first ensure that we are connected to the WiFi provided, and if we for some reason lose our connection we try to reconnect. During the development of this example we lost the connection from time to time – but that may be because of our over wireless working environment. You will probably experience that as well, the root cause can be difficult to detect when working with radio enabled systems – so adding the following code snippet will guarantee that the module is connected to the WiFi if it is within reach.

 if (WiFi.status() != WL_CONNECTED) {
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
    }
    // Print the new IP to Serial. 
    printWiFiStatus();
  }

The last part of the software checks if there is any new clients connected and if they have sent any data. If there is data available it is read and interpreted. If a H is received the LED is turned on and if a L is received it is turned off. Any other characters is simply ignored. The implementation follows here.

WiFiClient client = server.available();
  
  if (client) {
    
    Serial.println("Client connected.");
    
    while (client.connected()) {  
      
      if (client.available()) {
        
        char command = client.read(); 
        
        if (command == 'H') {
          
          digitalWrite(ledPin, HIGH);
          Serial.println("Led is now on.");
        }
        else if (command == 'L') {
          
          digitalWrite(ledPin, LOW);
          Serial.println("Led is now off.");
        }        
      }
    }
    
    Serial.println("Client disconnected.");
    client.stop();
  }

Unfortunately we had some issues with the code above, from time to time it seems like the client.connected() execution failed to detect when a client disconnected. In an more advanced implementation a watchdog timer could have been implemented along with the method call. If you do experience any issues, try restarting the module or consider implementing watchdog functionality into the sketch.

Step 3 – Mobile application

Preparation

If you already have a fully working copy of Evothings Studio you can skip this step.

First you have to install the Evothings Studio on your computer. The Evothings Studio consists of two softwares that interacts with each other. You have to install Evothings Workbench on you computer. The software provides you with the interface in which you will perform your development. You also have to install the Evothings Client (iOSAndroid) on your smartphone. The client will connect to the workbench and execute the mobile application.

Source code

The source code can be found on the Evothings Github repository.

The application is designed to interface with the previously implemented TCP-server on the ESP8266 and sends commands to turn on and off the LED connected to GPIO 2. The application consists of three files, index.html which contains all the code connected to the user interface, app.css which contains the style sheets of the application and last, app.js which contains all the logic of the application.

esp8266-controlView

The user interface consists of three views, startViewconnectingView and controlView. The startView, see above, contains the initial view that is displayed to the user when the application is launched. It makes it possible to connect to the ESP8266 module using its IP address. The connectingView is displayed when the user tries to connect to the board. And finally the controlView, see below, which is displayed once the application is connected to the module and ready to send commands.

esp8266-startView

The logic behind the application should be fairly straight forward and described in the following paragraphs. The method app.connect() is executed when the user presses the connectButton. The implementation the tries to open a TCP socket to the ESP8266 module, if it succeeds it displays the controlView. The implementation can be viewed below.

app.connect = function() {

	var IPAddress = $('#IPAddress').val()
	console.log('Trying to connect to ' + IPAddress)

	$('#startView').hide()
	$('#connectingStatus').text('Connecting to ' + IPAddress)
	$('#connectingView').show()

	chrome.sockets.tcp.create(function(createInfo) {

		app.socketId = createInfo.socketId

		chrome.sockets.tcp.connect(
			app.socketId,
			IPAddress,
			app.PORT,
			connectedCallback)
	})

	function connectedCallback(result) {
	
		if (result === 0) {

			 console.log('Connected to ' + IPAddress)
			 $('#connectingView').hide()
			 $('#controlView').show()
		}
		else {

			var errorMessage = 'Failed to connect to ' + app.IPAdress
			console.log(errorMessage)
			navigator.notification.alert(errorMessage, function() {})
			$('#connectingView').hide()
			$('#startView').show()
		}
	}
}

When a connection is established the application awaits user interaction, the user can either touch the circle that represents the LED or press the disconnect button. If the circle is pressed, either app.ledOn() or app.ledOff() is invoked – depending on the state the LED is in. The implementation of these two methods can be found below.

app.ledOn = function() {

	app.sendString('H')
	$('#led').removeClass('ledOff').addClass('ledOn')
	$('#led').unbind('click').click(function(){
		app.ledOff()
	})	
}

app.ledOff = function() {

	app.sendString('L')
	$('#led').removeClass('ledOn').addClass('ledOff')
	$('#led').unbind('click').click(function(){
		app.ledOn()
	})
}

If the disconnectButton is pressed, the app.disconnect() method is invoked, this method simply closes the socket and switches to the startView again.

app.disconnect = function() {

	chrome.sockets.tcp.close(app.socketId, function() {
		console.log('TCP Socket close finished.')
	})
	$('#controlView').hide()
	$('#startView').show()
}

To keep this tutorial simple we have omitted the fact that a command sent might not be received by the ESP8266 module. A simple way to ensure this is to implement a acknowledge functionality, every time the ESP8266 either turns on or off the led it should acknowledge success or failure by sending a message to the application. In the example we did previously for the MediaTek Connect 7681 we implemented a simple version of such a functionality, if you are curious you can have a look in that source code which can be found on our Github repository.

Summary

This tutorial shows you how simple it is to develop a mobile application for your ESP8266 module using nothing but HTML5 and JavaScript. This is our small contribution to the ever growing open source community revolving around the cheap and powerful ESP8266 modules. Feel free to use the source code as a starting point for your project. Order a couple of ESP8266 modules, download Evothings Studio and start working on your own project today! We can not wait to see what you will build, please share any creations with us @evothings.

estimote-beacons-group-small

Eddystone is coming, opening up the beacon space

Estimote, Kontakt and Radius Networks are upping their hardware offerings, here’s some things you need to know.
Read more→

cloud_two

Evothings Studio is coming cloud-side

Going from a downloadable product into a Saas solution, brings on a wide array of new possibilities. Join the growing community and learn more about the benefits of moving from desktop onto the cloud for mobile development.
Read more and download→

appstore_whirl

Ready for app stores with Phonegap Build

A simple way to build and sign your app for publishing, is via a build service. Adobe’s Phongegap Build is one for the candidates.
Read more→

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Google

Você está comentando utilizando sua conta Google. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s