echo '' ;

Archives

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

ADC

ESP8266 with  ADC Interface

                    This the simple example of ADC with ESP8266. ESP8266 have a in-build ACD unit with 10 bit resolution(10bits-0 to 1024 steps), so no need to add a external ADC converter ICs. if your beginner try this below codes and understand the ADC with ESP8266. I used Ai-thinger’s ESP-12F module(not used NodeMCU Dev Board) wit USB to UART Programmer and NodeMCU firmware. but you can also use any other firmware like Arduino code, Man-goose OS to do this. In this experiment used 3 NodeMCU module libraries are UART (for printing), Timer(for looping), and ADC Module. So your NodeMCU firmware should have this modules. NodeMCU only support only one ACD pin. ADC bin converts voltage from 0 to 3.3 according to 0- 1024 values(10bit resolution)

  •  Required Hardware Components :  2x USB to UART converter programmer, 1x ESP8266 Module(Used Ai-Thinker’s ESP-12F module), 1x Variable resistor  (Pot-10k)
  • Required software tools : ESPlorer IDE Tool,

Note : if you use NodeMCU Dev board don’t need ESP8266 Ai-Thinkers Module and UART Programmer. Because NodeMCU Dev Board have already Programmer.

Circuit Diagram

 

Code

  • EX  :tmr.alarm(0,500,1, function printf(adc.read(0)) end)
  • tmr.alarm function is like a loop for 500microseconds, So every microseconds once that ESP read the ADC value from that pin
  • print function is the same as uart.write(0, adc.read(0).."\n") the value to terminal window
  • adc.read  read the ADC value.

Results

 



 

ESP8266 NodeMCU Interface – DHT11

Now a days measuring temperature and humidity is not a difficult job. Because lot of sensor are available in the market. DHT11 and DHT22 are very familiar from others. DHT11 Module is very low cast and available in market long days. In this tutorial you will learn how to  interface DHT11 with ESP8266 module using NodeMCU Firmware. In this project I’m used  Espressif’s ESP8266X of Ai-thinger’s ESP-12F module with  Aosong DHT11 module using NodeMCU DHT Module in windows system. You can also use any other ESP8266 Modules for this project.

Read more… →

ESP8266 NodeMCU Module – File

 


File Modes

  •    – read mode (the default)
  • w   – write mode
  • a    – append mode
  • r+  – update mode, all previous data is preserved
  • w+– update mode, all previous data is erased
  • a+ – append update mode, previous data is preserved, writing is only allowed at the end of file

File Functions

  • file.open()  – Open a file (Create a new file when write mode)
    • file.open(filename, mode)
      • Eg : file.open(“New_File”, “r”)
      • returns nil if file not open, else file opened returns true
  • file.remove() – Remove a file.
    • file.remove(filename)
      • Eg: file.remove(“New_File”)
      • return nil (nothing)
  • file.rename() – Rename the file.
    • file.rename(oldname, newname)
      • Eg: file.rename(“Old_File”, “New_File”)
      • return true if success, false if error.

Create a New file

  • file.open(“File_Name”, “Mode”) 

File – Hello world Program

file.open("hello/world.txt", "w")
file.writeline("Hello World!")                                                
file.close()

 


Next :

Previous :


 

ESP8266 NodeMCU Interface – 7 Segment Display

In this “ESP8266 NodeMCU Interface 7 Segment Display” project, we’re interfacing using an MCP23017 GPIO expander. The MCP23017 expands GPIO capabilities, allowing us to control the display efficiently. This setup enables us to display numeric digits on the 7-segment display through the NodeMCU board.

The NodeMCU is programmed using Lua scripting language, leveraging the I²C communication protocol to communicate with the MCP23017. We utilize the GPIO pins of the MCP23017 to control the segments of the 7-segment display, achieving the desired numerical output.

This interface offers a versatile platform for displaying numeric data in various projects, such as digital clocks, temperature monitors, or any application requiring numerical output. With the flexibility and power of the ESP8266 NodeMCU and the MCP23017 GPIO expander, this interface provides a robust solution for integrating 7-segment displays into IoT and embedded systems projects.

Required

  • NodeMCU Modules (Firmware) :  Bit Module, GPIO Module, I2C Module, Timer Module,
  • hardware :  ESP8266 with Programmer (or)  NodeMCU Dev Kit, 7-Segment Display,
  • software tools : ESPlorer IDE Tool.

Code

This script initializes the necessary constants, sets up functions for reading from and writing to the MCP23017, initializes the MCP23017, and then starts a loop to blink the 7-segment display. Make sure you have the appropriate libraries and hardware connections set up. ESP8266 NodeMCU Interface 7 Segment Display

-- https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_nodemcu/
-- Tested By: Arun(20170219)
-- Example Name: AEW_7-Segment Display_MCP23017.lua
------------------------------------------------------------------------------------------
-- i2c setup
local id = 0 -- always 0
local pinSDA = 2 -- 1~12, IO index 
local pinSCL = 1 -- 1~12, IO index
local speed = i2c.SLOW -- only i2c.SLOW supported

-- CONSTANTS
local MCP23017_ADDRESS = 0x21 -- you can change this id, I used 0x21
local Numbers = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}

-- MCP23017 registers (everything except direction defaults to 0)
local IODIRA = 0x00 -- I/O DIRECTION REGISTER (0 = output, 1 = input (Default))
local IODIRB = 0x01
local IPOLA = 0x02 -- INPUT POLARITY REGISTER (0 = normal, 1 = inverse)
local IPOLB = 0x03
local GPINTENA = 0x04 -- INTERRUPT-ON-CHANGE PINS
local GPINTENB = 0x05
local DEFVALA = 0x06 -- Default comparison for interrupt on change (interrupts on opposite)
local DEFVALB = 0x07
local INTCONA = 0x08 -- Interrupt control (0 = interrupt on change from previous, 1 = interrupt on change from DEFVAL)
local INTCONB = 0x09
local IOCON = 0x0A -- IO Configuration: bank/mirror/seqop/disslw/haen/odr/intpol/notimp
--IOCON = 0x0B -- same as = 0x0A
local GPPUA = 0x0C -- GPIO PULL-UP RESISTOR REGISTER (0 = disabled, 1 = enabled)
local GPPUB = 0x0D
local INFTFA = 0x0E -- Interrupt flag (read only) : (0 = no interrupt, 1 = pin caused interrupt)
local INFTFB = 0x0F
local INTCAPA = 0x10 -- Interrupt capture (read only) : value of GPIO at time of last interrupt
local INTCAPB = 0x11
local GPIOA = 0x12 -- Port value. Write to change, read to obtain value
local GPIOB = 0x13
local OLLATA = 0x14 -- Output latch. Write to latch output.
local OLLATB = 0x15
local chip1 = 0x20 -- MCP23017 is on I2C address = 0x20
local chip2 = 0x21 -- MCP23017 is on I2C address = 0x21

