echo '' ;

Category Archives: Embedded

ESP32 ArduinoCore Interface – ADC

The “ESP32 ArduinoCore Interface – ADC” provides a seamless integration between the ESP32 microcontroller and the Arduino development environment, specifically focusing on the Analog-to-Digital Converter (ADC) functionality.

ADC

TermDescription
ADCAnalog-to-Digital Converter – A device or circuit that converts analog signals to digital data.
FunctionalityConverts continuous analog signals into discrete digital values.
ProcessSamples the analog input signal at regular intervals and quantizes the sampled values into digital values.
ApplicationsUsed in microcontrollers, data acquisition systems, sensors, audio equipment, communication devices, and more.
ResolutionThe number of digital bits used to represent the analog signal. Higher resolution ADCs provide more precise representations.
Sampling RateDetermines how frequently the ADC samples the analog input signal. Higher sampling rates enable more accurate representation of fast-changing signals.
TypesSuccessive approximation, delta-sigma, pipeline, and flash ADCs are common types, each with specific advantages and applications.
InterfaceInterfaces with digital systems such as microcontrollers or computers, where the digital output values can be processed or stored.

ADC Pins

PinADC ChannelGPIO Number
GPIO32ADC1_CH432
GPIO33ADC1_CH533
GPIO34ADC1_CH634
GPIO35ADC1_CH735
GPIO36ADC1_CH036
GPIO37ADC1_CH137
GPIO25ADC2_CH825
GPIO26ADC2_CH926

This table lists the ADC pins available on the ESP32 microcontroller along with their corresponding ADC channels and GPIO numbers.

Code

/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

Code Explanation of ESP32 ArduinoCore Interface ADC

Code Purpose: Reading an analog input from pin A0 and printing the value to the serial monitor.

Setup Routine: This part of the code initializes serial communication at a baud rate of 9600 bits per second.

   // the setup routine runs once when you press reset:
   void setup() {
     // initialize serial communication at 9600 bits per second:
     Serial.begin(9600);
   }

Loop Routine:

  1. This section continuously reads the analog value from pin A0 using the analogRead() function.
  2. It then prints the value to the serial monitor using Serial.println().
  3. A small delay of 1 millisecond is added between reads for stability using delay().
   // the loop routine runs over and over again forever:
   void loop() {
     // read the input on analog pin 0:
     int sensorValue = analogRead(A0);
     // print out the value you read:
     Serial.println(sensorValue);
     delay(1);        // delay in between reads for stability
   }

Overall Functionality: This code can be useful for testing analog sensors or for basic data-logging applications.

Advantage of ESP32 ArduinoCore Interface ADC

AdvantageDescription
Analog Signal ProcessingADCs enable microcontrollers to process analog signals from the physical world, converting them into digital values that can be processed by digital systems.
Sensor InterfacingADCs facilitate interfacing with various sensors that produce analog output, such as temperature sensors, light sensors, and pressure sensors, allowing accurate measurement and response to real-world phenomena.
Signal ConditioningADCs can be used for signal conditioning tasks, including amplification, filtering, and noise reduction, before converting analog signals to digital form, improving accuracy and reliability of measured data.
Data AcquisitionADCs enable microcontrollers to acquire data from analog sources at high speeds and with high precision, suitable for applications such as data logging, instrumentation, and control systems.
VersatilityADCs come in various resolutions, sampling rates, and input voltage ranges, allowing developers to choose the most suitable ADC for their specific application requirements.
IntegrationMany microcontrollers, including the ESP32, feature built-in ADCs, eliminating the need for external ADC components and reducing system complexity and cost.

NEXT

Arduino-Core Get Start (Soon)
ESP32 Arduino Core Interface
ArduinoCore Interface Basics
ArduinoCore Interface WiFi
ArduinoCore Interface – LED
ArduinoCore Interface ADC
ArduinoCore Interface DS18B20
ESP32 Arduino Core Projects
ArduinoCore Project – WebServer
Others
Arduino-Core Sitemap
Arduino-Core All Post

Workshop : 20171001-Internet Of Things Using ESP8266

“If you think that the internet has changed your life, think again. The IoT is about to change it all over again!” –

— Brendan O’Brien, Aria systems


Workshop : Internet Of Things using ESP8266

ESP8266 is popular Wi-Fi chip and Internet of things is one of the fastest growing technologies. So we thought to conduct a technical workshop about IOT using ESP8266. You’ll learn the basic concepts and features of the Internet of Things and will be able to build projects using the ESP8266 NodeMCU platform. You’ll also discover fundamental concepts of cloud computing, sensor reading, connecting the ESP8266 to the Internet, wireless interfaces and controlling devices with Android phones. You’ll also learn to use the most popular open platforms for managing sensor data from the ESP8266, how to trigger actuators remotely, and how to read information on your Android Smart Phones. if you attend this workshop you will able to do IOT projects by you-self also you can help others to lean about IOT. Interested, can join this workshop. The duration is seven hours in a day and details are mentioned below and refer the image also.

Session-1 (Morning)

  • Overview of Internet of things.
  • Get started with ESP8266 and development board.
  • Basics interface : GPIO,Timer, File System, WiFi.
  • Basic Experiments : LED, RGB LED, Buzzer, Button, Relay.
  • Some More Experiments : PWM, WiFi, TCP, UDP, SNPT, RTC, MQTT.

Session-2 (Afternoon)

  • Real time Project 1 : Smart Device Control with monitor (Home Automation devices-Online/Offline).
  • Real Time Project 2 : Smart RGB Light (Online/Offline).
  • Project 3 : Network Status Indicator.
  • Project 4 : Data Logger.

Goal

  • Workshop is to make the students skill full and efficient for Internet of things related concepts.
  • The students to do their final year projects by them-self.
  • Apply Internet of things application in your day-to-day.

