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("");
}
}
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
Based on this example:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/udp-examples.html
[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");
}*/
}
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
}
0. Allow for insecure connections in chrome on editer.p5js.org
OBS: P5JS tries to force you to use a secure connection, which is not compatible with all websocket solutions for Arduino. So, if you are having problems, then:
Go to editor.p5j.org
Go to site settings, which can be opened from the URL.
Scroll down to insecure content and choose "allow".
Refresh page
You should now have a "not secure" warning.
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.
NOTE!! THERE IS A BUG IN THIS EXAMPLE - YOU NEED TO DOWNLOAD THE file in the p5js editor and run it locally - p5js editor defaults to https and the boards uses an insecure connection.
Note: use ArduinoWebsockets.h library instead for ssh: https://github.com/gilmaimon/ArduinoWebsockets
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/
ESP32/Arduino SERIAL to p5 (Directly)
On some browsers (tested in chrome) you can communicate directly with an Arduino (Any including ESP32 and UNO) through Serial communication. This example show you how.
The old way that works in all browser is to use the p5.serial library which uses as proxy app to establish the connection:
https://github.com/p5-serial/p5.serialport
[show the arduino code]
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
}
unsigned long timer = 0;
void loop() {
// put your main code here, to run repeatedly:
if (millis() - timer > 1000)
{
timer = millis();
Serial.println("hello");
}
while (Serial.available() > 0) {
Serial.print((char)Serial.read());
}
}
[show the p5js code]
let serialAvaliable = false;
let serialInput = "";
function setup() {
createCanvas(400, 400);
print("press c to connect")
}
function keyPressed() {
if (key == "c") {
serialConnect();
}
}
var timer = 0;
function draw() {
background(220);
// prints the serial input buffer when the serialAvaliable flag is true
if (serialAvaliable) {
serialAvaliable = false;
print(serialInput);
serialInput = "";
}
//Send a hello to the arduino every 3 seconds
//- if it shows up in the console it means that the arduino returned it
if (millis() - timer > 3000) {
timer = millis();
serialWrite("hello from p5");
}
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// SERIAL COMMUNICATION FUNCTIONS BELOW
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
let port;
let reader;
let inputDone;
let outputDone;
let inputStream;
let outputStream;
let portIsOpen = false;
async function serialListen() {
if (portIsOpen) {
while (true) {
const { value, done } = await reader.read();
if (value) {
serialAvaliable = true;
serialInput = serialInput + value;
}
if (done) {
console.log("[readLoop] DONE", done);
reader.releaseLock();
break;
}
}
}
}
async function serialConnect() {
if (navigator.serial) {
port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
const decoder = new TextDecoderStream();
inputStream = decoder.readable;
inputDone = port.readable.pipeTo(decoder.writable);
reader = inputStream.getReader();
const encoder = new TextEncoderStream();
outputDone = encoder.readable.pipeTo(port.writable);
outputStream = encoder.writable;
portIsOpen = true;
print("Port is open");
serialListen();
} else {
print("Serial not compatible with the browser you are using :/");
}
}
function serialWrite(line) {
if (portIsOpen) {
// CODELAB: Write to output stream
const writer = outputStream.getWriter();
writer.write(line);
writer.releaseLock();
}
}
Upload the Arduino code above to the board
2. Open the example sketch or copy paste it from the p5js above.
3. Run the sketch while the arduino board is connected to the computer. Click on the canvas to the right and press C. A dialog box should appear with where you can choose the port.
4. In the console you should now be able to see the communication between the two.
CONNECT An ESP32 TO A TELLO DRONe
Go to this link and download the zip library:
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.
Processing as Websocket PROXY
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 in 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
}
MQTT / PUBSUB VIA Shiftr
[show the arduino code]
// This example uses an ESP32 Development Board
// to connect to shiftr.io.
//
// You can check on your device after a successful
// connection here: https://www.shiftr.io/try.
//
// by Joël Gähwiler
// https://github.com/256dpi/arduino-mqtt
#define ONBOARD_LED 2
#include <WiFi.h>
#include <MQTT.h>
WiFiClient net;
MQTTClient client;
unsigned long lastMillis = 0;
void connect() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.print("\nconnecting...");
while (!client.connect("arduino", "public", "public")) {
Serial.print(".");
delay(1000);
}
Serial.println("\nconnected!");
client.subscribe("/idsp5js");
// client.unsubscribe("/hello");
}
void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
if(topic.equals("/idsp5js") && payload.equals("on"))
{
digitalWrite(ONBOARD_LED,HIGH);
}
else if(topic.equals("/idsp5js") && payload.equals("off"))
{
digitalWrite(ONBOARD_LED,LOW);
}
// Note: Do not use the client in the callback to publish, subscribe or
// unsubscribe as it may cause deadlocks when other things arrive while
// sending and receiving acknowledgments. Instead, change a global variable,
// or push to a queue and handle it in the loop after calling `client.loop()`.
}
void setup() {
Serial.begin(9600);
WiFi.begin("WIFINAME", "PASSWORD");
// Note: Local domain names (e.g. "Computer.local" on OSX) are not supported
// by Arduino. You need to set the IP address directly.
client.begin("public.cloud.shiftr.io", net);
client.onMessage(messageReceived);
pinMode(ONBOARD_LED,OUTPUT);
connect();
}
void loop() {
client.loop();
delay(10); // <- fixes some issues with WiFi stability
if (!client.connected()) {
connect();
}
// publish a message roughly every second.
if (millis() - lastMillis > 1000) {
lastMillis = millis();
client.publish("/idsesp32", "I am online");
}
}
[show the p5js code]
// Make sure that this string is in your index.html header:
// <script crossorigin="anonymous" src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
// XXXX
var client;
function setup() {
createCanvas(windowWidth, windowHeight);
client = mqtt.connect(
"wss://public:public@public.cloud.shiftr.io",
{
clientId: "p5jsids",
}
);
client.on("connect", function () {
console.log("connected!");
client.subscribe("/idsesp32");
});
client.on("message", function (topic, message) {
print(topic + ": " + message);
});
textSize(30);
}
var lightIsOn = false
var mouseIsPressedOld = false
function draw() {
if(mouseIsPressed == true && mouseIsPressedOld == false)
{
lightIsOn = !lightIsOn;
if(lightIsOn)
{
client.publish("/idsp5js", "on");
}
else
{
client.publish("/idsp5js", "off");
}
}
mouseIsPressedOld = mouseIsPressed;
if(lightIsOn)
{
background(0,0,255);
}
else
{
background(100);
}
text("Click to turn on led",100,100);
}
function keyPressed()
{
}
0. Either setup a wifi connection on your phone or use an existing one. - make sure to have 2.4ghz and maximize compability
1. Install mgtt by Joël Gähwiler for arduino
2. Copy the Arduino code from above in the collapsable dropdown to Arduino and change the wifi name and pasword.
3. Verify that you are connected in the serial monitor
4. Load up the p5js sketch: https://editor.p5js.org/hobye/sketches/Wdui-3T2U
and click the canvas to turn on and off the blue led on the board
HTTP REQUEST Get the Weather (P5JS)
[show the p5js code]
var weather;
// runs once when the app i starting.
function setup() {
loadGoogleFont("Droid Sans");
createCanvas(windowWidth, windowHeight);
noStroke();
noScrolling();
background(255, 255, 255);
strokeWeight(3);
var url =
"https://api.openweathermap.org/data/2.5/weather?q=roskilde,dk&APPID=d28e0b6cfa6d48a373d2359ff966fbad&units=metric";
httpGet(url, "jsonp", false, function (response) {
// when the HTTP request completes, populate the variable that holds the
// earthquake data used in the visualization.
weather = response;
print(weather);
});
//add some text
fill(242, 166, 121);
textSize(40);
}
// runs for each frame
function draw() {
// draws a background blue
background(1, 31, 38);
if (weather != undefined) {
text("Temp. Roskilde:\n" + weather.main.temp, 70, 150);
}
}
function keyReleased() {
if (key == "f") {
fullScreenToggle();
}
}
Use the code above or just click the link to get an example of retrieving api data in p5js
https://editor.p5js.org/hobye/sketches/lOkonv3yM
Get the current weather information. The url returns a json file with different information:
{"coord":{"lon":12.0803,"lat":55.6415},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":4.45,"feels_like":-2.73,"temp_min":3.89,"temp_max":5,"pressure":1026,"humidity":41},"visibility":10000,"wind":{"speed":6.17,"deg":310},"clouds":{"all":0},"dt":1614951920,"sys":{"type":1,"id":1588,"country":"DK","sunrise":1614923558,"sunset":1614963240},"timezone":3600,"id":2614481,"name":"Roskilde","cod":200}
Go to https://openweathermap.org/ for more information.
HTTP REQUEST Get the Weather (ESP32)
[show the arduino code]
/**
BasicHTTPSClient.ino
Created on: 14.10.2018
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
WiFiMulti WiFiMulti;
void setup() {
Serial.begin(9600);
// Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP("WIFINAME", "WIFIPASSWORD");
// wait for WiFi connection
Serial.print("Waiting for WiFi to connect...");
while ((WiFiMulti.run() != WL_CONNECTED)) {
Serial.print(".");
}
Serial.println(" connected");
}
void loop() {
WiFiClient *client = new WiFiClient;
if(client) {
{
// Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is
HTTPClient http;
Serial.print("[HTTPS] begin...\n");
if (http.begin(*client, "http://api.openweathermap.org/data/2.5/weather?q=roskilde,dk&APPID=d28e0b6cfa6d48a373d2359ff966fbad&units=metric")) { // HTTPS
Serial.print("[HTTPS] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTPS] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = http.getString();
Serial.println("### The full json ###");
Serial.println(payload);
// WARNING: This is a hack to get the temp - you should use arduinojson library (https://arduinojson.org/)
int startTempPos = payload.indexOf("\"temp\":") + 7; // +7 to compensate for the lenght
int endTempPos = payload.indexOf(",\"feels_like\"");
float currentTemp = payload.substring(startTempPos,endTempPos).toFloat();
Serial.print("The temp is:");
Serial.println(currentTemp);
}
} else {
Serial.printf("[HTTPS] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}
// End extra scoping block
}
delete client;
} else {
Serial.println("Unable to create client");
}
Serial.println();
Serial.println("Waiting 10s before the next round...");
delay(10000);
}
0. Either setup a wifi connection on your phone or use an existing one. - make sure to have 2.4ghz and maximize compability
2. Copy the Arduino code from above in the collapsable dropdown to Arduino and change the wifi name and pasword.
3. Open the terminal to see the temperature
CONNECT TO P5.js over BLE
TCP/IP CLIENT<>SERVER
Node RED
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.
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");
}*/
}