IOT Tutorial

Make a webserver


This example show you how to make a webserver that is hosted on the esp32 itself.

Boiled down example based on random nerd tutorials.

[show the code]

/*********

Edited version of Rui Santos

Complete project details at https://randomnerdtutorials.com

*********/


// Load Wi-Fi library

#include <WiFi.h>


// Replace with your network credentials

const char* ssid = "REPLACE_WITH_YOUR_SSID";

const char* password = "REPLACE_WITH_YOUR_PASSWORD";


// Set web server port number to 80

WiFiServer server(80);


// Variable to store the HTTP request

String header;


// Auxiliar variables to store the current output state

String ledState = "off";


#define ONBOARD_LED 2



// Current time

unsigned long currentTime = millis();

// Previous time

unsigned long previousTime = 0;

// Define timeout time in milliseconds (example: 2000ms = 2s)

const long timeoutTime = 2000;


void setup() {

Serial.begin(9600);

// Initialize the output variables as outputs

pinMode(ONBOARD_LED, OUTPUT);


// Set outputs to LOW

digitalWrite(ONBOARD_LED, 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() {

WiFiClient client = server.available(); // Listen for incoming clients


if (client) { // If a new client connects,

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 /led/on") >= 0) {

Serial.println("GPIO led on");

ledState = "on";

digitalWrite(ONBOARD_LED, HIGH);

} else if (header.indexOf("GET /led/off") >= 0) {

Serial.println("GPIO led off");

ledState = "off";

digitalWrite(ONBOARD_LED, 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(".btnGray {background-color: #555555;}</style></head>");


// Web Page Heading

client.println("<body><h1>Control the onboard LED</h1>");


// Display current state, and ON/OFF buttons


// If the ledState is off, it displays the ON button

if (ledState == "off") {

client.println("<p><a href=\"/led/on\"><button class=\"button btnGray\">OFF</button></a></p>");

} else {

client.println("<p><a href=\"/led/off\"><button class=\"button \">ON</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("");

}

}

  1. Either setup a wifi connection on your phone or use an existing one.

2. Make sure that your wifi hotspot i compatible with 2.4ghz - on IOS toggle Maximise Compatibility.

3. Copy the code from above in the collapsable dropdown and change the wifi name and pasword.

4. In the serial terminal see that it connects to your wifi hotspot and take note of the ip number.

5 Copy the ip into your url adress bar, make sure that your phone/computer is on the same wifi networks as the esp32

5. Click the button and the onboard led should blink.

Send UDP MESSAGES BETWEEN TWO ESP32 or a Computer


[show the code]

// Load Wi-Fi library

#include <WiFi.h>


// Replace with your network credentials

const char* ssid = "REPLACE_WITH_YOUR_SSID";

const char* password = "REPLACE_WITH_YOUR_PASSWORD";

//The udp library class

WiFiUDP udp;

unsigned int localUdpPort = 4210; // local port to listen on

char incomingPacket[255]; // buffer for incoming packets

char * replyPacket = "Hi there! Got the message :-)"; // a reply string to send back

char * broadcastPacket = "I am here";


void setup() {

Serial.begin(9600);


// 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

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());


udp.begin(localUdpPort);

Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);


}


unsigned long timer = 0;


void loop() {



int packetSize = udp.parsePacket();

if (packetSize)

{

// receive incoming UDP packets

Serial.printf("Received %d bytes from %s, port %d\n", packetSize, udp.remoteIP().toString().c_str(), udp.remotePort());

int len = udp.read(incomingPacket, 255);

if (len > 0)

{

incomingPacket[len] = 0;

}

Serial.printf("UDP packet contents: %s\n", incomingPacket);


// send back a reply, to the IP address and port we got the packet from

udp.beginPacket(udp.remoteIP(), udp.remotePort());

udp.print(replyPacket);

udp.endPacket();

}

/*if (millis() - timer > 10000) // send a broadcast msg every 10 seconds

{

timer = millis();

udp.beginPacket("255.255.255.255", localUdpPort);

udp.print(broadcastPacket);

udp.endPacket();

Serial.println("Just broadcasted");


}*/

}



  1. Either setup a wifi connection on your phone or use an existing one.

2. Copy the code from above in the collapsable dropdown and change the wifi name and pasword.

3. In the serial terminal see that it connects to your wifi hotspot and take note of the ip number.

4. Install https://packetsender.com/download#show to send a packege to the board.

WEBSOCKETS to P5.JS



[show the arduino code]

// Load Wi-Fi library

#include <WiFi.h>

#include <WebSocketsServer.h>



WebSocketsServer webSocket = WebSocketsServer(81);


// Replace with your network credentials

const char* ssid = "REPLACE_WITH_YOUR_SSID";

const char* password = "REPLACE_WITH_YOUR_PASSWORD";


void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {

const uint8_t* src = (const uint8_t*) mem;

Serial.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);

for (uint32_t i = 0; i < len; i++) {

if (i % cols == 0) {

Serial.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);

}

Serial.printf("%02X ", *src);

src++;

}

Serial.printf("\n");

}


void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {


switch(type) {

case WStype_DISCONNECTED:

Serial.printf("[%u] Disconnected!\n", num);

break;

case WStype_CONNECTED:

{

IPAddress ip = webSocket.remoteIP(num);

Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);


// send message to client

webSocket.sendTXT(num, "Connected");

}

break;

case WStype_TEXT:

Serial.printf("[%u] get Text: %s\n", num, payload);


// send message to client

// webSocket.sendTXT(num, "message here");


// send data to all connected clients

// webSocket.broadcastTXT("message here");

break;

case WStype_BIN:

Serial.printf("[%u] get binary length: %u\n", num, length);

hexdump(payload, length);


// send message to client

// webSocket.sendBIN(num, payload, length);

break;

case WStype_ERROR:

case WStype_FRAGMENT_TEXT_START:

case WStype_FRAGMENT_BIN_START:

case WStype_FRAGMENT:

case WStype_FRAGMENT_FIN:

break;

}


}


