Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

IoT Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

1.

Embedded System design using MCU – ESP32: Arduino Platform - Installation,


Port Configuration, Additional Board Installation (ESP32), Adding New Library,
Blinking LED

A.Installation & Configuration

To install the ESP32 board in your Arduino IDE, follow these next instructions:

1. In your Arduino IDE, go to File> Preferences

2. Enter the following into the “Additional Board Manager URLs” field:

https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

Then, click the “OK” button:


Note: if you already have the ESP8266 boards URL, you can separate the URLs
with a comma as follows:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-
pages/package_esp32_index.json,
http://arduino.esp8266.com/stable/package_esp8266com_index.json
3. Open the Boards Manager. Go to Tools > Board > Boards Manager…

4. Search for ESP32 and press install button for the “ESP32 by Espressif Systems“:

5. That’s it. It should be installed after a few seconds.


B.Blink LED code:
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(5000); // Wait for 1000 millisecond(s)
digitalWrite(LED_BUILTIN, LOW);
delay(5000); // Wait for 1000 millisecond(s)
}

C. Install the following libraries in Arduino Software


Go To -> Sketch -> Select Include Library -> Select Manage Libraries

1. Install DHT sensor Library

2. Install ThingSpeak Library


3. Adafruit IO Arduino library

4. Install the Adafruit Unified Sensor library


5. Install Adafruit MQTT Library

2. Embedded System design using MCU – ESP32- Usage of Digital Input/ Output
Devices - Arduino Platform
A.Digital Output – (Two LEDS )

const int ledpin1 = 26;


const int ledpin2 = 27;
void setup() {
// put your setup code here, to run once:
pinMode(ledpin1, OUTPUT);
pinMode(ledpin2, OUTPUT);
digitalWrite(ledpin1, LOW);
digitalWrite(ledpin2, LOW);
}

void loop() {
// put your main code here,to run repeatedly:
digitalWrite(ledpin1, HIGH);
digitalWrite(ledpin2, LOW);
delay(2000);
digitalWrite(ledpin1, LOW);
digitalWrite(ledpin2, HIGH);
delay(2000);
}
B.Push Button – Control LED
int led=13;
int pushbutton=2;
int inputval=0;

void setup()
{
pinMode(led,OUTPUT);
pinMode(pushbutton,INPUT);
}

void loop()
{
inputval=digitalRead(pushbutton);
if(inputval==1){
digitalWrite(led,HIGH);
}

if(inputval==0){
digitalWrite(led,LOW);
}

3. Embedded System design using MCU – ESP32- Usage of ADC and Analogue
Sensors - Arduino Platform
A.Analog Input & Serial Output
void setup()
{
pinMode(A0, INPUT);
Serial.begin(9600);
}
void loop()
{
int sensorValue = analogRead(A0);
Serial.print(“The sensor value is: “);
Serial.println(sensorValue);
delay(500);
}

B.POT-Controlling LED
void setup()
{
pinMode(10, OUTPUT);
pinMode(A0, INPUT);
Serial.begin(9600);
}

void loop()
{

int sensorValue = analogRead(A0);


Serial.println(sensorValue);

if (sensorValue>=512) {
digitalWrite(10, HIGH);
} else {
digitalWrite(10, LOW);
}
delay(500);
}
C.POT-FADING LED
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(10, OUTPUT);
pinMode(A0, INPUT);
Serial.begin(9600);
}
void loop()
{
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
int brightness = map(sensorValue, 0, 1023, 0, 255);
analogWrite(10, brightness);
delay(50);

4. Embedded System Design using MCU – ESP32- Usage of UART(Serial


Input/Output) – Arduino Platform

A.Serial Communication
void setup()
{

Serial.begin(9600);

void loop()
{

if (Serial.available()) {
char c=Serial.read();
if(c=='A')
{
digitalWrite(10, HIGH);
Serial.println("led on");
}
else if(c=='B')
{
digitalWrite(10, LOW);
Serial.println("led off");
}
}
}

Embedded System design using MCU – ESP32: Arduino Platform -5.Design of IoT
End node using MCU – ESP32 and Arduino Platform - Wireless Part - BLE -
Controlling IoT End node using Mobile Bluetooth
#include "BluetoothSerial.h"
/*
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
*/
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
pinMode(27,OUTPUT);
}
void loop() {
/*if (Serial.available()) {
SerialBT.write(Serial.read());
}*/
if (SerialBT.available()) {
char x=SerialBT.read();

//Serial.write(SerialBT.read());
if(x=='A'){
Serial.write(x);
digitalWrite(27,HIGH);
}
if(x=='B'){
Serial.write(x);
digitalWrite(27,LOW);
}

}
}

Bluetooth Mobile App Installation :


Search in the Google Play Store - Arduino & ESP32 Bluetooth cont – Dabble
Click the Connect icon to see the Bluetooth devices and connect
Click terminal to give input to control LED

6. Design of IoT End node using MCU – ESP32 and Arduino Platform - Wireless
Part - Wi-FiScan Wifi Network - Connect Internet through Wireless Hotspot
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "Thiru";
const char* password = "thiru123";
void initWiFi();

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
initWiFi();
}

