echo '' ;

Category Archives: ESP8266

ESP8266 Arduino-Core Interface – LED

LEDs have two legs, an anode (longer leg, positive) and a cathode (shorter leg, negative). Connect the anode to a current-limiting resistor and the other end of the resistor to the microcontroller’s output pin. Connect the cathode directly to the microcontroller’s ground (GND) pin. Interfacing an LED with an ESP8266 using the Arduino core is quite similar to the basic Arduino example. The ESP8266 Arduino core provides a convenient platform for programming ESP8266 modules with the Arduino IDE. Here’s a simple example of “interfacing an LED with an ESP8266 using an Arduino-core”ESP8266 Arduino-Core Interface – LED”:

Read more… →

ESP8266 NodeMCU Interface – DSB1820

Code

local ow_pin =   1 -- gpio-02
ds18b20.setup(ow_pin)

-- read all sensors and print all measurement results
ds18b20.read(
    function(ind,rom,res,temp,tdec,par)
        print(ind,string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",string.match(rom,"(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")),res,temp,tdec,par)
        print("Temp : "..temp)
    end,{});

 

ESP8266 Mongoose-OS Module – WiFi

Welcome to the ESP8266 Mongoose-OS Module on WiFi. In this module, we will explore how to configure and utilize WiFi connectivity on the ESP8266 microcontroller using Mongoose-OS firmware.

The ESP8266 is a powerful microcontroller with built-in WiFi capability, making it a popular choice for IoT (Internet of Things) projects. Mongoose-OS is an open-source firmware for microcontrollers that provides a development environment for building IoT applications.

Read more: ESP8266 Mongoose-OS Module – WiFi

In this module, we will cover topics such as configuring WiFi settings, connecting to WiFi networks, handling WiFi events, and utilizing WiFi functionalities in IoT applications. Whether you’re a beginner or an experienced developer, this module will provide you with the knowledge and skills to effectively use WiFi on the ESP8266 with Mongoose OS.

Let’s dive into the world of WiFi connectivity with the ESP8266 and Mongoose-OS!

Scan all available networks

Wifi.scan(function(results) {
    print(JSON.stringify(results));
});

Configure Access Point (Hotpots)

By default when flashing the firmware after ESP8266 WiFi configured as a AP mode in the WiFI AP SSID name of Mongoose_?????  here ????  is the chip id and password is Mongoose .

FAQ

  • How to Set ESP8266 to AP mode?
  • How to Set ESP8266 as Hotpots?

Steps to follow

  • Go to the Device files tab in a web browser using the mos tool. (IP address http://127.0.0.1:1992/#files )
  • Change the ap credential or set the credential in the conf0.json  file. (Refer Below Image)

Code Example

  • Enable AP Mode : “enable”: true, .
  • Disable AP Mode : “enable”: false, .
  • You can hide ESP8266 AP mode list using “hidden”: false,  (Not shown WiFi available list).
const wifiConfig = {
  wifi: {
    ap: {
      enable: true,
      ssid: "ArunEworld",
      pass: "info@aruneworld.com",
      hidden: false,
      channel: 6,
      max_connections: 10,
      ip: "192.168.4.1",
      netmask: "255.255.255.0",
      gw: "192.168.4.1",
      dhcp_start: "192.168.4.2",
      dhcp_end: "192.168.4.100",
      trigger_on_gpio: -1,
      disable_after: 0,
      hostname: "",
      keep_enabled: true
    }
  }
};

ESP8266 connects to WiFi Router

Here’s an example code snippet to connect an ESP8266 to a WiFi router using Mongoose OS:

load('api_config.js');     // Load the Mongoose OS configuration API
load('api_net.js');        // Load the Mongoose OS network API

// Configure WiFi settings
let ssid = 'YourWiFiSSID'; // Replace 'YourWiFiSSID' with your WiFi network SSID
let password = 'YourWiFiPassword'; // Replace 'YourWiFiPassword' with your WiFi network password

// Connect to WiFi
Net.connect({
  ssid: ssid,
  pass: password,
  auth: Net.AUTH_WPA2_PSK // Use WPA2 authentication (change if necessary)
});

// Event handler for WiFi connection status change
Net.setStatusEventHandler(function(ev, arg) {
  if (ev === Net.STATUS_DISCONNECTED) {
    print('WiFi disconnected');
  } else if (ev === Net.STATUS_CONNECTING) {
    print('WiFi connecting...');
  } else if (ev === Net.STATUS_CONNECTED) {
    print('WiFi connected');
  }
});

Replace 'YourWiFiSSID' with the SSID of your WiFi network and 'YourWiFiPassword' with the password of your WiFi network. This code will attempt to connect the ESP8266 to the specified WiFi network using the provided credentials. It also includes event handlers to print status messages when the WiFi connection status changes.

NEXT

MongooseOS
Mongoose-OS Interface
ESP8266 MongooseOS Interface LED
ESP8266 MongooseOS Interface Button
Mongoose OS Tutorials
ESP8266 MongooseOS Tutorials Web Server
Others
ESP8266 MongooseOS All Post

ESP8266 NodeMCU Module – HTTP


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 – HTTP

HTTP (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.

ESP8266 NodeMCU HTTP Module functions

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.

http.delete()

  • Executes a HTTP DELETE request. Note that concurrent requests are not supported.
  • Syntax : http.delete(url, headers, body, callback
  • Parameters
    • url The URL to fetch, including the http:// or https:// prefix
    • headers 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 empty
    • callback 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.
  • Returns : nil

HTTP Get Example

  • Read your thing-speak text file from the below code for ESP8266 NodeMCU Module HTTP.

Code

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)

Code Explanation

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
  • Here, a Lua table named 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
  • This line sets the URL of the server from which data will be fetched. It seems to be a text file containing data.
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
  • These lines configure the Wi-Fi module to operate in station mode, set the Wi-Fi station configuration to the values provided in 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)
  • These functions register event handlers for various Wi-Fi events like connection, disconnection, and obtaining an IP address. When any of these events occur, the code prints a message containing relevant information. Additionally, it starts or stops the timer depending on the event.
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
  • This function 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)
  • Finally, a timer is set up to call the GetFromArunEworld() function every 5 seconds to fetch data from the server.

HTTP Post Example

Post Data to thinkspeak website

Code

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)

Code Explanation

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
  • These lines define a Lua table 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
  • This line sets the URL of the ThingSpeak server where you’ll send the data.
count = 0 -- set initial count to 0
  • Initializes a variable 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
  • These lines configure the Wi-Fi module to work in station mode, set the Wi-Fi station configuration, and connect to the router using the provided SSID and password.
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
  • Defines a function PostToThingSpeak() to send data to ThingSpeak.
  • Constructs a string containing the API key and the current value of the count variable.
  • Sends an HTTP POST request to the ThingSpeak server with the constructed string.
  • Prints the response code and data received.
  • Increments the count after each successful post.
-- call post function every 20 seconds for ThingSpeak server update
tmr.alarm(1, 20000, tmr.ALARM_AUTO, function() PostToThingSpeak() end)
  • Sets up a timer to call the PostToThingSpeak() function every 20 seconds automatically.

Post Data to Aruneworld website

code

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

Code Explanation

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.

  1. Wi-Fi Configuration and Connection Setup:
   station_cfg={}
   station_cfg.ssid= "ArunEworld"
   station_cfg.pwd= "8300026060BLR"
   wifi.sta.config(station_cfg)
   wifi.sta.connect(1)
  • This section sets up the Wi-Fi station configuration with the SSID and password provided in station_cfg and then connects to the Wi-Fi network.
  1. 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)
  • It registers a callback function to handle the event when the device connects to a Wi-Fi network.
   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)
  • It registers a callback function to handle the event when the device disconnects from the Wi-Fi network. (Similar registration for other Wi-Fi events like authentication mode change, obtaining IP address, DHCP timeout, station/AP connection/disconnection, etc.)
  1. HTTP Post Functionality:
   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
  • Defines a function D_Send() to perform an HTTP POST request to a server when called. In this case, it posts humidity and temperature data.
  1. GPIO Pin Interrupt Setup:
   local function pin1cb(level)
       D_Send()
   end
   gpio.trig(3,"down", pin1cb) --gpio-0 pin
  • Defines a callback function pin1cb to be triggered when the GPIO pin 3 (GPIO 0) goes from high to low.
  • Registers this callback function with gpio.trig() to handle the GPIO interrupt.

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 Home Automation
Others
NodeMCU All Post
Sitemap

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 NodeMCU Module – GPIO

 

