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.
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.
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.
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.
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.
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.
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.)
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.
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.
if you have questions like How set GPIO pin as input in ESP8266? then refer the below contents
Required
ESP8266 Any module or NodeMCU Development Kit(Any Version)
ESPlorer
Wires (Optional)
Note : if your using ESP8266 module only you need to know basic connection diagram of ESP8266
Code
-- set pin index 1 to GPIO mode, and set the pin to high.
pin=3 --gpio-0
gpio.mode(pin, gpio.INPUT)
while true do
print("GPIO Read PIN Status : "..gpio.read(pin))
end
GPIO pin set as output
Set GPIO pin as output using gpio.mode() function.
--www.aruneworld.com/embedded/esp8266/esp8266-nodecmu
button_pin=3 --GPIO-0
gpio.mode(button_pin, gpio.INPUT)
while true do
print("GPIO Read PIN Status : "..gpio.read(button_pin))
tmr.delay(1000000)
end
NodeMCU Flasher tool is flashing the NodeMCU Firmware to ESP8266 Easily. This tool is developed by NodeMCU. Flashing firmware to an ESP8266-based NodeMCU board involves updating the firmware on the microcontroller to enable it to execute the desired code. Here’s a step-by-step guide on how to flash firmware to an ESP8266 NodeMCU using the ESP8266Flasher tool. Please note that you’ll need a USB-to-Serial converter or USB-based development board for this process.
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.
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.
What is NodeMCU Firmware?
What is the format of NodeMCU Firmware?
What contains the NodeMCU Fimware?
Build Firmware
How to build the NodeMCU Firmware for ESP8266?
How to compile the NodeMCU Firmware for ESP8266?
How to build the NodeMCU firmware from source?
How Build NodeMCU firmware for ESP8266 in Linux Machine?
How Build NodeMCU firmware for ESP8266 using web based Cloud?
how to build NodeMCU firmware on your own?
What are the ESP8266 modules are support this NodeMCU Firmware?
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.
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.
If you have many custom NodeMCU firmware, but the firmware name does not contain the details of info about what the NodeMCU module libraries are present. This article explains ESP8266 NodeMCU – How to know firmware information?, if ESPlorer works fine means ESP8266 returns the firmware details, some times ESPlorer IDE does not auto-detect the firmware details. so you should note that your custom NodeMCU firmware details yourself. This post will help to firmware details list easily by using small code.
The NodeMCU firmware is designed to work with the Lua scripting language. Lua is a lightweight and powerful scripting language that is well-suited for embedded systems.
The firmware is often used in conjunction with the NodeMCU development kit, which includes the ESP8266 WiFi module and a USB-to-Serial converter. The kit simplifies the development process and makes it easy to upload Lua scripts to the ESP8266
Home automation is the process of controlling various devices and systems in your home through a centralized control system. With the advancement of technology, home automation has become more accessible and affordable for homeowners.The ESP8266 NodeMCU is a popular choice for home automation projects due to its built-in Wi-Fi capability and compatibility with various sensors and actuators. In this project, we will explore how to set up a basic home automation system using the ESP8266 NodeMCU.
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.
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
Line
Code
Explanation
1
sda = 2
Assigns pin 2 to the variable sda, representing the Serial Data (SDA) pin.
2
scl = 1
Assigns pin 1 to the variable scl, representing the Serial Clock (SCL) pin.
4
print("ArunEworld")
Prints the message “ArunEworld” to the console.
7
adxl345.init(sda, scl)
Initializes the ADXL345 sensor with the SDA and SCL pins defined earlier.
10
tmr.delay(3000000)
Delays the execution of the program for 3 seconds (3000000 microseconds).
13
print(adxl345.read())
Reads data from the ADXL345 sensor and prints it to the console.
16
function ADXL_read() ... end
Defines a function named ADXL_read to read accelerometer data from the ADXL345 sensor.
19
tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)
Sets up a timer to call the ADXL_read function every 1000 milliseconds (1 second) repeatedly.
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.
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
Constant
Description
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
Certainly! Here’s an explanation of the provided Lua code:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
In Lua on the ESP8266 NodeMCU module, you can use the tmr module to work with a timer. Here’s a basic guide on using the ESP8266 NodeMCU Module – Timer. The tmr Module provides 7 (0-6) static timer functions of the timer module. we can’t use more than 7. Also, you can create an object-based timer function with a custom name.
we can use this timer function in the following applications
To blink an LED for a certain time duration its like a repeated process.
mqtt.client:close() – Closes connection to the broker.
mqtt.client:connect() – Connects to the broker specified by the given host, port, and secure options.
mqtt.client:lwt( ) – Setup Last Will and Testament (optional).
mqtt.client:on() – Registers a callback function for an event.
mqtt.client:publish() – Publishes a message.
mqtt.client:subscribe() – Subscribes to one or several topics.
mqtt.client:unsubscribe() – Unsubscribes from one or several topics.
MQTT Example
MQTT subscribe and publish the data to
-- Required Modules :Mqtt,Wifi
-- https://www.aruneworld.com/
-- Tested By : Arun(20170527)
-- Example Name : AEW_Mqtt.lua
---------------------------------------------------------------------------------
station_cfg={}
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "ArunEworld.com" --please change your SSID and Passworld
print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()
--Initializing Mqtt
DEVICE_NAME = "ArunEworld-"..node.chipid()
PUBLISH_TOPIC = "ArunEworld/"..DEVICE_NAME.."-Result"
SUBSCRIBE_TOPIC = "ArunEworld/"..DEVICE_NAME
CLIENT_ID = DEVICE_NAME
USERNAME = "username" -- please change your username
PASSWORD = "Password" -- please change your Password
HOSTNAME = "mqtt.aruneworld.com" -- Please change your port
PORT = "Port_Number" -- Please change your port number
-- Mqtt Setup
m = mqtt.Client(CLIENT_ID, 120, USERNAME, PASSWORD, 0)
m:connect(HOSTNAME, PORT, 0, function(conn)
m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Online", 1, 0, function(conn) end)
m:subscribe(SUBSCRIBE_TOPIC, 1, function(conn) end)
end)
--Mqtt Receive function
m:on("message", function(client, topic, payload)
if payload ~= nil then
print(payload)
else
print("Mqtt Reccived nill payload message")
end
collectgarbage("collect")
end)
--Mqtt Send function
local function Send_MQTT(strings)
m:publish(PUBLISH_TOPIC,strings, 1, 0, function(conn) end)
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)
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)
Read and Write files using MQTT
transfer files over mqtt
-- For More info :- https://www.aruneworld.com/
-- Tested By : Arun(20170527)
-- Required Modules : CJSON, FILE, MQTT, WiFi,
station_cfg={}
DEVICE_NAME = node.chipid()
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "Arun"
PUBLISH_TOPIC = "MQTT_File_Ex_PUB"
SUBSCRIBE_TOPIC = "MQTT_File_Ex_SUB"
CLIENT_ID = DEVICE_NAME
USERNAME = ""
PASSWORD = ""
HOSTNAME = "iot.eclipse.org"
PORT = 1883
print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()
-- test transfer files over mqtt.
m_dis={} --Created the table and name is m_dis
function dispatch(m,t,pl)
if pl~=nil and m_dis[t] then
m_dis[t](m,pl)
end
end
function pubfile(m,filename)
file.close()
file.open(filename)
repeat
local pl=file.read(1024)
if pl then m:publish("/topic2",pl,0,0) end
until not pl
file.close()
end
-- payload(json): {"cmd":xxx,"content":xxx}
function topic1func(m,pl)
print("get1: "..pl)
local pack = cjson.decode(pl)
if pack.content then
if pack.cmd == "open" then file.open(pack.content,"w+")
elseif pack.cmd == "write" then file.write(pack.content)
elseif pack.cmd == "close" then file.close()
elseif pack.cmd == "remove" then file.remove(pack.content)
elseif pack.cmd == "run" then dofile(pack.content)
elseif pack.cmd == "read" then pubfile(m, pack.content)
end
end
end
m_dis["/topic1"]=topic1func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
--m=mqtt.Client()
m = mqtt.Client(CLIENT_ID, 20, USERNAME, PASSWORD, 0)
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Live", 1, 0, function(m) print("[LOG]:- Mqtt "..DEVICE_NAME.." is Live in Online Mode") end)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
--m:connect(192.168.18.88,1883,0,1)
--host = "iot.eclipse.org"
m:connect(HOSTNAME,1883,0,1)
-- usage:
-- another client(pc) subscribe to /topic2, will receive the test.lua content.
-- and publish below message to /topic1
-- {"cmd":"open","content":"test.lua"}
-- {"cmd":"write","content":"print([[hello world]])\n"}
-- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
-- {"cmd":"write","content":"test.lua"}
-- {"cmd":"run","content":"test.lua"}
-- {"cmd":"read","content":"test.lua"}
MQTT to cloud
-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
if pl~=nil and m_dis[t] then
m_dis[t](m,pl)
end
end
function topic1func(m,pl)
print("get1: "..pl)
end
function topic2func(m,pl)
print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:subscribe("/topic2",0,function(m) print("sub done") end)
m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time()
m:publish("/topic1",pl,0,0)
end)
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 asuart.write(0, adc.read(0).."\n")the value to terminal window
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 Modulein windows system. You can also use any other ESP8266 Modules for this project.
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.
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-9
Header comments providing information about the code, including its source, author, and example name.
11-14
Declaration of variables for configuring the I²C communication, including the I²C ID, SDA pin, SCL pin, and speed.
17-33
Definition of constant values, including the address of the MCP23017, and an array of numbers for the 7-segment display.
36-60
Definition of MCP23017 register addresses and their corresponding functions. These functions handle reading from and writing to the MCP23017 registers.
63-72
Function to initialize the MCP23017. It sets the IO configuration and configures Port A as an output with all pins set to high.
75-89
Main program logic, including the initialization of the I²C module, printing the I²C speed, and handling initialization of the MCP23017.
92-100
Blinking of the 7-segment display. It sets all pins of Port A to high, delays, then sets them to low.
103-116
Loop 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.
118
Setting up a timer to call the Display() function every second.
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 Interface
Example
1. Input Sensing
Detecting button presses for menu navigation
2. User Interaction
Initiating actions such as turning on/off devices
3. Control Mechanism
Controlling the speed of a motor based on button input
4. Event Triggering
Triggering alarms or notifications
5. User Feedback
Providing feedback through LED indicators
6. Configuration Settings
Adjusting settings in a user interface
Advantage and Disadvantage
Advantages
Disadvantages
Simple and intuitive user interaction
Limited input options compared to touchscreens
Cost-effective and easy to implement
Physical wear and tear over time
Tactile feedback provides confirmation
Limited functionality for complex interactions
Suitable for applications requiring precise input
Limited space for multiple buttons on small devices
Works reliably in various environments
May 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 Buttons
Description
User Interaction
Buttons facilitate direct user interaction with electronic devices, enabling input commands.
Control
They provide users with control over device functions and operations, enhancing usability.
Feedback
Buttons offer tactile feedback upon pressing, confirming the user’s action.
Versatility
Buttons can be integrated into various devices and interfaces, offering versatile functionality.
Reliability
They are known for their durability and consistent performance, ensuring reliable operation.
Cost-Effectiveness
Buttons 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 Types
Description
Push Button
Typically a simple momentary switch that closes a circuit when pressed and opens it when released.
Tactile Button
Features a small, tactile protrusion on the surface, providing physical feedback upon pressing.
Toggle Switch
A mechanical switch with a lever or toggle that can be flipped or moved to open or close a circuit.
Rocker Switch
Similar to a toggle switch but with a flat, paddle-like actuator that rocks back and forth to toggle.
Slide Switch
Utilizes a sliding mechanism to open or close the circuit, often used for simple on/off operations.
Capacitive Touch Button
Operates through touch-sensitive materials, activated by the presence of a conductive object or a finger.
Membrane Button
Consists 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).
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.
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″)
Registers 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 Connection
Creates a TCP connection to communicate with Google’s server.
Connection Handler
Event handler for connection. Upon establishing a connection, sends an HTTP request to Google’s server.
Data Receive Handler
Event handler for receiving data. When receiving a response from Google’s server, it prints the retrieved time.
Timer
Sets 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--
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.
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.
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.
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.
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 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.
You must be logged in to post a comment.