-- user-defined function: read from reg_addr content of dev_addr --write MCP23017 start
function read_reg(MCP23017_ADDRESS, reg_addr)
    i2c.start(id)
    i2c.address(id, MCP23017_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, reg_addr)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, MCP23017_ADDRESS, i2c.RECEIVER)
    local c = string.byte(i2c.read(id, 1))
    i2c.stop(id)
    return c
end --read MCP23017 end

--write MCP23017 start
function write_reg(MCP23017_ADDRESS, reg_addr, reg_val)
    i2c.start(id)
    i2c.address(id, MCP23017_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, reg_addr)
    i2c.write(id, reg_val)
    i2c.stop(id)
end --write MCP23017 end

--MCP Initialize start
function init(MCP23017_ADDRESS)
    write_reg(MCP23017_ADDRESS, IOCON, 0x60) -- BANK=0, MIRROR=1, SEQOP=1, DISSLW=0, HAEN=0, ODR=0, INTPO=0, bit0=nil
    write_reg(MCP23017_ADDRESS, IODIRA, 0x00) -- Port A as Output
    write_reg(MCP23017_ADDRESS, GPIOA, 0xFF) -- Set All port A pins High
end --MCP Initialize end

-----------Main Program start------------------

i2c_speed = i2c.setup(id, pinSDA, pinSCL, speed) -- Initialize the I²C module. 
print("i2c_Speed : "..i2c_speed)
if i2c_speed ~= nil then
    print("i2c Speed : "..i2c_speed)
    print("i2c init done") 
else 
    print("i2c init not done!!")
end

--init MCP23017
init(MCP23017_ADDRESS)

--Blink 7segment Display
write_reg(0x21, GPIOA, 0xFF)
tmr.delay(100000)
write_reg(0x21, GPIOA, 0x00)
print("7-Segment is Ready")

--Loop
function Display()
    for Num = 1, 12 do
        print(Numbers[Num])
        if 11 == Num then
            Display()
        else
            write_reg(0x21, GPIOA, Numbers[Num])
        end
        tmr.delay(1000000)
    end
end

tmr.alarm(0, 1000, 0, Display)

Code Explanation

Line(s)Explanation
1-9Header comments providing information about the code, including its source, author, and example name.
11-14Declaration of variables for configuring the I²C communication, including the I²C ID, SDA pin, SCL pin, and speed.
17-33Definition of constant values, including the address of the MCP23017, and an array of numbers for the 7-segment display.
36-60Definition of MCP23017 register addresses and their corresponding functions. These functions handle reading from and writing to the MCP23017 registers.
63-72Function to initialize the MCP23017. It sets the IO configuration and configures Port A as an output with all pins set to high.
75-89Main program logic, including the initialization of the I²C module, printing the I²C speed, and handling initialization of the MCP23017.
92-100Blinking of the 7-segment display. It sets all pins of Port A to high, delays, then sets them to low.
103-116Loop function Display() to display the numbers on the 7-segment display. It iterates through the Numbers array, setting the appropriate value on Port A, and then delays.
118Setting up a timer to call the Display() function every second.

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

Whan captures button presses and counts the number of pulses generated by these presses. Below is an explanation of the code “ESP8266 266 NodeMCU Interface Button”.

The button interface is a fundamental component in electronics and user interfaces, offering users a simple yet effective way to interact with devices.It consists of a push mechanism and contacts, completing an electrical circuit when pressed to trigger predefined tasks. Additionally, buttons are essential components in electronic devices, facilitating user input and control. Various types of buttons exist, including momentary buttons, toggle switches, and membrane buttons, each tailored to specific applications.

Consumer electronics, industrial control panels, automotive interfaces, and medical devices widely utilize buttons. Design considerations such as size, shape, color, and placement are crucial for usability. Incorporating debounce circuitry is also essential to eliminate bouncing effects. While buttons provide intuitive interaction and are cost-effective, they have limitations such as limited input options and potential wear over time. Additionally, designing interfaces with multiple buttons can pose challenges regarding space constraints and user ergonomics.

Uses – Button

Uses of Button InterfaceExample
1. Input SensingDetecting button presses for menu navigation
2. User InteractionInitiating actions such as turning on/off devices
3. Control MechanismControlling the speed of a motor based on button input
4. Event TriggeringTriggering alarms or notifications
5. User FeedbackProviding feedback through LED indicators
6. Configuration SettingsAdjusting settings in a user interface

Advantage and Disadvantage

AdvantagesDisadvantages
Simple and intuitive user interactionLimited input options compared to touchscreens
Cost-effective and easy to implementPhysical wear and tear over time
Tactile feedback provides confirmationLimited functionality for complex interactions
Suitable for applications requiring precise inputLimited space for multiple buttons on small devices
Works reliably in various environmentsMay require debouncing to prevent false triggers

Importance of Buttons

ESP8266 NodeMCU Interface Button .Buttons are essential components in various electronic systems and interfaces for several reasons:

Importance of ButtonsDescription
User InteractionButtons facilitate direct user interaction with electronic devices, enabling input commands.
ControlThey provide users with control over device functions and operations, enhancing usability.
FeedbackButtons offer tactile feedback upon pressing, confirming the user’s action.
VersatilityButtons can be integrated into various devices and interfaces, offering versatile functionality.
ReliabilityThey are known for their durability and consistent performance, ensuring reliable operation.
Cost-EffectivenessButtons are cost-effective components, making them widely used in different applications.

Overall, buttons play a crucial role in enabling user interaction and control in electronic systems, thereby making them indispensable in many applications across industries.

Types of buttons