ESP8266 NodeMCU Devkit GPIO Pin Map

 

 

IO index ESP8266 pin IO index ESP8266 pin
0 [*] GPIO16 7 GPIO13
1 GPIO5 8 GPIO15
2 GPIO4 9 GPIO3
3 GPIO0 10 GPIO1
4 GPIO2 11 GPIO9
5 GPIO14 12 GPIO10
6 GPIO12

 

 


 ESP8266 NodeMCU Module GPIO Functions

gpio.mode() Initialize pin to GPIO mode, set the pin in/out direction, and optional internal weak pull-up.
gpio.read() Read digital GPIO pin value.
gpio.serout() Serialize output based on a sequence of delay-times in µs.
gpio.trig() Establish or clear a callback function to run on interrupt for a pin.
gpio.write() Set digital GPIO pin value.
gpio.pulse This covers a set of APIs that allow generation of pulse trains with accurate timing on
multiple pins.
gpio.pulse.build This builds the gpio.
gpio.pulse:start This starts the output operations.
gpio.pulse:getstate This returns the current state.
gpio.pulse:stop This stops the output operation at some future time.
gpio.pulse:cancel This stops the output operation immediately.
gpio.pulse:adjust This adds (or subtracts) time that will get used in the min / max delay case.
gpio.pulse:update This can change the contents of a particular step in the output program.

 

