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

 

ESP8266 NodeMCU Devkit GPIO Pin Map

 

 

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

 

 


 ESP8266 NodeMCU Module GPIO Functions

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

 

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


 

Pr-Request

 

GPIO pin set as input

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

 

Required

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

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

 

Code

 

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

 


GPIO pin set as output

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

 

Code

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

 

Result

 

 


GPIO pin status monitor

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

 

Required

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

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

 

Basic connection Diagram

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

 

Code

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

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

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

 

 


 

ESP8266 NodeMCU – Flash Firmware

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

Read more… →

ESP8266 NodeMCU – Build Firmware

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

Read more: ESP8266 NodeMCU – Build Firmware

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

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

What is firmware?

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

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

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

NodeMCU Firmware

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

In Linux


Web-based Cloud Build Custom NodeMCU Firmware

Beginner Recommended Method*

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

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

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

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

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

Step-6: Click the Start Your Build button

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

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


NEXT

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

ESP8266 NodeMCU – How to know firmware information

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

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

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

Read more… →

ESP8266 NodeMCU Interface – ADXL345

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

Read more: ESP8266 NodeMCU Interface – ADXL345

ADXL345

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

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

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

Code

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

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

print("ArunEworld")

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

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

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

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

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

Code Explanation

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

NEXT

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

ESP8266 NodeMCU Module – NET

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

Read more: ESP8266 NodeMCU Module – NET

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

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

NET Module Functions for ESP8266 NodeMCU

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

Example :1 TCP Connection in local

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

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

Code

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

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

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

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

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

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

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

-- Wifi Event Monitoring
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
    print("\n\tSTA - CONNECTED" ..
          "\n\tSSID: " .. T.SSID ..
          "\n\tBSSID: " .. T.BSSID ..
          "\n\tChannel: " .. T.channel)
end)

wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    print("\n\tSTA - DISCONNECTED" ..
          "\n\tSSID: " .. T.SSID ..
          "\n\tBSSID: " .. T.BSSID ..
          "\n\tReason: " .. T.reason)
    TCP_Conn = nil
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("\n\tSTA - GOT IP" ..
          "\n\tStation IP: " .. T.IP ..
          "\n\tSubnet Mask: " .. T.netmask ..
          "\n\tGateway IP: " .. T.gateway)
    TCP_CONNECTION_func()
end)

Code Explanation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

--wifi.start() -- commented out

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

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

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

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

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

Explanation

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

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

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

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

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

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

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

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

This line creates a TCP connection object named srv.

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

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

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

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

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

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


See also


Next

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

ESP8266 NodeMCU Module – Timer

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

we can use this timer function in the following applications

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

ESP8266 NodeMCU Module – MQTT

Functions

  • mqtt.Client()  – Creates a MQTT client.
  • 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)

 

 

 


Next :

Previous :


 

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