Button TypesDescription
Push ButtonTypically a simple momentary switch that closes a circuit when pressed and opens it when released.
Tactile ButtonFeatures a small, tactile protrusion on the surface, providing physical feedback upon pressing.
Toggle SwitchA mechanical switch with a lever or toggle that can be flipped or moved to open or close a circuit.
Rocker SwitchSimilar to a toggle switch but with a flat, paddle-like actuator that rocks back and forth to toggle.
Slide SwitchUtilizes a sliding mechanism to open or close the circuit, often used for simple on/off operations.
Capacitive Touch ButtonOperates through touch-sensitive materials, activated by the presence of a conductive object or a finger.
Membrane ButtonConsists of a flexible membrane with conductive traces, pressed to make contact with underlying circuits.

These button types offer various tactile and operational characteristics suitable for different applications.

Button Interrupt Counter

The Button Interrupt Counter script counts the number of button presses (pulses) detected on a specific GPIO pin (in this case, GPIO2 or GPIO9).

Required

  • NodeMCU Modules (Firmware): GPIO Module, Timer Module,
  • hardware: ESP8266 with Programmer (or)  NodeMCU Dev Kit, Button,
  • software tools: ESPlorer IDE Tool.

Code

The script tallies button presses (pulses) detected on GPIO2, which corresponds to GPIO9. It incorporates debouncing to prevent counting multiple pulses for a single press.

-- Source URLs and Testing Information
-- http://esp8266iot.blogspot.in/
-- http://aruneworld.blogspot.com/
-- Tested By: Arun(20170219)
-- Example Name: AEW_ButtonInterruptCounter.lua
------------------------------------------------------------------------------------------

-- Count pulses on GPIO2
count = 0
delay = 0

-- Configure GPIO9 (equivalent to GPIO2) for interrupt mode with pull-up enabled
gpio.mode(9, gpio.INT, gpio.PULLUP)

-- Interrupt handler function
function counter(level)
    local x = tmr.now() -- Get current time in microseconds
    if x > delay then
        delay = tmr.now() + 250000 -- Update delay to allow for the next pulse after 250 milliseconds
        count = count + 1 -- Increment pulse count
        print(count) -- Print the current count value
    end
end

-- Set up interrupt trigger on GPIO9 for falling edge detection
gpio.trig(9, "down", counter)

Code Explanation

Source URLs and Testing Information:

  • Two URLs are provided as the source of the code: http://esp8266iot.blogspot.in/ and http://aruneworld.blogspot.com/.
  • The code was tested by Arun on a specific date mentioned as 20170219.
  • The example is named AEW_ButtonInterruptCounter.lua.

Initial Variables Setup:

  • count: Initialized to 0, it will be used to count the pulses detected on GPIO2.
  • delay: Initialized to 0, it will be used to debounce the input and avoid counting multiple pulses for a single press.
  • gpio.mode(9, gpio.INT, gpio.PULLUP): Configures GPIO9 for interrupt mode with pull-up enabled.

Interrupt Handler Function (counter):

  • tmr.now(): Retrieves the current time in microseconds.
  • If the current time is greater than the delay value, it means that enough time has passed since the last pulse.
  • In such a case, the delay is updated to allow for the next pulse after a debounce period of 250 milliseconds.
  • The count variable is incremented to keep track of the number of pulses detected.

Setting up Interrupt Trigger:

  • gpio.trig(9, "down", counter): Sets up an interrupt trigger on GPIO9 for falling edge detection. When a falling edge (button press) is detected on GPIO9, the counter function is called.


Interrupt Example of ESP8266 NodeMCU Interface – Button

Code

do
    -- use pin 1 as the input pulse width counter
    local pin, pulse1, du, now, trig = 1, 0, 0, tmr.now, gpio.trig
    gpio.mode(pin, gpio.INT)

    local function pin1cb(level, pulse2)
        print(level, pulse2 - pulse1)
        pulse1 = pulse2
        trig(pin, level == gpio.HIGH and "down" or "up")
    end

    trig(pin, "down", pin1cb)
end

Code Explanation

This code segment configures GPIO pin 1 of the NodeMCU board as an input for pulse width counting. Here’s a breakdown of what it does:

Overall, this code enables GPIO pin 1 to monitor pulse width changes and execute the callback function accordingly, providing a way to measure the duration of pulses on the input pin.

Variable Initialization:

  • pin: Specifies GPIO pin 1 for pulse width counting.
  • pulse1: Tracks the start time of the pulse.
  • du, now: References to tmr.delay and tmr.now functions for timing operations.
  • trig: Reference to the gpio.trig function for setting up interrupts.

GPIO Configuration:

  • Sets GPIO pin 1 as an interrupt-enabled pin (gpio.mode(pin, gpio.INT)).

Callback Function:

  • Defines a callback function pin1cb(level, pulse2) to be executed when an interrupt occurs on pin 1.
  • The level parameter indicates whether the interrupt is triggered by a rising edge (gpio.HIGH) or falling edge (gpio.LOW).
  • pulse2 represents the time when the interrupt occurred.

Callback Logic:

  • Calculates the pulse width by subtracting the previous pulse time (pulse1) from the current pulse time (pulse2).
  • Prints the level (indicating rising or falling edge) and the calculated pulse width.
  • Updates pulse1 to store the current pulse time for the next interrupt.

Trigger Setup:

  • Sets up the interrupt trigger using gpio.trig(pin, "down", pin1cb).
  • The trigger is set to detect falling edges ("down") on pin 1 and execute the pin1cb callback function.

Interrupt

The Button Interrupt Counter script showcases the effectiveness of utilizing interrupts in microcontroller programming. By leveraging interrupts, the script efficiently responds to button presses without the need for continuous monitoring. This approach optimizes the utilization of system resources and enables the microcontroller to perform other tasks while waiting for button input.

Furthermore, the script demonstrates an essential concept in embedded systems programming: debouncing. This feature enhances the reliability and accuracy of the button press count, making the script suitable for applications where precise user input tracking is essential.

Overall, the Button Interrupt Counter script exemplifies best practices in microcontroller programming by combining interrupt-driven design with debounce mechanisms to achieve robust and efficient button input handling.

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 Tutorial – Get Google Time

This tutorial will discuss get the google time using NodeMCU in ESP8266. The ESP8266 NodeMCU is a popular development board known for its versatility and ease of use in Internet of Things (IoT) projects. In this tutorial, we’ll explore how to leverage the ESP8266 NodeMCU to fetch the current time from Google’s time servers. Accurate timekeeping is crucial for many IoT applications, such as data logging, scheduling tasks, and synchronization across multiple devices. By connecting to Google’s time servers, we can ensure that our ESP8266 NodeMCU has access to precise and reliable time information.