void loop() {
// put your main code here, to run repeatedly:

void initWiFi() {
Serial.println("");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.println(WiFi.localIP());
}
7.Embedded System design using MCU – ESP32: Arduino Platform
DHT11 Sensor Interface
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
float temp_value;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
dht.begin();
}

void loop() {
// put your main code here, to run repeatedly:
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);

Serial.print("Humidity: ");
Serial.println(h);
Serial.print("Temperature: (°C) ");
Serial.println(t);
Serial.print("Temperature: (F) ");
Serial.println(f);
delay(5000);
}
Implementation of MQTT protocol using ESP32 as MQTT Client (Publish).

#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"

#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

/*********** WiFi Access Point *****************/


#define WLAN_SSID "Thiru"
#define WLAN_PASS "thiru123"

/************* Adafruit.io Setup ****************/


#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "Dr_Thiru"
#define AIO_KEY "aio_dQCc05qOAeIu2XO31VIu3wHbmpNv"

/************ Global State***************/

/* Create an WiFiClient class to connect to the MQTT server.*/


WiFiClient client;

/* Setup the MQTT client class by passing in the WiFi client and MQTT server and login
details.*/
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME,
AIO_KEY);

Adafruit_MQTT_Publish dht_temp = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME


"/feeds/DHT_Temp");
Adafruit_MQTT_Publish dht_humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME
"/feeds/DHT_Humidity");

void MQTT_connect();

void setup() {
Serial.begin(9600);
delay(10);
Serial.println(F("DHTxx test!"));
dht.begin();
Serial.println(F("Adafruit MQTT demo"));

// Connect to WiFi access point.


Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());

void loop() {

/* Ensure the connection to the MQTT server is alive (this will make the first
connection and automatically reconnect when disconnected). See the MQTT_connect
function definition further below.*/
MQTT_connect();

float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);

Serial.print("Humidity(%): ");
Serial.print(h);
Serial.print(" Temperature (°C): ");
Serial.print(t);
Serial.print(" Temperature(F): ");
Serial.println(f);
//Mqtt Publish data

if (! dht_temp.publish(t)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
delay(10000);
if (! dht_humidity.publish(h)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
delay(1000);
}

/* Function to connect and reconnect as necessary to the MQTT server.


Should be called in the loop function and it will take care if connecting.*/
void MQTT_connect() {
int8_t ret;

// Stop if already connected.


if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

uint8_t retries = 1;
while ((ret = mqtt.connect()) != 0) {
// connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(3000);
retries--;
if (retries == 0) {
// basically die and wait for reset
while (1);
}
}
Serial.println("MQTT Connected!");
}

9.Implementation of MQTT protocol using ESP32 as MQTT Client () – Subscribe –


Control LED

#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"

#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void MQTT_connect();

int led1=27;

/********* WiFi Access Point ***********/

#define WLAN_SSID "Thiru"


#define WLAN_PASS "thiru123"

/***** Adafruit.io Setup *************/

#define AIO_SERVER "io.adafruit.com"


#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "Dr_Thiru"
#define AIO_KEY "aio_dQCc05qOAeIu2XO31VIu3wHbmpNv"
/* Create an WiFiClient class to connect to the MQTT server.*/
WiFiClient client;

/* Setup the MQTT client class by passing in the WiFi client and MQTT server and login
details.*/
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME,
AIO_KEY);

/******** Feeds **************/

Adafruit_MQTT_Publish dht_temp = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME


"/feeds/DHT_Temp");
Adafruit_MQTT_Publish dht_humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME
"/feeds/DHT_Humidity");

