FAQ
- http is tcp or udp?
- http only works TCP
echo '' ;
This tutorial “ESP8266 NodeMCU HTTP Module” will discuss. The ESP8266 NodeMCU module is a popular microcontroller board based on the ESP8266 Wi-Fi chip. It’s widely used for IoT (Internet of Things) projects due to its low cost, built-in Wi-Fi capabilities, and ease of programming. One common use case of the ESP8266 NodeMCU is handling HTTP requests and responses, allowing it to communicate with web servers, APIs, and other devices over the internet.
Read more: ESP8266 NodeMCU Module – HTTPHTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. With the ESP8266 NodeMCU, you can leverage HTTP to send and receive data, control devices remotely, and interact with cloud services.
In this example, we’ll explore how to configure the ESP8266 NodeMCU to connect to a Wi-Fi network, monitor Wi-Fi events, and perform HTTP operations such as sending POST requests to a web server. Additionally, we’ll set up a GPIO pin to trigger an action when its state changes, showcasing how the ESP8266 NodeMCU can interact with external devices.
http.delete() | Executes a HTTP DELETE request. |
http.get() | Executes a HTTP GET request. |
http.post() | Executes a HTTP POST request. |
http.put() | Executes a HTTP PUT request. |
http.request() | Execute a custom HTTP request for any HTTP method. |
url
The URL to fetch, including the http://
or https://
prefixheaders
Optional additional headers to append, including \r\n; may be nil
body
The body to post; must already be encoded in the appropriate format, but may be emptycallback
The callback function to be invoked when the response has been received or an error occurred; it is invoked with the arguments status_code
, body
and headers
. In case of an error status_code
is set to -1.nil
station_cfg={} station_cfg.ssid="ArunEworld" -- Enter SSID here station_cfg.pwd="8300026060INDIA" --Enter password here server_link = "http://iot.aruneworld.com/httt-get.txt" -- set server URL wifi.setmode(wifi.STATION) -- set wi-fi mode to station wifi.sta.config(station_cfg)-- set ssid&pwd to config wifi.sta.connect() -- connect to router --Wifi Eent Monitoring file wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T) print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\tChannel: "..T.channel) end) wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T) print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\treason: "..T.reason) tmr.stop(0) end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T) print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: ".. T.netmask.."\n\tGateway IP: "..T.gateway) tmr.start(0) end) function GetFromArunEworld()-- callback function for get data http.get(server_link,'', function(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) end end) end -- call get function after each 5 second tmr.alarm(1, 5000, 1, function() GetFromArunEworld() end)
This code sets up a NodeMCU or similar device to connect to a Wi-Fi network, monitor Wi-Fi events, and periodically fetch data from a server over HTTP. It’s a good example of IoT device interaction with both Wi-Fi and web servers.
station_cfg={} station_cfg.ssid="ArunEworld" -- Enter SSID here station_cfg.pwd="8300026060INDIA" -- Enter password here
station_cfg
is defined, which contains the SSID and password for connecting to the Wi-Fi network.server_link = "http://iot.aruneworld.com/httt-get.txt" -- set server URL
wifi.setmode(wifi.STATION) -- set Wi-Fi mode to station wifi.sta.config(station_cfg)-- set SSID and password to config wifi.sta.connect() -- connect to router
station_cfg
, and then initiate a connection to the specified router.-- Wi-Fi Event Monitoring wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T) print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\tChannel: "..T.channel) end) wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T) print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\treason: "..T.reason) tmr.stop(0) -- Stop timer upon disconnection end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T) print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: ".. T.netmask.."\n\tGateway IP: "..T.gateway) tmr.start(0) -- Start timer upon obtaining IP address end)
function GetFromArunEworld()-- callback function for fetching data http.get(server_link,'', function(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) end end) end
GetFromArunEworld()
is defined as a callback function to fetch data from the specified server. It makes an HTTP GET request to server_link
and prints the response code and data.-- call the fetch function every 5 seconds tmr.alarm(1, 5000, 1, function() GetFromArunEworld() end)
GetFromArunEworld()
function every 5 seconds to fetch data from the server.station_cfg={} station_cfg.ssid="ssid" -- Enter SSID here station_cfg.pwd="password" -- Enter password here server = "http://api.thingspeak.com/update" -- set server URL count = 0 -- set initial count to 0 wifi.setmode(wifi.STATION) -- set wi-fi mode to station wifi.sta.config(station_cfg) -- set ssid&pwd to config wifi.sta.connect() -- connect to router function PostToThingSpeak() -- callback function for post data local string = "api_key=1EYZIS5OCRJSKZHG&field1="..count http.post(server, '', string, function(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) count = count + 1 -- increment count after each successful post end end) end -- call post function after each 20 seconds for ThingSpeak server update tmr.alarm(1, 20000, tmr.ALARM_AUTO, function() PostToThingSpeak() end)
This script connects to the specified Wi-Fi network, sends data to a ThingSpeak channel at regular intervals, and increments the count each time data is successfully posted.
station_cfg={} station_cfg.ssid="ssid" -- Enter SSID here station_cfg.pwd="password" -- Enter password here
station_cfg
with keys ssid
and pwd
, representing the SSID and password of the Wi-Fi network you want to connect to.server = "http://api.thingspeak.com/update" -- set server URL
count = 0 -- set initial count to 0
count
to keep track of the number of data posts.wifi.setmode(wifi.STATION) -- set Wi-Fi mode to station wifi.sta.config(station_cfg) -- set ssid&pwd to config wifi.sta.connect() -- connect to router
function PostToThingSpeak() -- callback function for posting data local string = "api_key=1EYZIS5OCRJSKZHG&field1="..count http.post(server, '', string, function(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) count = count + 1 -- increment count after each successful post end end) end
PostToThingSpeak()
to send data to ThingSpeak.count
variable.-- call post function every 20 seconds for ThingSpeak server update tmr.alarm(1, 20000, tmr.ALARM_AUTO, function() PostToThingSpeak() end)
PostToThingSpeak()
function every 20 seconds automatically.station_cfg = {} station_cfg.ssid = "ArunEworld" station_cfg.pwd = "8300026060BLR" wifi.sta.config(station_cfg) wifi.sta.connect(1) wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T) print("\n\tSTA - CONNECTED" .. "\n\tSSID: " .. T.SSID .. "\n\tBSSID: " .. T.BSSID .. "\n\tChannel: " .. T.channel) end) wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T) print("\n\tSTA - DISCONNECTED" .. "\n\tSSID: " .. T.SSID .. "\n\tBSSID: " .. T.BSSID .. "\n\treason: " .. T.reason) end) wifi.eventmon.register(wifi.eventmon.STA_AUTHMODE_CHANGE, function(T) print("\n\tSTA - AUTHMODE CHANGE" .. "\n\told_auth_mode: " .. T.old_auth_mode .. "\n\tnew_auth_mode: " .. T.new_auth_mode) end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T) print("\n\tSTA - GOT IP" .. "\n\tStation IP: " .. T.IP .. "\n\tSubnet mask: " .. T.netmask .. "\n\tGateway IP: " .. T.gateway) end) wifi.eventmon.register(wifi.eventmon.STA_DHCP_TIMEOUT, function() print("\n\tSTA - DHCP TIMEOUT") end) wifi.eventmon.register(wifi.eventmon.AP_STACONNECTED, function(T) print("\n\tAP - STATION CONNECTED" .. "\n\tMAC: " .. T.MAC .. "\n\tAID: " .. T.AID) end) wifi.eventmon.register(wifi.eventmon.AP_STADISCONNECTED, function(T) print("\n\tAP - STATION DISCONNECTED" .. "\n\tMAC: " .. T.MAC .. "\n\tAID: " .. T.AID) end) wifi.eventmon.register(wifi.eventmon.AP_PROBEREQRECVED, function(T) print("\n\tAP - PROBE REQUEST RECEIVED" .. "\n\tMAC: " .. T.MAC .. "\n\tRSSI: " .. T.RSSI) end) wifi.eventmon.register(wifi.eventmon.WIFI_MODE_CHANGED, function(T) print("\n\tSTA - WIFI MODE CHANGED" .. "\n\told_mode: " .. T.old_mode .. "\n\tnew_mode: " .. T.new_mode) end) local function D_Send() tmr.wdclr() http.post('https://aruneworld.com.com/post', 'Content-Type: text/plain\r\n', 'Hum=23&temp=24', function(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) end end) end local function pin1cb(level) D_Send() end gpio.trig(3, "down", pin1cb) -- GPIO 0 pin
This code sets up a NodeMCU or similar device to connect to a Wi-Fi network, monitor various Wi-Fi events, and perform an action when a specific GPIO pin state changes. Let’s break it down:
Overall, this script configures the Wi-Fi connection, sets up event handlers for various Wi-Fi events, defines a function to send data via HTTP POST, and sets up a GPIO pin to trigger an action when its state changes.
station_cfg={} station_cfg.ssid= "ArunEworld" station_cfg.pwd= "8300026060BLR" wifi.sta.config(station_cfg) wifi.sta.connect(1)
station_cfg
and then connects to the Wi-Fi network.wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T) print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\tChannel: "..T.channel) end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T) print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: ".. T.BSSID.."\n\treason: "..T.reason) end)
local function D_Send() tmr.wdclr() http.post('https://aruneworld.com.com/post', 'Content-Type: text/plain\r\n', 'Hum=23&temp=24', function(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) end end) end
D_Send()
to perform an HTTP POST request to a server when called. In this case, it posts humidity and temperature data.local function pin1cb(level) D_Send() end gpio.trig(3,"down", pin1cb) --gpio-0 pin
pin1cb
to be triggered when the GPIO pin 3 (GPIO 0) goes from high to low.gpio.trig()
to handle the GPIO interrupt.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”.
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); ?>
//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.Purpose | Example and use Case |
---|---|
Data Logging | Use Case: Collecting sensor data from IoT devices and sending it to a web server for logging. |
Example: Temperature and humidity readings from a sensor sent periodically to a server for historical tracking. | |
Remote Control | Use Case: Controlling devices remotely through a web interface. |
Example: Sending commands to turn on/off lights, appliances, or actuators. | |
Sensor Data Transmission | Use Case: Transmitting real-time sensor data to a central server. |
Example: Accelerometer data from a wearable device sent to a cloud server for analysis. | |
Form Submissions | Use Case: Submitting form data from a device to a web server. |
Example: User input from a device form (e.g., a weather station) sent to a server for processing. | |
User Authentication | Use Case: Authenticating users and transmitting login credentials securely. |
Example: Transmitting username and password securely to a server for authentication. | |
Integration with APIs | Use Case: Interacting with third-party APIs or services. |
Example: Sending data to a cloud service API for weather information or other integrations. | |
Alerts and Notifications | Use Case: Sending alerts or notifications from a device to a central server. |
Example: Sending an alert when a predefined threshold is exceeded (e.g., temperature too high). | |
Configuration Updates | Use Case: Updating device configurations remotely. |
Example: Sending configuration parameters to a device, allowing dynamic adjustments. | |
Data Synchronization | Use Case: Synchronizing data between devices and servers. |
Example: Uploading data collected offline on a device to a central server when connectivity is restored. | |
Command and Control Systems | Use Case: Building command and control systems for industrial or automation applications. |
Example: Controlling and monitoring devices in a manufacturing plant through a central server. |
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.
if you have the following Questions and most of the repeated and same-meaning questions, then the Above article should help you
Arduino-Core IDE Setup |
|
ESP8266 Interface LED |
ESP8266 Interface Button |
ESP8266 Interface ADC |
|
ESP8266 Project WebServer |
HTTP Post Data to Web Page |
Cayenne MyDevice Get Start |
ESP8266 Arduino-Core Sitemap |
ESP8266 Arduino-Core All Post |
You must be logged in to post a comment.