Code for Get Google Time using NodeMCU in ESP8266

  • You can use any server instead of google. But that server should install http server
  • Use conn:connect(80,”google.com”)   or Google static ip address conn:connect(80,”64.233.161.94″)
-- https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_nodemcu/
-- Tested By  : Arun(20170219)
-- Example Name : AEW_GoogleTime.lua

station_cfg={}
station_cfg.ssid= "Arun" station_cfg.pwd= "ArunEworld" -- Change your SSID and Password
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()

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_GOT_IP, function(T)
  print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
  sta_ip = T.IP
end)



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_GOT_IP, function(T)
  print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
  sta_ip = T.IP
end)



conn=net.createConnection(net.TCP, 0) 

conn:on("connection",function(conn, payload)
            conn:send("HEAD / HTTP/1.1\r\n".. 
                      "Host: google.com\r\n"..
                      "Accept: */*\r\n"..
                      "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
                      "\r\n\r\n") 
            end)
            
conn:on("receive", function(conn, payload)
    print('\nRetrieved in '..((tmr.now()-t)/1000)..' milliseconds.')
    print('Google says it is '..string.sub(payload,string.find(payload,"Date: ")
           +6,string.find(payload,"Date: ")+35))
    conn:close()
    end) 
t = tmr.now()    
conn:connect(80,'google.com')
tmr.alarm(0,10000,1,function() conn:connect(80,'google.com') end) --every second Once
SectionExplanation
ConfigurationConfiguration for Wi-Fi connection.
Wi-Fi ModeSets the Wi-Fi mode to station mode.
Wi-Fi Event HandlersRegisters event handlers for Wi-Fi connection status: STA_CONNECTED, STA_DISCONNECTED, and STA_GOT_IP. These handlers print relevant information when these events occur.
TCP ConnectionCreates a TCP connection to communicate with Google’s server.
Connection HandlerEvent handler for connection. Upon establishing a connection, sends an HTTP request to Google’s server.
Data Receive HandlerEvent handler for receiving data. When receiving a response from Google’s server, it prints the retrieved time.
TimerSets a timer to attempt reconnection to Google’s server every 10 seconds.
ESP8266 NodeMCU Tutorial – Get Google Time

Result

> dofile("AEW_GoogleTime.lua")
> 
 STA - CONNECTED
 SSID: ArunEworld
 BSSID: c0:d0:70:c9:8d:a1
 Channel: 7

 STA - GOT IP
 Station IP: 192.168.1.103
 Subnet mask: 255.255.255.0
 Gateway IP: 192.168.1.1

Retrieved in 7881.115 milliseconds.
Google says it is Thu, 27 Apr 2017 15:05:55 GMT

Retrieved in 10166.297 milliseconds.
Google says it is Thu, 27 Apr 2017 15:05:58 GMT

Retrieved in 20194.126 milliseconds.
Google says it is Thu, 27 Apr 2017 15:06:08 GMT

--like every 10 seconds Once, will get time from Google--


ESP8266 NodeMCU Project – WiFi Status Indicator

This project utilizes an ESP8266 NodeMCU microcontroller to create a visual and auditory indicator for monitoring the status of a WiFi router connection. Based on the connection status, the script controls an LED and a buzzer to provide real-time feedback to the user.

Read more: ESP8266 NodeMCU Project – WiFi Status Indicator

Features

  1. LED Indicator: The script utilizes a GPIO pin connected to an LED to visually indicate the WiFi connection status. When the router is connected, the LED blinks periodically. If the connection is lost, the LED remains off.
  2. Buzzer Alarm: A buzzer connected to another GPIO pin provides audible feedback. When the WiFi connection is lost, the buzzer emits an alarm sound at regular intervals. Once the connection is restored, the buzzer stops.
  3. WiFi Event Monitoring: The script registers event handlers for WiFi connection events such as connection, disconnection, and obtaining an IP address. It prints relevant information to the console for debugging purposes.
  4. Automatic Status Monitoring: The NodeMCU board continuously monitors the WiFi connection status in the background. It automatically adjusts the LED and buzzer states based on changes in the connection status.

Overall, this project offers a simple yet effective solution for monitoring the status of a WiFi router connection, making it suitable for applications where real-time feedback on network connectivity is essential.

Required for ESP8266 WiFi Status Indicator

  • Required NodeMCU Modules (Firmware): GPIO Module, WiFi Module
  • Required Hardware: ESP8266 with Programmer (or)  NodeMCU Dev Kit, LED- 3v3 or 5v, Buzzer
  • Required Software Tools: ESPlorer IDE Tool

Code

ESP8266 WiFi Status Indicator

--[[
    Firmware: NodeMCU custom build by frightanic.com
    Modules: bit, enduser_setup, file, gpio, http, i2c, mdns, mqtt, net, node, ow, pwm, rtcfifo, rtcmem, rtctime, sntp, tmr, uart, wifi
    Required NodeMCU Modules: GPIO, WiFi, Node.
    Tested By: Arun(20170219)
    Example Name: AEW_WiFi_Router-Connection-Status-Indicator.lua
--]]

-- LED initialization
LED = 1 -- GPIO-5 as connect to LED
gpio.mode(LED, gpio.OUTPUT)
gpio.write(LED, gpio.LOW)

-- Buzzer initialization
Buzzer = 2 -- GPIO-04 as connect to Buzzer
gpio.mode(Buzzer, gpio.OUTPUT)
gpio.write(Buzzer, gpio.LOW)

-- WiFi initialization
station_cfg = {}
station_cfg.ssid = "Arun"
station_cfg.pwd = "ArunEworld" -- Change your SSID and Password
wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
wifi.sta.connect()

-- 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)
    Wifi_Router_Status = 1
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)
    Wifi_Router_Status = 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)
    sta_ip = T.IP
end)

-- Blink LED function
function Blink_Led()
    if (0 == gpio.read(LED)) then
        gpio.write(LED, gpio.HIGH)
    elseif (1 == gpio.read(LED)) then
        gpio.write(LED, gpio.LOW)
    end
    tmr.wdclr()
end

-- Buzzer Alarm function
function Buzzer_Alarm()
    if (0 == gpio.read(Buzzer)) then
        gpio.write(Buzzer, gpio.HIGH)
    elseif (1 == gpio.read(Buzzer)) then
        gpio.write(Buzzer, gpio.LOW)
    end
    tmr.delay(100000)
    tmr.wdclr()