Note : [*] D0(GPIO16) can only be used as gpio read/write. No support for open-drain/interrupt/pwm/i2c/ow.


 

Pr-Request

 

GPIO pin set as input

  • if you have questions like How set GPIO pin as input in ESP8266? then refer the below contents

 

Required

  • ESP8266 Any module or NodeMCU Development Kit(Any Version)
  • ESPlorer
  • Wires (Optional)

Note : if your using ESP8266 module only you need to know basic connection diagram of ESP8266

 

Code

 

-- set pin index 1 to GPIO mode, and set the pin to high.
pin=3 --gpio-0
gpio.mode(pin, gpio.INPUT)
while true do
print("GPIO Read PIN Status : "..gpio.read(pin))
end

 


GPIO pin set as output

  • Set GPIO pin as output using gpio.mode()  function.
  • Example : gpio.mode(pin, gpio.INPUT)

 

Code

pin = 3
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin,HIGH)
--gpio.write(pin, LOW)

 

Result

 

 


GPIO pin status monitor

  • GPIO pin monitor status is very useful, because if you wanna monitor the pin status based on do the some process can easily.
  • Example : continuously monitor the gpio input button pin and based on button pin low/high level trun on/off the led.

 

Required

  • ESP8266 Any module or NodeMCU Development Kit(Any Version)
  • ESPlorer
  • Wires (Optional)

Note : if your using ESP8266 module only you need to know basic connection diagram of ESP8266.

 

Basic connection Diagram

Note : this below diagram for flash nodeMCU Firmware to ESP8266. We use the same circuit. But GPIO-0 Should be High or float Mode

 

Code

--www.aruneworld.com/embedded/esp8266/esp8266-nodecmu

button_pin=3 --GPIO-0
gpio.mode(button_pin, gpio.INPUT)

while true do
    print("GPIO Read PIN Status : "..gpio.read(button_pin))
    tmr.delay(1000000)
end

 

 


 

ESP8266 NodeMCU – Flash Firmware

NodeMCU Flasher tool is flashing the NodeMCU Firmware to ESP8266 Easily. This tool is developed by NodeMCU. Flashing firmware to an ESP8266-based NodeMCU board involves updating the firmware on the microcontroller to enable it to execute the desired code. Here’s a step-by-step guide on how to flash firmware to an ESP8266 NodeMCU using the ESP8266Flasher tool. Please note that you’ll need a USB-to-Serial converter or USB-based development board for this process.

Read more… →

ESP8266 NodeMCU – Build Firmware

The ESP8266 NodeMCU is a versatile and affordable microcontroller board that has gained immense popularity in the maker community due to its built-in Wi-Fi capabilities and low cost. One of the key advantages of the NodeMCU is its flexibility, allowing developers to customize and build firmware tailored to their specific project requirements.

Read more: ESP8266 NodeMCU – Build Firmware

