echo '' ;

Archives

ESP8266 Arduino-core Tutorial – HTTP Post Data to Web Page

These various applications for sending data, especially in IoT projects. Below are some scenarios and use cases where sending data using an HTTP POST request can be beneficial. In this article will discuss about “ESP8266 Arduino-core Tutorial – HTTP Post Data to Web Page”.

Required

  • ESP8266 Any Module (Used NodeMCU Dev Kit Version 1.0)
  • Arduino IDE with ESP8266 Platform
  • Web Sever (Shared, Linux, Windows or Own Server like with any hosting providers: Amazon, GoDaddy, GlobeHost, BlueHost, HostingRaja and etc)
  • Cpanel Login Access and update index file contend

Cpanel index.php  code for web Server

Note I tested its code is working well.

<?php
    $age= $name = $TimeStamp = "";
    $Hum= $Temp =  "";
    $timezone = new DateTimeZone("Asia/Kolkata" );
        $date = new DateTime();
        $date->setTimezone($timezone );
        echo  $date->format('Ymd-H:i:s');
        $TimeStamp = $date;
        
    
     if( $_REQUEST["Hum"] ||  $_REQUEST["Temp"] ) 
    {
        echo " The Humidity is: ". $_REQUEST['Hum']. "%<br />";
        echo " The Temperature is: ". $_REQUEST['Temp']. " Celcius<br />";
        
        $Hum= $_REQUEST["Hum"];
        $Temp = $_REQUEST["Temp"];
        
        $myfile = fopen("arun.txt", "a") or die("Unable to open file!");
        fwrite($myfile, "TimeStamp : ".$date->format('Ymd-H:i:s')."\t | Hum : ".$Hum."\t | Temp : ".$Temp. " |\n");
        fclose($myfile);
        
    }
    
    if( $_GET["name"] || $_GET["age"] ) {
        echo "Welcome ". $_GET['name']. "<br />";
        echo "You are ". $_GET['age']. " years old.". "<br />";
        
        
        
        $age= $_GET["age"];
        $name = $_GET["name"];
        
        $myfile = fopen("arun.txt", "a") or die("Unable to open file!");
        fwrite($myfile, "TimeStamp : ".$date->format('Ymd-H:i:s')."\t | Name : ".$name."\t | Age : ".$age. " |\n");
        fclose($myfile);
    
        
        exit();
    }
    
    $myfile = fopen("arun.txt", "r") or die("Unable to open file!");
        echo "<table border='1' align ='center' >";
        while(!feof($myfile)) {
          echo "<tr><td border='1' align ='center' >";
          echo fgets($myfile) . "<br>";
          echo "</td></tr>";
        }
        echo "</table>";
        fclose($myfile);
?>

ESP8266 Arduino-Core Code for HTTP Post Data

//www.Aruneworld.com/embedded/esp8266/esp8266-arduino-core/

const char* hostGet = "iot.aruneworld.com/ESP8266/NodeMCU/HTTP-Post/"; 
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char* ssid="ArunEworld";
const char*password="8300026060INDIA";
WiFiClient client;

void postData() {

   WiFiClient clientGet;
   const int httpGetPort = 80;

   //the path and file to send the data to:
   String urlGet = "/index.php";

 
  // We now create and add parameters:
  String src = "12345";
  String typ = "6789";
  String nam = "temp";
  String vint = "92"; 

  urlGet += "?Hum=" + src + "&Temp=" + typ ;
   
      Serial.print(">>> Connecting to host: ");
      Serial.println(hostGet);
      
       if (!clientGet.connect(hostGet, httpGetPort)) {
        Serial.print("Connection failed: ");
        Serial.print(hostGet);
      } else {
          clientGet.println("GET " + urlGet + " HTTP/1.1");
          clientGet.print("Host: ");
          clientGet.println(hostGet);
          clientGet.println("User-Agent: ESP8266/1.0");
          clientGet.println("Connection: close\r\n\r\n");
          
          unsigned long timeoutP = millis();
          while (clientGet.available() == 0) {
            
            if (millis() - timeoutP > 10000) {
              Serial.print(">>> Client Timeout: ");
              Serial.println(hostGet);
              clientGet.stop();
              return;
            }
          }

          //just checks the 1st line of the server response. Could be expanded if needed.
          while(clientGet.available()){
            String retLine = clientGet.readStringUntil('\r');
            Serial.println(retLine);
            break; 
          }

      } //end client connection if else
                        
      Serial.print(">>> Closing host: ");
      Serial.println(hostGet);
          
      clientGet.stop();

}

void setup() {
    Serial.begin(115200); // Starts the serial communication
  WiFi.begin(ssid, password); //begin WiFi connection
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println("ArunEworld");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  postData();

  delay(30000);

}

Make sure to replace the placeholders:

  • your-ssid and your-password with your WiFi credentials.
  • your-server-address with the address of your server.
  • /your-api-endpoint with the specific endpoint on your server that handles the incoming POST requests.