end

tmr.alarm(0, 500, 1, function()
    if (1 == Wifi_Router_Status) then
        Blink_Led()
        gpio.write(Buzzer, gpio.LOW)
    elseif (0 == Wifi_Router_Status) then
        Buzzer_Alarm()
        gpio.write(LED, gpio.LOW)
    end
end)
-- Every second twice

Code Explanation

This code acts as a WiFi connection status indicator using LEDs and a buzzer, offering both visual and auditory feedback based on the connection status.

Module Import and Test Information:

  • The script begins with comments detailing the firmware, modules, and testing specifics.
  • It lists the required modules and mentions testing conducted by Arun on a specified date.

Initialization:

  • Initializes GPIO pins for the LED and buzzer.
  • Sets GPIO-5 (LED) as an output and initializes it to LOW.
  • Sets GPIO-04 (buzzer) as an output and initializes it to LOW.

WiFi Initialization:

  • Creates a table (station_cfg) to store the SSID and password for WiFi connection.
  • Configures the WiFi mode to station mode.
  • Establishes a connection to the WiFi network using the provided credentials.

WiFi Event Monitoring:

  • Registers event handlers for WiFi connection events such as STA_CONNECTED, STA_DISCONNECTED, and STA_GOT_IP.
  • Prints relevant information like SSID, BSSID, IP address, etc., upon these events.
  • Updates the Wifi_Router_Status variable based on the connection status.

Function Definitions:

  • Defines two functions: Blink_Led() and Buzzer_Alarm().
  • Blink_Led() toggles the LED state between ON and OFF.
  • Buzzer_Alarm() toggles the Buzzer state between ON and OFF with a delay of 0.1 second.

Main Loop:

  • Sets up a timer alarm to execute a function every 0.5 seconds.
  • Within the timer function:
  • Checks the Wifi_Router_Status variable.
  • If WiFi connects (Wifi_Router_Status = 1), it blinks the LED and disables the buzzer.
  • If WiFi disconnects (Wifi_Router_Status = 0), it triggers the buzzer alarm and disables the LED.
  • This loop repeats every 0.5 seconds, producing a blinking LED effect and triggering the buzzer if the WiFi connection is lost.

Comments:

  • The code includes comments throughout, explaining each section and function for improved readability and comprehension.

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

The code provided demonstrates the usage of the I2C (Inter-Integrated Circuit) protocol on an ESP8266 NodeMCU module. I2C is a popular serial communication protocol used to connect multiple peripherals with a microcontroller or a microprocessor. In this context, the code initializes the I2C interface on the NodeMCU module and showcases how to read data from a specific register of an I2C device.

Pr-Request to Lean

ESP8266 I2C Core

ESP8266 hardware supports only one i2c. But in  bit-banking(Bar Metal code) method you can use all your gpio pin as i2c pins. ESP8266 NodeMCU firmware platform supports only standard speed mode (Sm) 100khz . That means ESP8266 NodeMCU firmware supports 100Kbps for data transfer.


ESP8266 I2C Scanner

  • Required NodeMCU Modules (Firmware) : GPIO Module, I2C Module
  • Required hardware : ESP8266 with Programmer (or)  NodeMCU Dev Kit
  • Required software tools : ESPlorer IDE Tool

Code

This script helps identify I2C devices connected to the ESP8266 NodeMCU board by scanning through all possible device addresses and checking for responses. It’s useful for troubleshooting and verifying the connectivity of I2C devices in the system.

lua
-- https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_nodemcu/
-- Tested By: Arun(20170112)
-- Example Name: AEW_I2C_DeviceScaner.lua
----------------------------------------

-- Setup
local id = 0 -- always 0
local pinSDA = 2 -- 1~12, IO index
local pinSCL = 1 -- 1~12, IO index
local speed = i2c.SLOW -- only i2c.SLOW supported

-- Initialize
i2c.setup(id, pinSDA, pinSCL, speed) -- Initialize the I²C module.
print("Scanning Started....")

for count = 0, 127 do
    i2c.start(id) -- Send an I²C start condition.
    local Status = i2c.address(id, count, i2c.TRANSMITTER) -- Setup I²C address and read/write mode for the next transfer.
    i2c.stop(id) -- Send an I²C stop condition.

    if Status == true then
        print("Addrss - " .. count .. " Detected device address is 0x" .. string.format("%02x", count) .. " (" .. count .. ")")
    elseif Status == false then
        print("Addrss - " .. count .. " nil")
    end
end

print("Scanning End")

Explanation

This Lua script is designed to scan for I2C devices connected to an ESP8266 NodeMCU board. Here’s a breakdown of its functionality:

Setup:

  • It initializes the variables id, pinSDA, pinSCL, and speed.
  • id is set to 0, which typically refers to the first I2C interface on ESP8266 NodeMCU.
  • pinSDA and pinSCL are set to the GPIO pins used for SDA (data line) and SCL (clock line), respectively.
  • speed is set to i2c.SLOW, indicating the desired speed for I2C communication.

Initialization:

  • It initializes the I2C module using i2c.setup() with the specified id, pinSDA, pinSCL, and speed.

Scanning for Devices:

  • It iterates through possible device addresses from 0 to 127.
  • For each address, it attempts to establish communication with the device by sending a start condition (i2c.start()), setting the address (i2c.address()), and then stopping the communication (i2c.stop()).
  • If communication is successful (Status == true), it prints the detected device address in hexadecimal and decimal format.
  • If communication fails (Status == false), it prints “nil” for that address.

Printing Results:

  • It prints “Scanning Started….” before starting the scanning loop.
  • It prints “Scanning End” after the scanning loop is complete.

This table breaks down the code into its key components, making it easier to understand the flow and purpose of each part of the script.

LineExplanation
1-4Introduction and setup of necessary variables and constants.
6Initialization of the I2C module with specified parameters.
8-15Loop to iterate through possible device addresses (0 to 127).
10Start condition for I2C communication.
11Attempt to set the address and read/write mode for the next transfer.
12Stop condition for I2C communication.
13-15Check if the status of the communication is successful and print the detected device address.
17Print “Scanning Started….” to indicate the beginning of the scanning process.
18-21Loop to scan through all possible device addresses and attempt communication.
22-25Print “Scanning End” to indicate the completion of the scanning process.

ESP8266 I2C Example