Participation Prerequisites

To participate in the workshop, you will need the following:

  • A laptop – Windows(Latest) and at least one free USB port with internet connection.
  • A micro-USB cable with data lines that fits your USB port.
  • A Mobile with WiFi, Host-spot feature and internet connection.
  • A breadboard and arduino board with cable.(Optional)
  • You will need a install this software( I will give at workshop)
  • Java
    • Windows Offline (32-Bit)
    • Windows Offline (64-bit)
  • Keep on this below software’s
    • ESPlorer
    • Notepad++. : Windows Offline (32-Bit)
  • Please note that the workshop will be in mostly English (Local Language-Prefers).

Participation will receive in additional, at the workshop!

  • Wi-Fi development board,
  • LED,
  • RGB LED,
  • Female-female connector cables,
  • Piezoelectric speaker,
  • Magnetic Reed Switch
  • Magnet
  • Certificate will provide end of the workshop to each participate,
  • End of the session we will provide all kind of workshop materials like PPT, documents, videos and source code.

Venue

Department of Electronics and Communication Engineering,
Mahendra Engineering College
Salem – Thiruchengode Highway,
Mahendhirapuri, Namakkal District,
Mallasamudram, Tamil Nadu, India-637503.


Registration

Note : Once you registered, you will get a conformation message to registered mobile and e-mail.

This event was held. you can’t register. contact Mr.Arun.

 


Payment Method

Note : You can pay the workshop fee by two ways – Online/Offline. One we received your payment you will get a message to your registered mobile and e-mail.

Online : Pay using Paytm

  • Pay workshop fee (money) scan QR code image
  • In Optional description write  “ArunEworld_Workshop_20170821” ,space. “You_Name” “ArunEworld_Workshop_20170821″<space>”You_Name”  (Ex : ArunEworld_Workshop_20170821 Raja)

Offline : Pay to Workshop organizer

Contact: Mr.Giri.K , Assistant Professor, Mahendra College of Engineering,

Contact Number : +919003503908.

 


Attendees List

Once you complete registration successfully, then your name will be listed below automatically.

 

 


Contact Organizer

Mr. Giri. K (girik@mahendra.info, +919003503908)
Department of Electronics and Communication Engineering,
Mahendra Engineering College
Salem – Thiruchengode Highway,
Mahendhirapuri, Namakkal District,
Mallasamudram, Tamil Nadu, India-637503.


Workshop full details and resource

Click this below link to see the syllabus, contents, videos and more, etc..

  • 20170807-Workshop_IOT_ESP8266 Details

 


 

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

ESP32 Mongoose-OS Interface – WiFi

WiFi Status Monitor

// Monitor network connectivity.
Net.setStatusEventHandler(function(ev, arg) {
  let evs = "???";
  if (ev === Net.STATUS_DISCONNECTED) {
    evs = "DISCONNECTED";
  } else if (ev === Net.STATUS_CONNECTING) {
    evs = "CONNECTING";
  } else if (ev === Net.STATUS_CONNECTED) {
    evs = "CONNECTED";
  } else if (ev === Net.STATUS_GOT_IP) {
    evs = "GOT_IP";
  }
  print("== Net event:", ev, evs);
}, null);

 


Next :

Previous :


 

PIC Interface – PWM

 

Functions

  • pwm_init()
  • pwm_dutycycle(unsigned int duty)

Example : Generate predefined PWM using four buttons

Code

  • Define Port-B as input and RB0, RB1, RB2 and RB3 used as button input
  • Generate PWM using PWM functions

Note  :  UN-command the line depend on your preferred compiler.

//www.ArunEworld.com/embedded/microchip/pic_mcu/
#include<pic.h> // for Hi-Tech Compiler

#define _XTAL_FREQ 4000000

//short currduty1=16;
void init()
{
    PORTB=0X00;
    TRISB=0X0f;
}

void pwm_dutycycle(unsigned int duty)
{
    CCPR1L=duty;
    CCP1CON&=0xCF;
    CCP1CON=(CCP1CON|(0X30&(duty<<4)));
}

void pwm_init()
{
    TRISC=0X00;
    CCP1CON=0X0C;
    PR2=96;
    TMR2=0;
    T2CON=0x7B;
    pwm_dutycycle(0);
    T2CON=0X7F;
}

void delay(unsigned int de) {   while(de--);    }

void main()
{
    pwm_init();
    while(1)
    {
        if(RB0) {   /*delay(100);*/ pwm_dutycycle(0);   }
        if(RB1) {   /*delay(100);*/ pwm_dutycycle(64);  }
        if(RB2) {   /*delay(100);*/ pwm_dutycycle(128); }
        if(RB3) {   /*delay(100);*/ pwm_dutycycle(255); }
    }   
} 

 

Result :

 


Next :

previous :


 

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

ESP8266 NodeMCU Interface – MCP23008

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

Read more: ESP8266 NodeMCU Interface – MCP23008

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

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

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

Required

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

MCP23008 with LED Interface

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

-- Constant device address.
local MCP23008_ADDRESS = 0x20

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

-- Default value for i2c communication
local id = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Explanation

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

MCP23008 with Buttons Interface

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

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

-- Constant device address.
local MCP23008_ADDRESS = 0x20

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

-- Default value for i2c communication
local id = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Explanation

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

Next

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

ESP8266 NodeMCU Interface – MCP23017

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

Read more: ESP8266 NodeMCU Interface – MCP23017

MCP23017 with LED Interface

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

MCP23017 lua Module code

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

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

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

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

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

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

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

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

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

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

Code Explanation

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

Uses

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

Specifically, the code accomplishes the following tasks:

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

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

NEXT

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