In this guide, we will walk through the process of building firmware for the ESP8266 NodeMCU. Whether you’re a beginner looking to get started with microcontroller programming or an experienced developer aiming to create advanced IoT applications, this tutorial will provide you with the necessary steps to compile and upload firmware to your NodeMCU board.

We’ll cover essential topics such as setting up the development environment, configuring the firmware, compiling the code, and uploading it to the NodeMCU. By the end of this tutorial, you’ll have the skills and knowledge to harness the full potential of your ESP8266 NodeMCU board by creating custom firmware tailored to your project’s needs. Let’s dive in!

What is firmware?

  • Firmware is a piece of code for small type of device. The firmware contains binaries, that can do all the works and process.

If you have questions like the following, you can learn all of this question’s solutions here.

  1. What is NodeMCU Firmware?
  2. What is the format of NodeMCU Firmware?
  3. What contains the NodeMCU Fimware?
  4. Build Firmware
    1. How to build the NodeMCU Firmware for ESP8266?
    2. How to compile the NodeMCU Firmware for ESP8266?
    3. How to build the NodeMCU firmware from source?
    4. How Build NodeMCU firmware for ESP8266 in Linux Machine?
    5. How Build NodeMCU firmware for ESP8266 using web based Cloud?
    6. how to build NodeMCU firmware on your own?
  5. What are the ESP8266 modules are support this NodeMCU Firmware?
  6. Which ESP8266 modules is best for NodeMCU Firmware?

NodeMCU Firmware

  • NodeMCU firmware is contains many lua modules.
  • Lua modules are contains many lua library files and calling functions.
  • You can select based on your requirement in custom firmware build page.

In Linux


Web-based Cloud Build Custom NodeMCU Firmware

Beginner Recommended Method*

Step-1: Go to this site https://nodemcu-build.com/

Step-2: Two times enter your e-mail address (You will get a status about building the firmware)

Step 3: Select branch to build from (Recommended choose master always)

Step-4: Select modules to include( More than 40+ NodeMCU Lua Modules are available, Select depends upon your application development)

Step-5: Miscellaneous options (Recommended for beginner : Don’t select any option )

Step-6: Click the Start Your Build button

Step-7: Open your email ID (What you gave before)

Step 8: you will get an email about firmware building started and finished notification. In the finished Notification mail, you can download float and integer type NodeMCU .bin  firmware file.


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 Home Automation
Others
NodeMCU All Post
Sitemap

ESP8266 NodeMCU – How to know firmware information

If you have many custom NodeMCU firmware, but the firmware name does not contain the details of info about what the NodeMCU module libraries are present. This article explains ESP8266 NodeMCU – How to know firmware information?, if ESPlorer works fine means ESP8266 returns the firmware details, some times ESPlorer IDE does not auto-detect the firmware details. so you should note that your custom NodeMCU firmware details yourself. This post will help to firmware details list easily by using small code.

The NodeMCU firmware is designed to work with the Lua scripting language. Lua is a lightweight and powerful scripting language that is well-suited for embedded systems.

The firmware is often used in conjunction with the NodeMCU development kit, which includes the ESP8266 WiFi module and a USB-to-Serial converter. The kit simplifies the development process and makes it easy to upload Lua scripts to the ESP8266

Read more… →

ESP8266 NodeMCU – IDE

Three Different IDE’s are available from NodeMCU ESP8266 Platform

  • ESPlorer
  • Lua Loader
  • ESP8266 Web File Manager
  • ESP-IDF

This ESP8266 NodeMCU IDE tutorial Only discussed ESPlorer, You can use this ESPlorer tool as a UART Terminal Application. You can send and receive the data in terminal windows like Putty, DockLight

Read more… →

ESP8266 – Getting Started

ESP8266 is a powerful microcontroller with built-in WiFi. Whether you’re a beginner or an expert, this is the right place to enhance your knowledge about ESP8266 and its applications. Nowadays, ESP8266 is highly renowned for its versatility and is utilized in numerous applications such as home automation, smart plugs and lights, mesh networks, industrial wireless control, baby monitors, IP cameras, sensor networks, wearable electronics, WiFi location-aware devices, security ID tags, and WiFi position system beacons. It is a popular chip in the Internet of Things world. Before diving into learning about ESP8266, it’s essential to understand the manufacturer, Espressif.”