void setup() {

Serial.begin(9600);


// 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

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());


// server address, port and URL

webSocket.begin();


// event handler

webSocket.onEvent(webSocketEvent);

}


unsigned long timer = 0;

int counter = 0;


void loop() {

webSocket.loop();

if (millis() - timer > 2000) // send a counter value every 2 sec.

{

String numberString = String(counter);

webSocket.broadcastTXT(numberString);

counter = counter + 1;

timer = millis();

}


}





[show the p5js code]

// where the serial server is (your local machine):

var host = '10.0.1.27:81';

var socket; // the websocket

var sensorValue = 0; // the sensor value


function setup() {

createCanvas(400, 400);

// connect to server:

socket = new WebSocket('ws://' + host);

// socket connection listener:

socket.onopen = sendIntro;

// socket message listener:

socket.onmessage = readMessage;

}


function draw() {

background("#2307AF");

fill(255);

ellipse(sensorValue, height / 2, 20, 20);

text(sensorValue, 20, 20);

}


function sendIntro() {

// convert the message object to a string and send it:

socket.send("Hello");

}


function readMessage(event) {

var msg = event.data; // read data from the onmessage event

sensorValue = Number(msg);

println(sensorValue); // print it

}


  1. Either setup a wifi connection on your phone or use an existing one - make sure that your laptop is on the same network.

2. Install the library "websocket" by Markus Sattler

3. Copy the Arduino code from above in the collapsable dropdown to Arduino and change the wifi name and pasword.

4. In the serial terminal see that it connects to your wifi hotspot and take note of the ip number.

5. Open this p5.js sketch and change the ip to the one in your terminal. Press play.

ESP NOW



ESP-NOW is a protocol developed by Espressif, which enables multiple devices to communicate with one another without using Wi-Fi. The protocol is similar to the low-power 2.4GHz wireless connectivity that is often deployed in wireless mouses. So, the pairing between devices is needed prior to their communication. After the pairing is done, the connection is secure and peer-to-peer, with no handshake being required.

Look at the examples in the example library and have a look at Random nerds tutorial to learn more.

Connect to Things Speak



ThingSpeak for IoT Projects is data collection in the cloud. Use this to monitor your plant - track things and devices and make graph over the temperature over time at a certain locataion etc.

https://randomnerdtutorials.com/esp32-thingspeak-publish-arduino/

USB SERIAL to p5



It is possible to conenct via serial from P5js to an ESP32 - but because serial communication is not allowed you need a broker - a middle man.

https://medium.com/@yyyyyyyuan/tutorial-serial-communication-with-arduino-and-p5-js-cd39b3ac10ce

Note: new development in serial communication in browsers gives direct connection permission - I have not found a simple guide but here you can read the specifications: https://web.dev/serial/


CONNECT TO A TELLO DRONe



  1. Go to this link and download the zip library:

https://github.com/akshayvernekar/telloArduino

2. Extract all the files on your desktop

3. Move the "tello" folder into your Arduino library folder you can find it in your documents folder

4. Turn on the drone by pressing the button on the side shortly. An led will start to blin on the fron.

5. Open your wifi list and look for the tello wifi. Turn off the drone when you have the name to preserve battery.

4. Open the the Arduino example in the "tello_example" folder. Change the networkName to the name of wifi - leave the password blank

4. turn on and place the drone in an open space. Then upload the code.

Get the Weather (online API example)



Processing as Websocket PROXY



  1. install processing and install the websocket library from the library meny

2. Run the code below in processing:

import websockets.*;

WebsocketServer ws;


void setup(){

size(200,200);

ws= new WebsocketServer(this,8025,"");

}


void draw(){

background(0);

}


void webSocketServerEvent(String msg){

println(msg);

ws.sendMessage(msg);

}