Code

id = 0
sda = 1
scl = 2

-- Initialize I2C, set pin1 as SDA, set pin2 as SCL
i2c.setup(id, sda, scl, i2c.SLOW)

-- User-defined function: Read from reg_addr content of dev_addr
function read_reg(dev_addr, reg_addr)
    i2c.start(id)
    i2c.address(id, dev_addr, i2c.TRANSMITTER)
    i2c.write(id, reg_addr)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, dev_addr, i2c.RECEIVER)
    c = i2c.read(id, 1)
    i2c.stop(id)
    return c
end

-- Get content of register 0xAA of device 0x77
reg = read_reg(0x77, 0xAA)
print(string.byte(reg))

Code Explanation

This code sets up an I2C interface, defines a function to read data from a specific register of an I2C device, and then uses this function to read the content of a specific register from a specific device address.

Line(s)Explanation
1-3Define the I2C interface parameters: id for the I2C bus, sda for the data line, and scl for the clock line.
5Initialize the I2C communication with the specified parameters (I2C bus, SDA pin, SCL pin, and speed).
8-16Define a custom function read_reg to read data from a specified register address of a given device address.
9-11Start the I2C communication and address the device in write mode to specify the register to read from.
12Write the register address to the device.
13Stop the I2C communication after writing the register address.
14-16Restart the I2C communication, address the device in read mode, read one byte of data from the device, and then stop the I2C communication.
17-19Call the read_reg function to read the content of register 0xAA from device address 0x77.
20Print the byte value of the register content returned by the read_reg function.

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

This Lua script demonstrates how to interface the MCP23008 GPIO expander with an ESP8266 NodeMCU board. The MCP23008 provides an easy way to expand the number of GPIO pins available for use, which can be particularly useful when working with microcontrollers like the ESP8266 that have limited GPIO pins.

Read more: ESP8266 NodeMCU Interface – MCP23008

By using the I2C protocol, the ESP8266 communicates with the MCP23008 to control its GPIO pins. This script sets up the MCP23008, configures its GPIO pins as inputs or outputs, and demonstrates reading the state of input pins (buttons) and controlling the output pins (LEDs).

The script showcases how to initialize the MCP23008, set pin directions, configure pull-up resistors, and read/write GPIO states. Additionally, it periodically reads the state of input pins (buttons) and prints their status, providing a practical example of interfacing with external components using the MCP23008.

Overall, this script serves as a practical guide for implementing GPIO expansion with the MCP23008 on the ESP8266 NodeMCU platform.

Required

  • Required NodeMCU Modules (Firmware) : GPIO Module, I2C Module, Node Module,
  • Required Hardware and Software Tools are ESP8266 with Programmer (or)  NodeMCU Dev Kit, MCP23008, LED,
  • Required software tool is ESPlorer IDE Tool.

MCP23008 with LED Interface