Read more… →

ESP8266 – FAQ

Here are some (frequently asked questions) FAQ about ESP8266. These FAQs cover some of the common questions about ESP8266, but if you have any specific questions or need more information, feel free to Refer to All ESP8266 Sections! (ESP8266 FAQ)

Read more: ESP8266 – FAQ

What is ESP8266?

  • Espressif Systems developed ESP8266, a low-cost Wi-Fi microchip, making it widely utilized in IoT (Internet of Things) projects due to its affordability and versatility.

Key features of ESP8266?

  • Key features of ESP8266 include Wi-Fi connectivity, low power consumption, GPIO pins for interfacing with external devices, and support for various programming languages like Arduino, Lua, and MicroPython.

What programming languages can I use with ESP8266?

  • ESP8266 can be programmed using languages like Arduino (C/C++), Lua, and MicroPython. Each language has its advantages and is suitable for different types of projects and developers.

How do I program ESP8266?

  • ESP8266 can be programmed using the Arduino IDE with the help of the ESP8266 board package, or using other development environments like PlatformIO. Additionally, Lua and MicroPython can be used for programming ESP8266 devices.

What are some common applications of ESP8266?

  • Common applications of ESP8266 include IoT devices such as smart home systems, environmental monitoring devices, Wi-Fi controlled appliances, weather stations, and more.

Can ESP8266 act as a web server?

  • Yes, ESP8266 can act as a web server, allowing it to serve web pages, handle HTTP requests, and communicate with web clients over Wi-Fi.

Is ESP8266 suitable for battery-powered applications?

  • While ESP8266 offers low power modes and can be used in battery-powered applications, its power consumption may not be as low as other microcontrollers specifically designed for low power consumption.

Can ESP8266 communicate with other microcontrollers or devices?

  • Yes, ESP8266 can communicate with other microcontrollers and devices using various communication protocols like SPI, I2C, UART, and MQTT over Wi-Fi.

FAQ: What is NodeMCU?

  • NodeMCU is a firmware platform for ESP8266-based devices, providing a Lua-based scripting language for easy development of IoT applications.

Where can I find documentation and resources for ESP8266?

  • Documentation, tutorials, and resources for ESP8266 are available on the official Espressif website, community forums, GitHub repositories, and various online tutorials and blogs.

FAQ: Where to Buy ESP8266 Modules?

Before buying an ESP8266 module, it’s important to know the different kinds of modules available and their features. You can find detailed information about this in the post linked here. By reading that post, you’ll get an idea of which ESP8266 module is suitable for your requirements. If you’re a beginner, I recommend buying the NodeMCU Dev Board. Nowadays, everything is available online, so there’s no need to worry about purchasing anything. If you order online, you’ll receive your item within a few days. The best place to buy an ESP8266 is on eBay because many sellers are offering different prices ranging from low to high. You can also try other platforms like Amazon and AliExpress. Click the links below to buy an

ESP8266 online:


What is the main difference b/w nodemcu and ESP-WROOM-02?

  • Nodemcu
    • NodeMCU is a lua based open source platform for ESP8266.
    • nodemcu dev kits it’s a development kit of NodeMCU
  • ESP8266 Wroom-02
    • ESPressif is the maker and manufacturer of ESP8266 chips.
    • ESP8266 WROOM-02 is development board of Espressif.

Coding wise any deference is there between ESP-Wroom-02 and NdeMCU?

  • Answer is no.
  • Because hardware components may vary from different kind of ESP8266 boards like antenna design, PCB design, PCB board Layer size, Flash memory GPIO pin extensions and Board size.
  • You first choose your programming platform (NodeMCU, Arduino, Direct C, Mongoose OS, MicroPhython, ESP8266 Basic). ESP8266 Supports many different programming language like C, C++, Lua, JavaScript, Python and many more.

Next Topic

ESP8266 FAQ

ESP8266 Get Start
ESP8266 Various Boards
ESP8266 Programming Methods
ESP8266 Various Programmer
ESP8266 Build&Flash Firmware
ESP8266 Resource
ESP8266 FQA
ESP8266 MQTT broker BONDAR.
ESP8266 Platforms
ESP8266 Arduino-Core
ESP8266 AT-Commands
ESP8266 Mongoose OS
ESP8266 NodeMCU
Others
ESP8266 Sitemap
ESP8266 All post