Applications and Uses

Security aspects & Encryption

When implementing HTTP POST requests in your application, consider security aspects such as using HTTPS for encrypted communication and implementing proper authentication mechanisms to protect sensitive data. Always follow best practices for secure communication, especially when transmitting data over the internet.

FAQ

if you have the following Questions and most of the repeated and same-meaning questions, then the Above article should help you

  • How send data to web page using ESP8266?
  • How to HTTP Post Data to Web Page using ESP8266 via Arduino-core Tutorial –
  • ESP8266 send data to website?
  • Send ESP8266 Data to Your Webpage – no AT Commands
  • Arduino-Esp8266-Post-Data-to-Website
  • ESP8266: HTTP POST Requests
  • Posting and getting data from ESP on Apache WebServer
  • How to Send Data from Arduino to Webpage using WiFi?
  • How to send data to a server using ESP8266 with Arduino?

NEXT

Arduino-Core IDE Setup
ESP8266 Arduino Core Interface
ESP8266 Interface LED
ESP8266 Interface Button
ESP8266 Interface ADC
ESP8266 Arduno Core Projects
ESP8266 Project WebServer
HTTP Post Data to Web Page
Arduino Based Platforms
Cayenne MyDevice Get Start
Others
ESP8266 Arduino-Core Sitemap
ESP8266 Arduino-Core All Post

ESP8266 Arduino-Core Tutorial – Web Server

TCP Server Listener

The below Arduino code will also create a server and Access Point in ESP8266 which will continuously listen for a connection.

Code

//www.ArunEworld.com

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char *ssid = "ArunEworld";
const char *password = "Arun";

ESP8266WebServer server(80);

void handleRoot() 
{
    server.send(200, "text/html", "<t1>ArunEworld</t1>");
    server.send(200, "text/html", "<h1>ArunEworld : TCP WebServer Listener</h1>");
    server.send(200, "text/html", "<h2>You are connected</h2>");
}

void setup()
{
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");
    WiFi.softAP(ssid, password);
    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);
    server.on("/", handleRoot);
    server.begin();
    Serial.println("HTTP server started");
}

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

After uploading this sketch, you can find a new Access Point named “test” from your Laptop or PC.

Result


 

ESP8266 NodeMCU Tutorial – Web Server

The ESP8266 NodeMCU Tutorial – Web Server provides a comprehensive guide on how to set up a web server using the NodeMCU development board powered by the ESP8266 microcontroller.

Read more: ESP8266 NodeMCU Tutorial – Web Server

Simple Web Server

  • Simple web server display heap, ip, mac address some other details ..
  • First need to connect ESP8266 with WiFi Router. then access the web server using ip address
print("****** Wifi data's Initializing *********")
mode = wifi.STATION
ssid = "ArunEworld"
password = "Arun"

print("****** Setup Wifi Settings *********")
wifi.setmode(mode)
wifi.sta.config(ssid, password)

function Wif_Connect()
    WC = wifi.sta.status() --WC Wifi_Connect
    print("Wifi Status is : " .. WC)

    if WC == 0 then
        print("0.Satation is Idle ??")
        wifi.sta.autoconnect(auto)
    elseif WC == 1 then
        print("1.Satation Connecting....Wait a moment")
    elseif WC == 2 then
        print("2.password is wrong !")
    elseif WC == 3 then
        print("3.No Access Point Found !")
    elseif WC == 4 then
        print("4.Station connecting fail !")
    elseif WC == 5 then
        print("IP :" .. wifi.sta.getip())
        tmr.stop(0)
        -- dofile("AEW_Webserver.lua")
        -- print("IP :"..wifi.sta.getip())
        -- dofile("File_name.lua")
        -- please write your file name
    end
end

print("**** Webserver Running........ ****")
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
    conn:on("receive", function(client, request)
        buf = buf .. "<h1>Arun Eworld</h1>"
        buf = buf .. "Chip ID :<b>" .. node.chipid() .. "</b><BR>"
        --[[ 
        buf = buf.."Heap :<b>".. node.heap() .. "</b><BR>";
        buf = buf.."Station Mac Address :<b>".. wifi.sta.getmac() .. "</b><BR>";
        buf = buf.."AP Mac Address :<b>".. wifi.ap.getmac() .. "</b><BR>";
        buf = buf.."GetMode :<b>".. wifi.getmode() .. "</b><BR>";
        buf = buf.."Status :<b>".. wifi.sta.status() .. "</b><BR>";
        --buf = buf.."AP IP Address :<b>".. wifi.ap.getip() .. "</b><BR>";
        buf = buf.."Station IP Address :<b>".. wifi.sta.getip() .. "</b><BR>";
        buf = buf.."TMR.NOW :<b>" .. tmr.now() .. "</b><BR<BR><BR>";
        ]]--
        client:send(buf)
        client:close()
        collectgarbage()
    end)
end)

tmr.alarm(0, 5000, 1, Wif_Connect)

