How To Make an IoT Device
Send and receive data between smartphones and Arduino
Shubh Patni
Imagine being able to communicate with any device from anywhere in the world. You can control your TV, lights, washing machine, dishwasher, toaster, coffee machine, anything you want, just for a few bucks.
You can do it with Arduino.
I have a lot of these lying around in my room, ready to automate another device of mine. In my other article, I covered how you can use Arduino as a switch to turn on or off any device. In this one, we are taking things further.
In this article, I will show you how you can send and receive data from smartphones to Arduino and vice versa. This would allow you to not only use your phone as a switch but also use it to send specific commands for operations and to get the state from Arduino.
I will use a WS2812B LED strip to send data from the phone for different colors and brightness, and I’ll get the state from ESP8266 for the same. You can use it for another project if you like.
Web Sockets
There are many ways you can set up a connection between a smartphone and an Arduino. You can use Bluetooth, online services, HTTP protocol, or web sockets.
I have compared these methods in one of my previous articles.
The conclusion was web sockets are a better way of transferring data, in the sense that the connection remains open until any one device disconnects. Unlike HTTP, web sockets need not make a new connection every time they want to send some data.
A good analogy would be a phone call. Until a party disconnects, both the parties can talk and communicate.
Web sockets are used where you need real-time data. For example, you do not want your screen to get refreshed every time you shoot in a game; that will cause latency and degrade the experience. In trading, you may want to know price changes as quickly as they happen, to find the right opportunity and make a profit. So for this project, web sockets is the way to go.
In cases where you don’t care about latency, need old data, or want data only once, HTTP is a better option.
How To Use Web Sockets in Arduino
Before we go ahead with the code, there are a few things you will need:
- ESP8266-NodeMCU
- Any device you want to control. I am using LED strips.
- Smartphone
There are a few ways you can design an interface for the Android device. You can create either an Android app or a webpage hosted on the ESP8266. Whichever one you choose, apart from syntax differences, everything will be the same.
We will create an Android app using MIT App Inventor. It is a visual programming environment where you can create apps using drag-and-drop code. You can also use other platforms such as QT, Android studio, and others as per your convenience.

There are three extensions you will need to download in MIT App Inventor to make web sockets work.
- WebSocketCl1 (To make a web socket connection)
- TaifunWiFi1 (To connect to Wi-Fi and get information about it)
- KIO4_GetAllIp1 (To get the IP addresses of all the devices connected to the same network — download the first attachment by Juan Antonio)
After you download them, do the following:

I have created a simple UI using the drag-and-drop components, and you can improve the UI as per your needs. This is a straightforward part, so I’ll let you figure it out yourself.
MIT App Inventor Code
Click on the blocks button to program the app.


Below is a detailed explanation of the above code.
When the app is opened, we collect the subnet of the network and store it in a variable. We need the subnet of the network because it is one parameter for the KIO4_GetAllIp1.checkHosts
function which returns the IP addresses of all the connected devices.
With the IP addresses, we also collect some irrelevant data (“”
and []
) so we get rid of it using the replace all mappings
function. Finally, we separate all the collected IP addresses and append them to a global array which can then be accessed by any function.

When the connect button is clicked, we call the above function. The connect button has two states: connect and disconnect. If the connection is not established, we try to connect to all the IP addresses using the WebSocketCl1.CreateConnection
function because we do not know the IP address of the phone and we assume that only the phone is requesting a web socket connection.
There are other two functions, WebSocketCl1.OnConnect
and WebSocketCl1.OnError
. The former is called when a connection is made, and it renames the label to let the user know that connection has been made. The other function is called in case of an error.