ESP8266 MQTT broker BONDAR

The ESP8266 can indeed be programmed to act as an MQTT broker, allowing it to handle messaging between different devices in a network using the MQTT protocol. Will Discuss “ESP8266 MQTT broker BONDAR”.

Get Start of ESP8266 MQTT broker BONDAR

Create an account

  • Create an account in here
  • Activate your iotcentral account

Download Bin FIle

Flash the Bondar Firmware

  • your ESP8266 starting from address 0x0. (Use esptool.py or ESP Flash Download Tool)
  • For Linus
    • sudo esptool.py -p /dev/ttyUSB0 –baud 9600 write_flash -fs 32m-c1 -fm dio -ff 40m 0x00000 bondar.bin

ESP8266 Configuration

  • ESP8266 will start as Access Point mode. and named as Bondar_XXXXXXXXX  . (Ex refer Below image : Bondar_2e3ae80cb19a ) and should use default password 12345678
  • Now connect that AP Network (Bondar_2e3ae80cb19a ) with your laptop or mobile.
  • Go to 192.168.4.1 in your browser and you will get a configuration page. Then enter your wifi Credential and your he user and password used on IoTCentral.eu
  • Reset the ESP8266 by Click button and also unplug and re-plug the power cable (I recommend you to unplug and then plug the power cable).
  • After Rest you can see when did soft web browser reset button

IoTCentral.eu Account Details

  • Login to your home page on IoTCentral.eu
  • You will see your allocated topic
  • Use allocated_topic/your_topics to connect to iotcentral.eu:1883 and /allocated_topic/your_topic to connect from your Wi-Fi network.

Note :   Always use your email address and the password used on IoTCentral.eu to publish and subscribe. In this way your data is protected and no one will get access to your data since the topic is secret and you are using your username and password to publish and subscribe to the cloud.


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 Interface – ADXL345

The ESP8266 NodeMCU is a popular development board based on the ESP8266 microcontroller, which offers built-in Wi-Fi capabilities, making it ideal for Internet of Things (IoT) projects. In this project, we’ll explore how to interface the ESP8266 NodeMCU with the ADXL345 accelerometer sensor.

Read more: ESP8266 NodeMCU Interface – ADXL345

ADXL345

The ADXL345 is a small, thin, ultralow power, 3-axis accelerometer with high resolution (13-bit) measurement at up to ±16 g. It’s suitable for various applications, including tilt sensing, motion detection, and vibration monitoring.

By combining the ESP8266 NodeMCU with the ADXL345 sensor, we can create IoT applications that can monitor and analyze motion or vibrations remotely over Wi-Fi. This interface allows us to gather data from the accelerometer sensor and transmit it to a server, cloud platform, or display it on a web page.

Throughout this project, we’ll cover the hardware setup, including connecting the ADXL345 sensor to the ESP8266 NodeMCU, and the software implementation, which involves programming the ESP8266 NodeMCU to communicate with the ADXL345 sensor and transmit the data. With this interface, you’ll be able to leverage the power of the ESP8266 NodeMCU and the capabilities of the ADXL345 sensor to create versatile IoT applications for motion sensing and monitoring.

Code

Make sure you have the necessary libraries and setup to run this code on your hardware.

-- www.ArunEworld.com 
sda = 2 -- GPIO-4 
scl = 1 -- GPIO-5 

print("ArunEworld")

-- Initialize the ADXL345 sensor
adxl345.init(sda, scl)

-- Delay for 3000000 microseconds (3 seconds)
tmr.delay(3000000)

-- Read data from the ADXL345 sensor
print(adxl345.read())

-- Define a function to read accelerometer data
function ADXL_read() 
    -- Read accelerometer data
    local x, y, z = adxl345.read() 
    -- Print accelerometer data
    print("X-axis:", x)
    print("Y-axis:", y)
    print("Z-axis:", z)
    -- Alternatively, you can print all axes at once using the following line:
    -- print(string.format("X = %d, Y = %d, Z = %d", x, y, z))
end 

-- Set up a timer to call the ADXL_read function every 1000 milliseconds (1 second)
tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)

Code Explanation