// Setup a feed called 'onoff' for subscribing to changes.


Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME
"/feeds/onoff");

void setup() {
Serial.begin(9600);
delay(10);

Serial.println(F("DHTxx test!"));
dht.begin();
Serial.println(F("Adafruit MQTT demo"));

// Connect to WiFi access point.


Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// digitalWrite(led1, HIGH);

// Setup MQTT subscription for onoff feed.


pinMode(led1,OUTPUT);
mqtt.subscribe(&onoffbutton);
// digitalWrite(led1, HIGH);

void loop() {

/* Ensure the connection to the MQTT server is alive (this will make the first
connection and automatically reconnect when disconnected). See the MQTT_connect
function definition further below. */
MQTT_connect();

Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &onoffbutton) {
Serial.print(F("Got: "));
Serial.println((char *)onoffbutton.lastread);
if (strcmp((char *)onoffbutton.lastread, "ON") == 0) {
digitalWrite(led1, HIGH);
Serial.println("led is on");
}
if (strcmp((char *)onoffbutton.lastread, "OFF") == 0) {
digitalWrite(led1, LOW);
Serial.println("led is off");
}
}
}
// Now we can publish stuff!

float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
// int r=analogRead(A6);

Serial.print("Humidity(%): ");
Serial.print(h);
Serial.print(" Temperature (°C): ");
Serial.print(t);
Serial.print(" Temperature(F): ");
Serial.println(f);