`lua
----------------------------------------
-- https://www.aruneworld.com/embedded/espressif/esp32/esp32_nodemcu/
-- Tested By : Arun(20170212)
-- Example Name : AEW_MCP23008_LEDs.lua
----------------------------------------

-- Constant device address.
local MCP23008_ADDRESS = 0x20

-- Registers' address as defined in the MCP23008's datasheet
local MCP23008_IODIR = 0x00
local MCP23008_IPOL = 0x01
local MCP23008_GPINTEN = 0x02
local MCP23008_DEFVAL = 0x03
local MCP23008_INTCON = 0x04
local MCP23008_IOCON = 0x05
local MCP23008_GPPU = 0x06
local MCP23008_INTF = 0x07
local MCP23008_INTCAP = 0x08
local MCP23008_GPIO = 0x09
local MCP23008_OLAT = 0x0A

-- Default value for i2c communication
local id = 0

-- pin modes for I/O direction
M.INPUT = 1
M.OUTPUT = 0

-- pin states for I/O i.e. on/off
M.HIGH = 1
M.LOW = 0

-- Weak pull-up resistor state
M.ENABLE = 1
M.DISABLE = 0

-- Write function: Writes one byte to a register
local function write(registerAddress, data)
    i2c.start(id)
    i2c.address(id, MCP23008_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, registerAddress)
    i2c.write(id, data)
    i2c.stop(id)
end

-- Read function: Reads the value of a register
local function read(registerAddress)
    i2c.start(id)
    i2c.address(id, MCP23008_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, registerAddress)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, MCP23008_ADDRESS, i2c.RECEIVER)
    local data = 0x00
    data = i2c.read(id, 1) -- we expect only one byte of data
    i2c.stop(id)
    return string.byte(data) -- i2c.read returns a string so we convert to its int value
end

-- Begin function: Sets the MCP23008 device address's last three bits
function M.begin(address, pinSDA, pinSCL, speed)
    MCP23008_ADDRESS = bit.bor(MCP23008_ADDRESS, address)
    i2c.setup(id, pinSDA, pinSCL, speed)
end

-- Write GPIO function: Writes a byte of data to the GPIO register
function M.writeGPIO(dataByte)
    write(MCP23008_GPIO, dataByte)
end

-- Read GPIO function: Reads a byte of data from the GPIO register
function M.readGPIO()
    return read(MCP23008_GPIO)
end

-- Write IODIR function: Writes one byte of data to the IODIR register
function M.writeIODIR(dataByte)
    write(MCP23008_IODIR, dataByte)
end

-- Read IODIR function: Reads a byte from the IODIR register
function M.readIODIR()
    return read(MCP23008_IODIR)
end

-- Write GPPU function: Writes a byte of data to the GPPU register
function M.writeGPPU(dataByte)
    write(MCP23008_GPPU, dataByte)
end

-- Read GPPU function: Reads the GPPU (Pull-UP resistors register) byte
function M.readGPPU()
    return read(MCP23008_GPPU)
end

-- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware
local gpio0, gpio2 = 3, 4

-- Setup MCP23008
M.begin(0x0, gpio2, gpio0, i2c.SLOW)
M.writeIODIR(0x00) -- make all GPIO pins as outputs
M.writeGPIO(0x00) -- make all GPIO pins off/low

-- Count function: Reads the value from the GPIO register, increases the read value by 1,
-- and writes it back so the LEDs will display a binary count up to 255 or 0xFF in hex.
local function count()
    local gpio = 0x00
    gpio = mcp23008.readGPIO()
    if gpio < 0xff then
        mcp23008.writeGPIO(gpio + 1)
    else
        mcp23008.writeGPIO(0x00)
    end
end

-- Run count() every 100ms
tmr.alarm(0,100,1,count)

Explanation

SectionDescription for ESP8266 NodeMCU Interface MCP23008
Header CommentsContains information about the source, author, and example name.
ConstantsDefines constant values for the MCP23008’s device address and various register addresses.
Global VariablesInitializes the id variable to represent the I2C interface index.
Pin Modes and StatesDefines constants for input and output modes, as well as pin states for I/O operations.
Write and Read FunctionsFunctions to write data to and read data from MCP23008 registers via I2C communication.
Initialization FunctionSets up the MCP23008 device address and initializes I2C communication.
GPIO Control FunctionsFunctions to write to and read from the GPIO register of the MCP23008.
I/O Direction Control FunctionsFunctions to control the input/output direction register (IODIR) of the MCP23008.
Pull-Up Resistor Configuration FunctionsFunctions to control the pull-up resistor configuration register (GPPU) of the MCP23008.
Main SetupMaps GPIO pins for SDA and SCL, and initializes the MCP23008 with specific configurations.
LED Counting FunctionReads the current value from the GPIO register, increments it by 1, and writes it back to create a binary count pattern on the LEDs.
Timer SetupSets up a timer to execute the LED counting function (count) every 100ms.

MCP23008 with Buttons Interface

This Lua code sets up communication between an ESP8266 NodeMCU and an MCP23008 I/O expander via the I2C protocol. It defines functions to write and read from the MCP23008’s registers, as well as functions to control the GPIO pins and their states. Finally, it continuously monitors the state of the GPIO pins connected to buttons and prints the state every 2 seconds.

----------------------------------------
-- https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_nodemcu/
-- Tested By : Arun(20170212)
-- Example Name : AEW_MCP23008_Buttons.lua
----------------------------------------

-- Constant device address.
local MCP23008_ADDRESS = 0x20

-- Registers' address as defined in the MCP23008's datasheet
local MCP23008_IODIR = 0x00
local MCP23008_IPOL = 0x01
local MCP23008_GPINTEN = 0x02
local MCP23008_DEFVAL = 0x03
local MCP23008_INTCON = 0x04
local MCP23008_IOCON = 0x05
local MCP23008_GPPU = 0x06
local MCP23008_INTF = 0x07
local MCP23008_INTCAP = 0x08
local MCP23008_GPIO = 0x09
local MCP23008_OLAT = 0x0A

-- Default value for i2c communication
local id = 0

-- pin modes for I/O direction
M.INPUT = 1
M.OUTPUT = 0

-- pin states for I/O i.e. on/off
M.HIGH = 1
M.LOW = 0

-- Weak pull-up resistor state
M.ENABLE = 1
M.DISABLE = 0

-- Write function: Writes one byte to a register
local function write(registerAddress, data)
    i2c.start(id)
    i2c.address(id, MCP23008_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, registerAddress)
    i2c.write(id, data)
    i2c.stop(id)
end

-- Read function: Reads the value of a register
local function read(registerAddress)
    i2c.start(id)
    i2c.address(id, MCP23008_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, registerAddress)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, MCP23008_ADDRESS, i2c.RECEIVER)
    local data = i2c.read(id, 1)
    i2c.stop(id)
    return string.byte(data)
end

-- Begin function: Sets the MCP23008 device address's last three bits
function M.begin(address, pinSDA, pinSCL, speed)
    MCP23008_ADDRESS = bit.bor(MCP23008_ADDRESS, address)
    i2c.setup(id, pinSDA, pinSCL, speed)
end

-- Write GPIO function: Writes a byte of data to the GPIO register
function M.writeGPIO(dataByte)
    write(MCP23008_GPIO, dataByte)
end

-- Read GPIO function: Reads a byte of data from the GPIO register
function M.readGPIO()
    return read(MCP23008_GPIO)
end

-- Write IODIR function: Writes one byte of data to the IODIR register
function M.writeIODIR(dataByte)
    write(MCP23008_IODIR, dataByte)
end

-- Read IODIR function: Reads a byte from the IODIR register
function M.readIODIR()
    return read(MCP23008_IODIR)
end

-- Write GPPU function: Writes a byte of data to the GPPU register
function M.writeGPPU(dataByte)
    write(MCP23008_GPPU, dataByte)
end

-- Read GPPU function: Reads the GPPU (Pull-UP resistors register) byte
function M.readGPPU()
    return read(MCP23008_GPPU)
end

-- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware
local gpio0, gpio2 = 3, 4

-- Setup the MCP23008
M.begin(0x0, gpio2, gpio0, i2c.SLOW)
M.writeIODIR(0xff)
M.writeGPPU(0xff)

-- Show buttons state function
function showButtons()
    local gpio = M.readGPIO()
    for pin = 0, 7 do
        local pinState = bit.band(bit.rshift(gpio, pin), 0x1)
        if pinState == M.HIGH then
            pinState = "HIGH"
        else
            pinState = "LOW"
        end
        print("Pin " .. pin .. ": " .. pinState)
    end
    print("\r\n")
end

tmr.alarm(0, 2000, 1, showButtons) -- run showButtons() every 2 seconds

Explanation

SectionDescription
Header CommentsContains information about the source, author, and example name.
ConstantsDefines constant values for the MCP23008’s device address and various register addresses.
Global VariablesInitializes the id variable to represent the I2C interface index.
Pin Modes and StatesDefines constants for input and output modes, as well as pin states for I/O operations.
Write and Read FunctionsFunctions to write data to and read data from MCP23008 registers via I2C communication.
Initialization FunctionSets up the MCP23008 device address and initializes I2C communication.
GPIO Control FunctionsFunctions to write to and read from the GPIO register of the MCP23008.
I/O Direction Control FunctionsFunctions to control the input/output direction register (IODIR) of the MCP23008.
Pull-Up Resistor ConfigurationFunctions to control the pull-up resistor configuration register (GPPU) of the MCP23008.
Main SetupMaps GPIO pins for SDA and SCL, and initializes the MCP23008 with specific configurations.
Show Buttons State FunctionReads the state of each GPIO pin (button), prints the state, and repeats every 2 seconds.

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

The MCP23017 is a popular I/O expander IC that allows you to increase the number of I/O pins available to a microcontroller. In this code example, we’ll interface an MCP23017 with an ESP8266 NodeMCU board to control LEDs. The ESP8266 NodeMCU will communicate with the MCP23017 via the I2C protocol to toggle the LEDs connected to the MCP23017’s GPIO pins. This setup provides a straightforward way to expand the number of GPIO pins available for controlling external devices.

Read more: ESP8266 NodeMCU Interface – MCP23017

MCP23017 with LED Interface

  • Required NodeMCU Modules (Firmware): GPIO Module, I2C Module, Node Module,
  • Required Hardware and Software Tools are ESP8266 with Programmer (or)  NodeMCU Dev Kit, MCP23017, LED,
  • The required software tool is the ESPlorer IDE Tool.

MCP23017 lua Module code

`lua
-- https://www.aruneworld.com/embedded/espressif/esp32/esp32_nodemcu/
-- Tested By : Arun(20170212)
-- Example Name : AEW_MCP23017_LEDs.lua
------------------------------------------------------------------------------------------
-- i2c setup
local id = 0 -- always 0
local pinSDA = 2 -- 1~12, IO index
local pinSCL = 1 -- 1~12, IO index
local speed = i2c.SLOW -- only i2c.SLOW supported