LineCodeExplanation
1sda = 2Assigns pin 2 to the variable sda, representing the Serial Data (SDA) pin.
2scl = 1Assigns pin 1 to the variable scl, representing the Serial Clock (SCL) pin.
4print("ArunEworld")Prints the message “ArunEworld” to the console.
7adxl345.init(sda, scl)Initializes the ADXL345 sensor with the SDA and SCL pins defined earlier.
10tmr.delay(3000000)Delays the execution of the program for 3 seconds (3000000 microseconds).
13print(adxl345.read())Reads data from the ADXL345 sensor and prints it to the console.
16function ADXL_read() ... endDefines a function named ADXL_read to read accelerometer data from the ADXL345 sensor.
19tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)Sets up a timer to call the ADXL_read function every 1000 milliseconds (1 second) repeatedly.

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 Home Automation
Others
NodeMCU All Post
Sitemap

ESP8266 NodeMCU Module – NET

The “ESP8266 NodeMCU Module NET” introduces a comprehensive set of functionalities for network communication on the ESP8266 platform using the NodeMCU firmware. This module empowers developers to create versatile IoT applications by enabling connections over Wi-Fi, TCP/IP, and UDP protocols.

Read more: ESP8266 NodeMCU Module – NET

With the NET module, developers can perform various networking tasks such as creating clients and servers, establishing UDP sockets, managing multicast groups, and interacting with DNS servers. This module provides a wide range of functions for initiating, managing, and terminating network connections, as well as for resolving hostnames and configuring DNS servers.

Whether it’s setting up a web server, connecting to cloud services, or implementing peer-to-peer communication, the ESP8266 NodeMCU Module NET offers the necessary tools and capabilities to facilitate seamless networking operations. It serves as a foundational component for building connected devices and IoT solutions powered by the ESP8266 platform.

NET Module Functions for ESP8266 NodeMCU

ConstantDescription
net.createConnection()Creates a client.
net.createServer()Creates a server.
net.createUDPSocket()Creates a UDP socket.
net.multicastJoin()Join multicast group.
net.multicastLeave()Leave multicast group.
net.server:close()Closes the server.
net.server:listen()Listen on port from IP address.
net.server:getaddr()Returns server local address/port.
net.socket:close()Closes socket.
net.socket:connect()Connect to a remote server.
net.socket:dns()Provides DNS resolution for a hostname.
net.socket:getpeer()Retrieve port and IP of remote peer.
net.socket:getaddr()Retrieve local port and IP of socket.
net.socket:hold()Throttle data reception by placing a request to block the TCP receive function.
net.socket:on()Register callback functions for specific events.
net.socket:send()Sends data to remote peer.
net.socket:ttl()Changes or retrieves Time-To-Live value on socket.
net.socket:unhold()Unblock TCP receiving data by revocation of a preceding hold().
net.udpsocket:close()Closes UDP socket.
net.udpsocket:listen()Listen on port from IP address.
net.udpsocket:on()Register callback functions for specific events.
net.udpsocket:send()Sends data to specific remote peer.
net.udpsocket:dns()Provides DNS resolution for a hostname.
net.udpsocket:getaddr()Retrieve local port and IP of socket.
net.udpsocket:ttl()Changes or retrieves Time-To-Live value on socket.
net.dns.getdnsserver()Gets the IP address of the DNS server used to resolve hostnames.
net.dns.resolve()Resolve a hostname to an IP address.
net.dns.setdnsserver()Sets the IP of the DNS server used to resolve hostnames.

Example :1 TCP Connection in local

The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends a message to the server. It also includes event handlers to handle Wi-Fi connection events.

  • Create a TCP connection and communicate with TCP server
  • Set IP of Server

Code

-- www.ArunEworld.com
print("ArunEworld : TCP Example")

-- Connect to Access Point (DO NOT save config to flash)
wifi.setmode(wifi.STATIONAP)

station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()

function TCP_CONNECTION_func()
    TCP_Conn = net.createConnection(net.TCP, 0)
    TCP_Conn:connect(80, '192.168.1.102') -- Change your server IP

    TCP_Conn:on("connection", function(TCP_Conn, payload)
        print("Connection_func : ")
        print(payload)
    end)

    TCP_Conn:on("receive", function(TCP_Conn, payload)
        print("Received : " .. payload)
    end)

    TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")
end