Code Explanation

Sure, here’s an explanation of the provided Lua code:

  1. Wifi Initialization:
    • The code begins by printing a message indicating the initialization of WiFi data.
    • It sets the WiFi mode to Station mode.
    • Defines the SSID and password for the WiFi connection.
  2. WiFi Connection Function (Wif_Connect):
    • This function is responsible for handling the WiFi connection process.
    • It retrieves the current WiFi connection status using wifi.sta.status().
    • Depending on the status, it performs different actions:
      • If the status is 0, it indicates that the station is idle, and it attempts to autoconnect.
      • If the status is 1, it indicates that the station is connecting.
      • If the status is 2, it indicates that the password is incorrect.
      • If the status is 3, it indicates that no Access Point (AP) is found.
      • If the status is 4, it indicates that the connection to the AP failed.
      • If the status is 5, it indicates a successful connection, and it prints the assigned IP address.
        • It also stops the timer (tmr.stop(0)), which triggers the connection attempt.
  3. Webserver Setup:
    • The code prints a message indicating that the web server is running.
    • It creates a TCP server (srv) that listens on port 80.
    • Upon receiving a connection, it defines a callback function to handle incoming requests.
    • The callback function constructs an HTML response (buf) containing the header <h1>Arun Eworld</h1> and the chip ID.
    • The response is sent back to the client, and the connection is closed.
  4. Timer Initialization:
    • A timer (tmr) is set to call the Wif_Connect function every 5 seconds (tmr.alarm(0, 5000, 1, Wif_Connect)).

This code initializes the WiFi connection, continuously attempts to connect to the configured network, and sets up a basic web server to handle incoming requests. (ESP8266 NodeMCU Tutorial Web Server)

TCP Server Listener

This code given below will configure the ESP to act as an Access Point and it has its own SSID=”ArunEworld” and Password=”Arun” and also act as the server which will continuously listen for a connection.

Code

This code initializes the ESP8266 module as an access point with the SSID “ArunEworld” and password “Arun”. It then creates a TCP server that listens on port 80. When a connection is established, it prints any received data and releases resources after sending a response.

print("ArunEworld - ESP8266 Server")
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="ArunEworld", pwd="Arun"})
print("Server IP Address:", wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(80, function(conn)
    conn:on("receive", function(conn, receivedData)
        print("Received Data: " .. receivedData)
    end)
    conn:on("sent", function(conn)
        collectgarbage()
    end)
end)

Result

Host pot


Code Explanation

This code initializes the ESP8266 module as an access point with the SSID “ArunEworld” and password “Arun”, creates a TCP server listening on port 80, and defines callback functions to handle received and sent data.

LineCodeExplanation
1print("ArunEworld - ESP8266 Server")Prints a message indicating the initialization of the ESP8266 server.
2wifi.setmode(wifi.STATIONAP)Sets the mode of the WiFi module to STATIONAP, enabling it to function as both a station and an access point.
3wifi.ap.config({ssid="ArunEworld", pwd="Arun"})Configures the access point with the SSID “ArunEworld” and password “Arun”.
4print("Server IP Address:", wifi.ap.getip())Prints the IP address assigned to the ESP8266 access point.
6sv = net.createServer(net.TCP)Creates a TCP server object.
7sv:listen(80, function(conn)Starts the server and listens for connections on port 80.
8conn:on("receive", function(conn, receivedData)Sets up a callback function to handle received data.
9print("Received Data: " .. receivedData)Prints the received data.
10end)Ends the “receive” callback function definition.
11conn:on("sent", function(conn)Sets up a callback function to handle data sent.
12collectgarbage()Collects garbage to free up memory.
13end)Ends the “sent” callback function definition.
14end)Ends the server callback function definition.

NEXT

NodeMCU Get Start
NodeMCU Build Firmware
NodeMCU Flash Firmware
NodeMCU IDE
ESP8266 NodeMCU Modules
NodeMCU Module–Firmware Info
NodeMCU Module – GPIO
NodeMCU Module – Node
NodeMCU Module – WiFi
NodeMCU Module – Timer
NodeMCU Module – I2C
NodeMCU Module – File
NodeMCU Module – NET
NodeMCU Module – HTTP
NodeMCU Module – MQTT
ESP8266 NodeMCU Interface
NodeMCU Interface LED
NodeMCU Interface Button
NodeMCU Interface 7 Seg
NodeMCU Interface LCD
NodeMCU Interface ADC
NodeMCU Interface DHT11
NodeMCU Interface MCP23008
NodeMCU Interface MCP23017
NodeMCU Interface ADXL345
NodeMCU Interface DS18B20
ESP8266 NodeMCU Tutorials
NodeMCU Tutorials Google Time
NodeMCU Tutorials WebServer
ESP8266 NodeMCU Projects
Imperial March Ringtone Play
WiFi Router Status Indicator
ESP8266 NodeMCU Project – Home Automation
Others
NodeMCU All Post
Sitemap