-- Rotate LEDs
Shift_1 = {1,2,4,8,16,32,64,128}
Shift_2 = {128,64,32,16,8,4,2,1}

-- CONSTANTS
local MCP23017_ADDRESS = 0x21 -- you can change this id, I used 0x21

-- MCP23017 registers (everything except direction defaults to 0)
local IODIRA = 0x00 -- I/O DIRECTION REGISTE (0 = output, 1 = input (Default))
local IODIRB = 0x01
local IPOLA = 0x02 -- INPUT POLARITY REGISTER (0 = normal, 1 = inverse)
local IPOLB = 0x03
--GPINTEN – INTERRUPT-ON-CHANGE PINS
local GPINTENA = 0x04 -- Interrupt on change (0 = disable, 1 = enable)
local GPINTENB = 0x05
local DEFVALA = 0x06 -- Default comparison for interrupt on change (interrupts on opposite)
local DEFVALB = 0x07
local INTCONA = 0x08 -- Interrupt control (0 = interrupt on change from previous, 1 = interrupt on change from DEFVAL)
local INTCONB = 0x09
local IOCON = 0x0A -- IO Configuration: bank/mirror/seqop/disslw/haen/odr/intpol/notimp
--IOCON = 0x0B -- same as = 0x0A
local GPPUA = 0x0C -- GPIO PULL-UP RESISTOR REGISTERull-up resistor (0 = disabled, 1 = enabled)
local GPPUB = 0x0D
local INFTFA = 0x0E -- Interrupt flag (read only): (0 = no interrupt, 1 = pin caused interrupt)
local INFTFB = 0x0F
local INTCAPA = 0x10 -- Interrupt capture (read only): value of GPIO at time of last interrupt
local INTCAPB = 0x11
local GPIOA = 0x12 -- Port value. Write to change, read to obtain value
local GPIOB = 0x13
local OLLATA = 0x14 -- Output latch. Write to latch output.
local OLLATB = 0x15

local chip1 = 0x20 -- MCP23017 is on I2C address = 0x20
local chip2 = 0x21 -- MCP23017 is on I2C address = 0x21

-- user-defined function: read from reg_addr content of dev_addr
function read_reg(MCP23017_ADDRESS, reg_addr)
    i2c.start(id)
    i2c.address(id, MCP23017_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, reg_addr)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, MCP23017_ADDRESS, i2c.RECEIVER)
    c = string.byte(i2c.read(id, 1))
    i2c.stop(id)
    return c
end

--write MCP23017 start
function write_reg(MCP23017_ADDRESS, reg_addr, reg_val)
    i2c.start(id)
    i2c.address(id, MCP23017_ADDRESS, i2c.TRANSMITTER)
    i2c.write(id, reg_addr)
    i2c.write(id, reg_val)
    i2c.stop(id)
end
--write MCP23017 end

--MCP Initialize start
function init(MCP23017_ADDRESS)
    write_reg(MCP23017_ADDRESS, IOCON, 0x60) -- BANK=0, MIRROR=1, SEQOP=1, DISSLW=0, HAEN=0, ODR=0, INTPO=0, bit0=nil
    write_reg(MCP23017_ADDRESS, IODIRA, 0x00) -- Port A as Output
    write_reg(MCP23017_ADDRESS, GPIOA, 0xFF) -- Set All port A pins High
end
--MCP Initialize end

-----------Main Program start------------------
i2c_speed = i2c.setup(id, pinSDA, pinSCL, speed) -- Initialize the I²C module.

if i2c_speed ~= nil then
    print("i2c Speed : "..i2c_speed)
    print("i2c init done")
else
    print("i2c

Code Explanation

SectionDescription for ESP8266 NodeMCU Interface MCP23017
IntroductionThis code demonstrates the interfacing of MCP23017 with the ESP8266 NodeMCU board using the I2C communication protocol.
I2C SetupSets up the parameters for I2C communication, including the I2C ID, SDA and SCL pins, and speed.
ConstantsDefines constants for MCP23017 registers and addresses used in the code.
User-Defined FunctionsIncludes functions to read and write data from/to MCP23017 registers.
MCP InitializationInitializes the MCP23017 by configuring its IOCON register and setting Port A as output with all pins high.
Main ProgramInitializes the I2C module, initializes the MCP23017, defines functions for LED blinking and shifting, and starts a timer to periodically shift the LEDs.

Uses

This code example demonstrates the use of the MCP23017 I/O expander with an ESP8266 NodeMCU board. It showcases how to set up communication between the ESP8266 and the MCP23017 via the I2C protocol and how to control LEDs connected to the MCP23017’s GPIO pins.

Specifically, the code accomplishes the following tasks:

  1. Sets up the I2C communication between the ESP8266 NodeMCU and the MCP23017.
  2. Initializes the MCP23017 by configuring its registers.
  3. Implements functions to read from and write to the MCP23017 registers.
  4. Defines functions to control the LEDs connected to the MCP23017.
  5. Defines a main loop function to shift LEDs connected to the MCP23017 GPIO pins.
  6. Sets up a timer to execute the main loop function periodically.

Overall, this code serves as a practical example of how to interface an ESP8266 NodeMCU with an MCP23017 to expand the available GPIO pins for controlling external components such as LEDs.

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