-- Wifi 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)
    TCP_Conn = nil
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)
    TCP_CONNECTION_func()
end)

Code Explanation

Certainly! Here’s an explanation of the provided Lua code:

  1. Print Statement:
   print("ArunEworld : TCP Example")

This line prints out the string "ArunEworld : TCP Example". It serves as an informational message indicating the purpose of the code.

  1. Wi-Fi Configuration:
   wifi.setmode(wifi.STATIONAP)

This line sets the Wi-Fi mode to STATIONAP, allowing the device to connect to an existing Wi-Fi network as a station while also creating an access point.

   station_cfg = {}
   station_cfg.ssid = "ArunEworld"
   station_cfg.pwd = "ArunEworld.com"
   wifi.sta.config(station_cfg)
   wifi.sta.connect()

These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.

  1. TCP Connection Setup:
   function TCP_CONNECTION_func()
       TCP_Conn = net.createConnection(net.TCP, 0)
       TCP_Conn:connect(80, '192.168.1.102') -- Change your server IP
   end

This function sets up a TCP connection to the specified server IP address (192.168.1.102) on port 80.

  1. TCP Event Handlers:
   TCP_Conn:on("connection", function(TCP_Conn, payload)
       print("Connection_func : ")
       print(payload)
   end)

This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which prints out the connection payload.

   TCP_Conn:on("receive", function(TCP_Conn, payload)
       print("Received : " .. payload)
   end)

This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.

  1. Sending Data:
   TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")

This line sends a message to the TCP server after the connection is established.

  1. Wi-Fi Event Monitoring:
   wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
       -- Event handler for when the Wi-Fi station is connected
       -- Print out details about the connection
   end)

   -- Similar event handlers are registered for other Wi-Fi events like disconnection and obtaining an IP address.

Example :1 TCP Connection to httpbin.org  site (Onlin)

print("ww.ArunEworld.com")
print("wifi init")

--wifi.start() -- commented out

wifi.setmode(wifi.STATIONAP) -- connect to Access Point (DO NOT save config to flash)

station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()

srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c)
    print(c)
end)

-- Wait for connection before sending.
srv:on("connection", function(sck, c)
    -- 'Connection: close' rather than 'Connection: keep-alive' to have server
    -- initiate a close of the connection after final response (frees memory
    -- earlier here), https://tools.ietf.org/html/rfc7230#section-6.6
    sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
end)

srv:connect(80, 'httpbin.org')

Explanation

The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends an HTTP GET request to retrieve data from httpbin.org. Any received data is printed to the console.

  1. Print Statements:
   print("ww.ArunEworld.com")
   print("wifi init")

These lines print out the strings "ww.ArunEworld.com" and "wifi init". They are for informational purposes and help indicate the progress of the program.

  1. Wi-Fi Configuration:
   wifi.setmode(wifi.STATIONAP)

This line sets the Wi-Fi mode to STATIONAP, which allows the device to connect to an existing Wi-Fi network as a station while also creating an access point.

   station_cfg = {}
   station_cfg.ssid = "ArunEworld"
   station_cfg.pwd = "ArunEworld.com"
   wifi.sta.config(station_cfg)
   wifi.sta.connect()

These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.

  1. TCP Connection Setup:
   srv = net.createConnection(net.TCP, 0)

This line creates a TCP connection object named srv.

   srv:on("receive", function(sck, c)
       print(c)
   end)

This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.

   srv:on("connection", function(sck, c)
       sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
   end)

This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which sends an HTTP GET request to httpbin.org. The request includes the path /get and necessary headers.

  1. Connect to Server:
   srv:connect(80, 'httpbin.org')

This line initiates the connection to the server at httpbin.org on port 80 (the standard HTTP port).


See also


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 Home Automation
Others
NodeMCU All Post
Sitemap

ESP8266 NodeMCU Module – Timer

In Lua on the ESP8266 NodeMCU module, you can use the tmr module to work with a timer. Here’s a basic guide on using the ESP8266 NodeMCU Module – Timer. The tmr Module provides 7 (0-6) static timer functions of the timer module. we can’t use more than 7. Also, you can create an object-based timer function with a custom name.

we can use this timer function in the following applications

  • To blink an LED for a certain time duration its like a repeated process.
  • To monitor the WiFi Status of ESP8266 IP address.
Read more… →