if (! dht_temp.publish(t)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
delay(10000);
if (! dht_humidity.publish(h)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
/*delay(1000);
if (! pot.publish(r)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
} */

// ping the server to keep the mqtt connection alive


// NOT required if you are publishing once every KEEPALIVE seconds
/*
if(! mqtt.ping()) {
mqtt.disconnect();
}
*/
}

/* Function to connect and reconnect as necessary to the MQTT server.


Should be called in the loop function and it will take care if connecting. */
void MQTT_connect() {
int8_t ret;

// Stop if already connected.


if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

uint8_t retries = 1;
while ((ret = mqtt.connect()) != 0) {
// connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 3 seconds...");
mqtt.disconnect();
delay(3000);
retries--;
if (retries == 0) {
// basically die and wait for reset
while (1);
}
}
Serial.println("MQTT Connected!");
}

10. Controlling of Actuator in ESP 32 based IoT End node using IFTTT.
11.Design of WebServer using ESP32 as Hardware and Arduino as Software Platform. –
Sending Data to Webserver

// Load Wi-Fi library


#include <WiFi.h>
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

float temperature;
float humidity;
// Replace with your network credentials
const char* ssid = "Thiru";
const char* password = "thiru123";

// Set web server port number to 80


WiFiServer server(80);

// Variable to store the HTTP request


String header;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout (example: 2000ms = 2s)
const long timeoutTime = 2000;

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

// Connect to Wi-Fi network with SSID and password


Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();

// Listen for incoming clients


WiFiClient client = server.available();
// If a new client connects,
if (client) {
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client.");
// print a message out in the serial port
String currentLine = "";
// make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) {
// loop while the client's connected
currentTime = millis();
if (client.available()) {
// if there's bytes to read from the client,
char c = client.read();
// read a byte, then
Serial.write(c);
// print it out the serial monitor
header += c;
if (c == '\n') {
// if the byte is a newline character
/* if the current line is blank, you got two newline characters in a row.
that's the end of the client HTTP request, so send a response: */
if (currentLine.length() == 0) {
/* HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
and a content-type so the client knows what's coming, then a blank line: */
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("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-
scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px
auto; text-align: center;}");

client.println("</style></head>");

// Web Page Heading

client.println("<body><h1>ESP32 Web Server</h1>");


client.println("<p><h2>Temperature Value " + String(temperature) + "</h2></p>");
client.println("<p><h2>Humidity Value " + String(humidity) + "</h2></p>");

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

// The HTTP response ends with another blank line


client.println();
// Break out of the while loop
break;
} else {
// if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') {
// if you got anything else but a carriage return character,
currentLine += c;
// add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}

12.Design of WebServer using ESP32 as Hardware and Arduino as Software Platform. –


Controlling Devices from Webserver

// Load Wi-Fi library


#include <WiFi.h>
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

float temperature;
float humidity;
// Replace with your network credentials
const char* ssid = "Thiru";
const char* password = "thiru123";

// Set web server port number to 80


WiFiServer server(80);

// Variable to store the HTTP request


String header;

// variables to store the current output state


String output26State = "off";
String output27State = "off";

// Assign output variables to GPIO pins


const int output26 = 26;
const int output27 = 27;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout (example: 2000ms = 2s)
const long timeoutTime = 2000;

float temp=10;
void setup() {
Serial.begin(115200);
dht.begin();
// Initialize the output variables as outputs
pinMode(output26, OUTPUT);
pinMode(output27, OUTPUT);
// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output27, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}

void loop(){
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();

// Listen for incoming clients


WiFiClient client = server.available();
// If a new client connects,
if (client) {
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client.");
// print a message out in the serial port
String currentLine = "";
// make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) {
// loop while the client's connected
currentTime = millis();
if (client.available()) {
// if there's bytes to read from the client,
char c = client.read();
// read a byte, then
Serial.write(c);
// print it out the serial monitor
header += c;
if (c == '\n') {
// if the byte is a newline character
/* if the current line is blank, you got two newline characters in a row.
that's the end of the client HTTP request, so send a response: */
if (currentLine.length() == 0) {
/* HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
and a content-type so the client knows what's coming, then a blank line: */
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();

// turns the GPIOs on and off


if (header.indexOf("GET /26/on") >= 0) {
Serial.println("GPIO 26 on");
output26State = "on";
digitalWrite(output26, HIGH);
} else if (header.indexOf("GET /26/off") >= 0) {
Serial.println("GPIO 26 off");
output26State = "off";
digitalWrite(output26, LOW);
} else if (header.indexOf("GET /27/on") >= 0) {
Serial.println("GPIO 27 on");
output27State = "on";
digitalWrite(output27, HIGH);
} else if (header.indexOf("GET /27/off") >= 0) {
Serial.println("GPIO 27 off");
output27State = "off";
digitalWrite(output27, LOW);
}

// Display the HTML web page


client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-
scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your
preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px
auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px
40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");

// Web Page Heading


client.println("<body><h1>ESP32 Web Server</h1>");

client.println("<p><h2>Temperature Value " + String(temperature) + "</h2></p>");


client.println("<p><h2>Humidity Value " + String(humidity) + "</h2></p>");

// Display current state, and ON/OFF buttons for GPIO 26


client.println("<p>GPIO 26 (Yellow) - State " + output26State + "</p>");
// If the output26State is off, it displays the ON button
if (output26State=="off") {
client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
}

// Display current state, and ON/OFF buttons for GPIO 27


client.println("<p>GPIO 27 (Green) - State " + output27State + "</p>");
// If the output27State is off, it displays the ON button
if (output27State=="off") {
client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/27/off\"><button class=\"button
button2\">OFF</button></a></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else {
// if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') {
// if you got anything else but a carriage return character,
currentLine += c;
// add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}

13.Design of WebSocket Communication using ESP32 as Hardware and Arduino as Software


Platform. – Controlling Devices from Webserver
Installing Libraries – Async Web Server

To build the web server we’ll use the ESPAsyncWebServer library. This library needs the AsyncTCP library to
work properly. Click the links below to download the libraries.

• ESPAsyncWebServer
• AsyncTCP

These libraries aren’t available to install through the Arduino Library Manager, so you need to copy the library
files to the Arduino Installation Libraries folder. Alternatively, in your Arduino IDE, you can go
to Sketch > Include Library > Add .zip Library and select the libraries you’ve just downloaded.

Websocket Server
// Import required libraries
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

// Replace with your network credentials

#define WLAN_SSID "Thiru1"


#define WLAN_PASS "cse73cse82"
bool ledState = 0;
const int ledPin = 26;

// Create AsyncWebServer object on port 80


AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

const char index_html[] PROGMEM = R"rawliteral(


<!DOCTYPE HTML><html>
<head>
<title>ESP Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<style>
html {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
h1 {
font-size: 1.8rem;
color: white;
}
h2{
font-size: 1.5rem;
font-weight: bold;
color: #143642;
}
.topnav {
overflow: hidden;
background-color: #143642;
}
body {
margin: 0;
}
.content {
padding: 30px;
max-width: 600px;
margin: 0 auto;
}
.card {
background-color: #F8F7F9;;
box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
padding-top:10px;
padding-bottom:20px;
}
.button {
padding: 15px 50px;
font-size: 24px;
text-align: center;
outline: none;
color: #fff;
background-color: #0f8b8d;
border: none;
border-radius: 5px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
/*.button:hover {background-color: #0f8b8d}*/
.button:active {
background-color: #0f8b8d;
box-shadow: 2 2px #CDCDCD;
transform: translateY(2px);
}
.state {
font-size: 1.5rem;
color:#8c8c8c;
font-weight: bold;
}
</style>
<title>ESP Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
</head>
<body>
<div class="topnav">
<h1>ESP WebSocket Server</h1>
</div>
<div class="content">
<div class="card">
<h2>Output - LED - GPIO 26</h2>
<p class="state">state: <span id="state">%STATE%</span></p>
<p><button id="button" class="button">Toggle</button></p>
</div>
</div>
<script>
var gateway = `ws://${window.location.hostname}/ws`;
var websocket;
window.addEventListener('load', onLoad);
function initWebSocket() {
console.log('Trying to open a WebSocket connection...');
websocket = new WebSocket(gateway);
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage; // <-- add this line
}
function onOpen(event) {
console.log('Connection opened');
}
function onClose(event) {
console.log('Connection closed');
setTimeout(initWebSocket, 2000);
}
function onMessage(event) {
var state;
if (event.data == "1"){
state = "ON";
}
else{
state = "OFF";
}
document.getElementById('state').innerHTML = state;
}
function onLoad(event) {
initWebSocket();
initButton();
}
function initButton() {
document.getElementById('button').addEventListener('click', toggle);
}
function toggle(){
websocket.send('toggle');
}
</script>
</body>
</html>
)rawliteral";

void notifyClients() {
ws.textAll(String(ledState));
}

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {


AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
if (strcmp((char*)data, "toggle") == 0) {
ledState = !ledState;
notifyClients();
}
}
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,


void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client-
>remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}

void initWebSocket() {
ws.onEvent(onEvent);
server.addHandler(&ws);
}

String processor(const String& var){


Serial.println(var);
if(var == "STATE"){
if (ledState){
return "ON";
}
else{
return "OFF";
}
}
return String();
}

void setup(){
// Serial port for debugging purposes
Serial.begin(115200);

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);

// Connect to Wi-Fi
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}

// Print ESP Local IP Address


Serial.println(WiFi.localIP());
initWebSocket();

// Route for root / web page


server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});

// Start server
server.begin();
}

void loop() {
ws.cleanupClients();
digitalWrite(ledPin, ledState);
}

WebSocket Client

From the serial monitor find the IP Address of the Server

Open the web browser – http://serveripaddress

http://192.168.0.103
14.IoT Cloud Platform - Working with ThingSpeak Cloud - Account Creation and
Dashboard Design
15. Integration of IoT End Node ( ESP32 based ) with ThingSpeak Cloud and ESP 32 Based
Arduino Program for Cloud Integration

#include <WiFi.h>
#include "DHT.h"
#include "ThingSpeak.h"

const char* ssid = "Thiru"; // your network SSID (name)


const char* password = "thiru123";

WiFiClient client;
unsigned long myChannelNumber = 1913557;
const char * myWriteAPIKey = "DFNMJEOPYO1HWM51";

float temp=0;
float hum=0;
int pot=0;
#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void send_thinkspeak(){
Wifi_Connect();
ThingSpeak.setField(1,String(temp));
ThingSpeak.setField(2,String(hum));
ThingSpeak.setField(3,String(pot));
int x= ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);

// int x = ThingSpeak.writeField(myChannelNumber, 10.1, 20.1,30.1, myWriteAPIKey);


//int y = ThingSpeak.writeField(myChannelNumber, 2, 20.1, myWriteAPIKey);
Serial.println("the value of x");
Serial.println(x);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}

void read_sensors(){
hum = dht.readHumidity();
Serial.println("Humidity :");
Serial.println(hum);
// Read temperature as Celsius (the default)
temp = dht.readTemperature();
Serial.println("Temperature in celsius :");
Serial.println(temp);
pot = analogRead(A0);
Serial.println("Pot value :");
Serial.println(pot);

}
void Wifi_Connect() {
Serial.print("Attempting to connect");
// put your main code here, to run repeatedly:
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //Initialize serial
pinMode(A0,INPUT);
dht.begin();
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); //
analogReadResolution(9);
Wifi_Connect();

void loop() {
read_sensors();
send_thinkspeak();
delay(10000);
}

You might also like