The Slider2.PositionChanged
function is used to set the brightness of the LED. The data is then sent to Arduino using the WebSocketCl1.Send
function. It takes a string, so we concatenate the hexadecimal value with -b
to indicate we are changing the brightness.
Note: The entire project is out-of-the-scope for this article, so I have left out the parts about RGB conversion and how we set the color. This is just to show you how data is sent. Below is the entire project.
To upload the code into an Android device, first download the MIT App Inventor app. Now go back to the code and click on the Build button, and then click on “provide QR code for APK file.” Now open the Android app and scan the QR code to get the download link for the APK file.
Arduino Code
Arduino Code
#include <FastLED.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <FS.h>
#define LED_PIN 4
#define ANALOG_READ 0
#define NUM_LEDS 100
CRGB leds[NUM_LEDS];
WebSocketsServer webSocket = WebSocketsServer(81);
const char *ssid = "abcd";
const char *password = "12345678";
uint8_t hue = 0;
uint8_t brightness = 100;
void setup() {
// put your setup code here, to run once:
FastLED.addLeds<WS2812B, LED_PIN, RGB>(leds, NUM_LEDS);
FastLED.setBrightness(brightness);
FastLED.clear();
Serial.begin(115200);
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.println("Connected!");
Serial.print("AP IP address: ");
Serial.println(myIP);
webSocket.begin();
webSocket.onEvent(onWebSocketEvent);
}
void loop() {
webSocket.loop();
// put your main code here, to run repeatedly:
}
void onWebSocketEvent(uint8_t connection, WStype_t type, uint8_t * payload, size_t length) {
switch (type){
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", connection);
break;
case WStype_CONNECTED: {
IPAddress ip = webSocket.remoteIP(connection);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", connection, ip[0], ip[1], ip[2], ip[3], payload);
webSocket.sendTXT(connection, "Connected");
}
break;
case WStype_TEXT:
Serial.printf("[%u] get Text: %s\n", connection, payload);
if (payload[0] == '-'){
switch (payload[1]) {
case 'h': // Request to set hue
hue = strtoul((const char *) &payload[2], NULL, 16);
Serial.printf("hueee: is :: %u",hue);
//hue = map(hue,0,360,0,255);
fill_solid(leds,NUM_LEDS,CHSV(hue,255,255));
FastLED.show();
Serial.printf("recieved msg hue");
break;
case 'b': // Request to set brightness
brightness = strtoul((const char *) &payload[2], NULL, 16);
Serial.printf("brightness: is :: %u",brightness);
FastLED.setBrightness(brightness);
FastLED.show();
Serial.printf("recieved msg brightness");
break;
}
}
break;
}
}
This code is for my LED lights project, but it is perfect to explain how to use web sockets in Arduino.
Before we start, you must install the WebSocket Server library. First download the zip file using the link below and follow these instructions to install it.
Include the WiFiClient.h
and WebSocketsServer.h
files. They will allow us to use Arduino as an access point. In simple terms, Arduino will act as Wi-Fi which our phone can connect to. Line 14 instantiates an object of WebSocketsServer
class for port 81
. On lines 15 and 16, we set the SSID and password for the Arduino access point.
In the setup()
function, on lines 29 and 30, we turn on our access point, and on lines 35 and 36, look for any web socket connections. The main loop()
of the program on line 39, which checks for any web socket requests, errors, or data.
The onWebSocketEvent()
function is called in case of any request. It has four parameters: connection, type, payload, and length. The connection
is the device it is connected to; type
tells us what kind of message we have received such as connect request, disconnect request, data; and payload
contains the actual message sent from the phone.
On line 46, we check what type of request we have received, and different operations take place based on that. I assume you are aware of how the switch case statement works. Now we just need to unpack the payload and call functions based on the received commands.
The rest of the code will change based on what you are trying to do. You just need to check for the type of request and make different functions to handle each case. The payload is a string, so you must send string data in such a way that it is easy to handle in Arduino, as I have done above.
Once you are done, you can upload the code to ESP-8266, and voila, the project is finished.
Upvote
Shubh Patni
Hi! I am Shubh, a Programmer, Blogger, and a YouTuber. I believe in decentralisation, love tech, and invest in crypto. I create content related to these topics and programming and bogging.

Related Articles