Pages

Friday, 20 September 2019

ESP32-OTA (Over the air) programming

ESP32-OTA (Over the air) programming

Aim:

Turn ON and OFF an LED after Particular delay using OTA web server

Description:

Turn To learn how to connect LED to digital pins of an ESP32 Microcontroller and program to blink an LED using OTA web server.

Hardware required:

ESP32-Microcontroller development board.

Pin connection:


Pin Mapping:

LED
ESP32
LED
I04

Procedure:
1. When you install the ESP32 add-on for the Arduino IDE, it will automatically install the      
    Arduino OTA library.
2. Go to File > Examples > ArduinoOTA > OTAWebUpdater.


3. The following code should load.

#include <WiFi.h>
#include <WiFiClient.h
#include <WebServer.h
#include <ESPmDNS.h
#include <Update.h>
const char* host = "esp32"; const char* ssid = "ssid";
const char* password = "password";

WebServer server(80);

/*
* Login page
*/

const char* loginIndex = "<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>" 
   "<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>" 
"<br>"
"</td>" 
"<br>"
"<br>"
"</tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>" 
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>" 
"<br>"
"<br>" 
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>" 
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)" 
"{"
"if(form.userid.value=='admin' && form.pwd.value=='admin')" 
"{"
"window.open('/serverIndex')" 
"}"
"else" 
 "{"
" alert('Error Password or Username')/*displays error message*/" 
"}"
"}"
"</script>";

/*
* Server Index Page
*/

const char* serverIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" 
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>" 
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>" 
"<script>" 
"$('form').submit(function(e){" "e.preventDefault();"
"var form = $('#upload_form')[0];" "var data = new FormData(form);" " $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data," "contentType: false," "processData:false," "xhr: function() {"
"var xhr = new window.XMLHttpRequest();" "xhr.upload.addEventListener('progress', function(evt) {" "if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');" 
"}"
"}, false);"  
"return xhr;" 
"},"
"success:function(d, s) {" "console.log('success!')" 
"},"
"error: function (a, b, c) {" "}"
"});"
"});"
"</script>";

/*
* setup function
*/
void setup(void) {
Serial.begin(115200);

// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) { delay(500);
Serial.print(".");
}
Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP());

/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local Serial.println("Error setting up MDNS responder!"); 
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */ server.on("/", HTTP_GET, []() { server.sendHeader("Connection", "close"); 
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */ 
server.on("/update", HTTP_POST, []() { server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
}

void loop(void) { server.handleClient(); delay(1);
}

1. You should change the following lines on the code to include your own network credentials.
Ø  const char* ssid = “ ” ;
Ø  const char* password = “ ” ;
    2.       Upload the above code to ESP32 board. Enter proper network credentials.
    3.       Now select proper board and serial port.
    4.   Once the code is uploaded , open serial monitor select baud rate 115200 and press enable         
          button and then you will get ESP32 IP address.


   8.   Copy the IP address which you obtain from the serial monitor and paste it in your browser.

   9.  Username: admin
          Password: admin

    10. After entering the username and password a new tab should open on the /serverIndex URL.  
          This page allows you to upload a new code to your ESP32. You should upload .bin files.


Preparing the sketch:
    1.  Write a simple program (Blinking of LED) using OTA web server and save it with the name 
           LED_blink and complile it.

     2.      Once the uploading is done go to Sketch<Export compiled binary.


         3.        Then select Sketch<Show sketch folder.
         4.        In this folder two files will be generated .ino and .bin.
         5.        You should upload the .bin file using OTA Web Server.


        6.        In browser on ESP32 OTA Web Updater page , click on choose file button
        7.        Select .bin file and click Update.
        8.        Code will be successfully uploaded.


Output:


Tuesday, 17 September 2019

ESP32-FTP

This summary is not available. Please click here to view the post.

ESP32-JSON

ESP32-JSON

Aim:

To interface Wi-Fi module with ESP32 to send data to server using RDL ESP32 Development board.

Description:

Interfacing wi-fi module to send data to the server using ESP32microcontroller.

Hardware required:

ESP32-Microcontroller development board.

Pin connection:



Procedure:
1.        Connect the USB cable to the ESP32 development board.
2.        Open Arduino IDE .Select DOIT ESP32 DEVKIT V1in boards and select COM port.
3.        Verify the program and upload it.
4.        Now you can see wifi connected along with the IP address on the serial monitor.
5.     To check the inserted values of gas and temperature use the server address and check it on        
        the browser.
   

Program:

/*
*     This sketch sends data via HTTP POST requests to data.sparkfun.com service.
*
*     You need to get streamId and privateKey at data.sparkfun.com and paste them
*     below. Or just customize this script to talk to other HTTP servers.
*
*/

#include <WiFi.h>

char ssid[]                        = "your ssid"; char password[] = "your password";

const char* host = "varmatrix.com";
const char* streamId                       = "....................................................... ";
const char* privateKey = ".......................................................................... ";
void setup() { Serial.begin(115200); delay(10);

// We start by connecting to a WiFi network

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

/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause network-issues with your other WiFi-devices on your WiFi-network. */
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) { delay(500);
Serial.print(".");
}

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

int value = 0;
 void loop() {

String url="/surendrardl/nitk/getone/insert.php?"; String jason_string="";
char cmd=0;
while(cmd!=13)
{
if (Serial.available()) { cmd=Serial.read();
//        Serial.write(cmd); if(cmd!=13)
jason_string+=cmd;
}
}

while(Serial.available()>0) {Serial.read();}

Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections const int httpPort = 80;
if (!esp32client.connect(host, httpPort)) { Serial.println("connection failed"); return;
}

// We now create a URI for the request

//String              url="/energyconsumption/insert.php?one=1&two=3&three=2";
Serial.print("Requesting URL:");
Serial.println(url);
//String jason_string="{\"gas\":\"40\",\"temp\":\"70\"}";
// This will send the request to the server esp32client.print(String("POST ") + url + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" + "Accept: *" + "/" + "*\r\n" +
"Content-Length: " + jason_string.length() + "\r\n" + "Content-Type: application/json\r\n" +
"\r\n" + jason_string
+ "\r\n");
unsigned long timeout = millis(); while (esp32client.available() == 0) {
if (millis() - timeout > 5000) { Serial.println(">>> Client Timeout !"); esp32client.stop();
return;
}
}

// Read all the lines of the reply from server and print them to Serial while(esp32client.available()){
String line = esp32client.readStringUntil('\r');
Serial.print(line);
}

Serial.println();
// Serial.println("closing connection");
}


Output:

1.    Open serial monitor you can see Wi-Fi connected along with IP address
Insert { “gas”:”40” , “temperature”:”70” } in the serial monitor and press enter.



2. Enter http://varmatrix.com/sudrendrerdl/nitk/postone/postportal.html in your browser.