3. Run the code below i p5 - or use the link:

// where the serial server is (your local machine):

var host = 'localhost:8025';

var socket; // the websocket

var sensorValue = 0; // the sensor value


function setup() {

createCanvas(400, 400);

// connect to server:

socket = new WebSocket('ws://' + host);

// socket connection listener:

socket.onopen = sendIntro;

// socket message listener:

socket.onmessage = readMessage;

}


function draw() {

background("#2307AF");

fill(255);


}


function sendIntro() {

// convert the message object to a string and send it:

//socket.send("Hello");

}


function mouseClicked()

{

socket.send("Hello");

}


function readMessage(event) {

var msg = event.data; // read data from the onmessage event

println(msg); // print it

}

CONNECT TO P5.js over BLE



TCP/IP CLIENT<>SERVER



Node RED



MQTT ADAFRUiT Dashboard


https://learn.adafruit.com/welcome-to-adafruit-io/getting-started-with-adafruit-io

WEBSERVER WITH A BUTTON AND PAGE HIT COUNTER

/*********


Edited version of Rui Santos


Complete project details at https://randomnerdtutorials.com


*********/


int showCounter = 0;



// Load Wi-Fi library


#include <WiFi.h>




// Replace with your network credentials


const char* ssid = "hobye";


const char* password = "minminmin";




// Set web server port number to 80


WiFiServer server(80);




// Variable to store the HTTP request


String header;




// Auxiliar variables to store the current output state


String ledState = "off";




#define ONBOARD_LED 2






// Current time


unsigned long currentTime = millis();


// Previous time


unsigned long previousTime = 0;


// Define timeout time in milliseconds (example: 2000ms = 2s)


const long timeoutTime = 2000;




void setup() {


Serial.begin(9600);


// Initialize the output variables as outputs


pinMode(ONBOARD_LED, OUTPUT);

pinMode(25, INPUT_PULLUP);



// Set outputs to LOW


digitalWrite(ONBOARD_LED, 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() {


WiFiClient client = server.available(); // Listen for incoming clients




if (client) { // If a new client connects,


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 /led/on") >= 0) {


Serial.println("GPIO led on");


ledState = "on";


digitalWrite(ONBOARD_LED, HIGH);


} else if (header.indexOf("GET /led/off") >= 0) {


Serial.println("GPIO led off");


ledState = "off";


digitalWrite(ONBOARD_LED, 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(".btnGray {background-color: #555555;}</style></head>");




// Web Page Heading


client.println("<body><h1>MADS IS TINKERING</h1>");


showCounter = showCounter + 1;

client.println("<h1>");

client.println("This page has been shown ");

client.println(showCounter);

client.println(" times");

client.println("</h1>");


boolean btnPressed = !digitalRead(25);


if (btnPressed == true) {


client.println("button has been pressed.");


}



// Display current state, and ON/OFF buttons




// If the ledState is off, it displays the ON button


if (ledState == "off") {


client.println("<p><a href=\"/led/on\"><button class=\"button btnGray\">OFF</button></a></p>");


} else {


client.println("<p><a href=\"/led/off\"><button class=\"button \">ON</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("");


}


}

EXAMPLE COMPARE A MSG OVER UDO

// Load Wi-Fi library


#include <WiFi.h>




// Replace with your network credentials


const char* ssid = "hobye";


const char* password = "minminmin";


//The udp library class


WiFiUDP udp;


unsigned int localUdpPort = 4210; // local port to listen on


char incomingPacket[255]; // buffer for incoming packets


char * replyPacket = "Hi there! Got the message :-)"; // a reply string to send back


char * broadcastPacket = "I am here";




void setup() {


Serial.begin(9600);




// 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


Serial.println("");


Serial.println("WiFi connected.");


Serial.println("IP address: ");


Serial.println(WiFi.localIP());




udp.begin(localUdpPort);


Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);




}




unsigned long timer = 0;




void loop() {






int packetSize = udp.parsePacket();


if (packetSize)


{


// receive incoming UDP packets


Serial.printf("Received %d bytes from %s, port %d\n", packetSize, udp.remoteIP().toString().c_str(), udp.remotePort());


int len = udp.read(incomingPacket, 255);


if (len > 0)


{


incomingPacket[len] = 0;


}


Serial.printf("UDP packet contents: %s\n", incomingPacket);

String input = incomingPacket;

if(input.equals("ledON"))

{

Serial.println("got led on");

}




// send back a reply, to the IP address and port we got the packet from


udp.beginPacket(udp.remoteIP(), udp.remotePort());


udp.print(replyPacket);


udp.endPacket();


}


/*if (millis() - timer > 10000) // send a broadcast msg every 10 seconds


{


timer = millis();


udp.beginPacket("255.255.255.255", localUdpPort);


udp.print(broadcastPacket);


udp.endPacket();


Serial.println("Just broadcasted");




}*/


}