echo '' ;

Archives

ESP8266 NodeMCU Interface – MCP23008

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

Read more: ESP8266 NodeMCU Interface – MCP23008

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

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

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

Required

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

MCP23008 with LED Interface

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

-- Constant device address.
local MCP23008_ADDRESS = 0x20

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

-- Default value for i2c communication
local id = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Explanation

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

MCP23008 with Buttons Interface

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

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

-- Constant device address.
local MCP23008_ADDRESS = 0x20

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

-- Default value for i2c communication
local id = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Explanation

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

Next

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

ESP8266 NodeMCU Interface – MCP23017

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

Read more: ESP8266 NodeMCU Interface – MCP23017

MCP23017 with LED Interface

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

MCP23017 lua Module code

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

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

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

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

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

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

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

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

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

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

Code Explanation

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

Uses

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

Specifically, the code accomplishes the following tasks:

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

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

NEXT

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

ESP8266 NodeMCU Interface – LCD

The ESP8266 NodeMCU Interface with LCD allows you to integrate an LCD with your NodeMCU board, enabling you to create projects with visual feedback.

Read more: ESP8266 NodeMCU Interface – LCD

LCD 16×2 HD44780 Display Interface

  • We can easily add a 2×16 LCD to ESP8266.
  • But ESP8266 has less GPIO pins.
  • Two methods.
    • Using i2c driver
    • Using GPIO pins.

Code

This code provides basic functionality for interfacing with a 16×2 HD44780 LCD using an ESP8266 NodeMCU board. Adjustments may be needed based on your specific hardware setup and requirements.

-- Define GPIO pins for LCD connections
local PIN_RS = 1    -- GPIO5
local PIN_EN = 2    -- GPIO4
local PIN_D4 = 3    -- GPIO0
local PIN_D5 = 4    -- GPIO2
local PIN_D6 = 5    -- GPIO14
local PIN_D7 = 6    -- GPIO12

-- Function to send a command to LCD
local function lcd_command(cmd)
    gpio.write(PIN_RS, gpio.LOW)   -- Set RS pin LOW for command mode
    -- Send high nibble
    gpio.write(PIN_D4, bit.isset(cmd, 4) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D5, bit.isset(cmd, 5) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D6, bit.isset(cmd, 6) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D7, bit.isset(cmd, 7) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_EN, gpio.HIGH)
    gpio.write(PIN_EN, gpio.LOW)
    -- Send low nibble
    gpio.write(PIN_D4, bit.isset(cmd, 0) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D5, bit.isset(cmd, 1) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D6, bit.isset(cmd, 2) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D7, bit.isset(cmd, 3) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_EN, gpio.HIGH)
    gpio.write(PIN_EN, gpio.LOW)
    -- Delay for command execution
    tmr.delay(2000)  -- Adjust delay as needed
end

-- Function to send data to LCD
local function lcd_data(data)
    gpio.write(PIN_RS, gpio.HIGH)  -- Set RS pin HIGH for data mode
    -- Send high nibble
    gpio.write(PIN_D4, bit.isset(data, 4) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D5, bit.isset(data, 5) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D6, bit.isset(data, 6) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D7, bit.isset(data, 7) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_EN, gpio.HIGH)
    gpio.write(PIN_EN, gpio.LOW)
    -- Send low nibble
    gpio.write(PIN_D4, bit.isset(data, 0) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D5, bit.isset(data, 1) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D6, bit.isset(data, 2) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_D7, bit.isset(data, 3) and gpio.HIGH or gpio.LOW)
    gpio.write(PIN_EN, gpio.HIGH)
    gpio.write(PIN_EN, gpio.LOW)
    -- Delay for data transfer
    tmr.delay(2000)  -- Adjust delay as needed
end

-- Function to initialize the LCD
local function lcd_init()
    -- Set GPIO pins as outputs
    gpio.mode(PIN_RS, gpio.OUTPUT)
    gpio.mode(PIN_EN, gpio.OUTPUT)
    gpio.mode(PIN_D4, gpio.OUTPUT)
    gpio.mode(PIN_D5, gpio.OUTPUT)
    gpio.mode(PIN_D6, gpio.OUTPUT)
    gpio.mode(PIN_D7, gpio.OUTPUT)
    
    -- Initialization sequence
    tmr.delay(15000)  -- Wait for power-up
    lcd_command(0x33) -- Initialize
    lcd_command(0x32) -- Set to 4-bit mode
    lcd_command(0x28) -- 2 lines, 5x8 font
    lcd_command(0x0C) -- Display on, cursor off, blink off
    lcd_command(0x01) -- Clear display
    lcd_command(0x06) -- Increment cursor
end

-- Function to clear the LCD
local function lcd_clear()
    lcd_command(0x01) -- Clear display
end

-- Function to set cursor position
local function lcd_set_cursor(row, col)
    local offset = {0x00, 0x40}
    lcd_command(0x80 + offset[row] + col - 1)
end

-- Function to write a string to the LCD
local function lcd_write_string(str)
    for i = 1, #str do
        lcd_data(string.byte(str, i))
    end
end

-- Example usage
lcd_init()  -- Initialize the LCD
lcd_clear() -- Clear the LCD
lcd_set_cursor(1, 1) -- Set cursor to first row, first column
lcd_write_string("Hello, World!") -- Write a string to the LCD

Code Explanation

SectionExplanation
Initialization– The code initializes the LCD module by setting up the GPIO pins for communication and configuring the LCD settings.
Function Definitions– Defines helper functions for sending commands and data to the LCD, such as lcd_send_command and lcd_send_data. These functions handle the low-level communication with the LCD module.
LCD Initialization– Initializes the LCD by sending a sequence of commands to configure its display settings, such as the number of lines, cursor behavior, and display on/off settings.
Clearing the Display– Sends a command to clear the display and return the cursor to the home position.
Setting Cursor– Sets the cursor position on the LCD. The lcd_set_cursor function takes the row and column numbers as parameters and calculates the corresponding position based on the LCD’s row length.
Writing Characters– Writes characters to the LCD at the current cursor position. The lcd_write_char function sends data to the LCD to display the specified character.
Writing Strings– Writes strings to the LCD. The lcd_write_string function iterates over each character in the string and calls lcd_write_char to display them sequentially.
Main Function– Demonstrates how to use the defined functions to interact with the LCD. It initializes the LCD, clears the display, sets the cursor to the first position, and writes a string to the LCD.

Nokia-5110 PCD8544 Display interface

  • Required NodeMCU Modules (Firmware): GPIO Module
  • Required hardware: ESP8266 with Programmer (or)  NodeMCU Dev Kit, Nokia 5110 PCD8544 LCD Display,
  • Required software tools: ESPlorer IDE Tool

Code

`lua
-- https://www.aruneworld.com/embedded/esp8266/esp8266-nodemcu/
-- Tested By : Arun(20170212)
-- Example Name : AEW_LCD_Nokia-5110_PCD8544.lua
-- Reference data sheet: https://www.sparkfun.com/datasheets/LCD/Monochrome/Nokia5110.pdf

--------------------------------------------------------------------------------
-- The following code referred by this post: http://playground.arduino.cc/Code/PCD8544
-- You need to configure the pins you are using here
PIN_RESET = 0
PIN_SCE = 1
PIN_DC = 2
PIN_SDIN = 3
PIN_SCLK = 4

local LCD_D = gpio.HIGH
local LCD_C = gpio.LOW
local LCD_X = 84
local LCD_Y = 48

local chars = "\0\0\0\0\0\0\0\95\0\0\0\7\0\7\0\20\127\20\127\20\36\42\127\42\18\35\19\8\100\98\54\73\85\34\80\0\5\3\0\0\0\28\34\65\0\0\65\34\28\0\20\8\62\8\20\8\8\62\8\8\0\80\48\0\0\8\8\8\8\8\0\96\96\0\0\32\16\8\4\2\62\81\73\69\62\0\66\127\64\0\66\97\81\73\70\33\65\69\75\49\24\20\18\127\16\39\69\69\69\57\60\74\73\73\48\1\113\9\5\3\54\73\73\73\54\6\73\73\41\30\0\54\54\0\0\0\86\54\0\0\8\20\34\65\0\20\20\20\20\20\0\65\34\20\8\2\1\81\9\6\50\73\121\65\62\126\17\17\17\126\127\73\73\73\54\62\65\65\65\34\127\65\65\34\28\127\73\73\73\65\127\9\9\9\1\62\65\73\73\122\127\8\8\8\127\0\65\127\65\0\32\64\65\63\1\127\8\20\34\65\127\64\64\64\64\127\2\12\2\127\127\4\8\16\127\62\65\65\65\62\127\9\9\9\6\62\65\81\33\94\127\9\25\41\70\70\73\73\73\49\1\1\127\1\1\63\64\64\64\63\31\32\64\32\31\63\64\56\64\63\99\20\8\20\99\7\8\112\8\7\97\81\73\69\67\0\127\65\65\0\2\4\8\16\32\0\65\65\127\0\4\2\1\2\4\64\64\64\64\64\0\1\2\4\0\32\84\84\84\120\127\72\68\68\56\56\68\68\68\32\56\68\68\72\127\56\84\84\84\24\8\126\9\1\2\12\82\82\82\62\127\8\4\4\120\0\68\125\64\0\32\64\68\61\0\127\16\40\68\0\0\65\127\64\0\124\4\24\4\120\124\8\4\4\120\56\68\68\68\56\124\20\20\20\8\8\20\20\24\124\124\8\4\4\8\72\84\84\84\32\4\63\68\64\32\60\64\64\32\124\28\32\64\32\28\60\64\48\64\60\68\40\16\40\68\12\80\80\80\60\68\100\84\76\68\0\8\54\65\0\0\0\127\0\0\0\65\54\8\0\16\8\8\16\8\120\70\65\70\120"

local function shiftOut(d, cl, data)
    for index = 0, 7 do
        if bit.isset(data, 7 - index) then
            gpio.write(d, gpio.HIGH)
        else
            gpio.write(d, gpio.LOW)
        end
        gpio.write(cl, gpio.HIGH)
        tmr.delay(5)
        gpio.write(cl, gpio.LOW)
    end
end

local function LCDWrite(dc, data)
    gpio.write(PIN_DC, dc)
    gpio.write(PIN_SCE, gpio.LOW)
    shiftOut(PIN_SDIN, PIN_SCLK, data)
    gpio.write(PIN_SCE, gpio.HIGH)
end

function LcdSetPins(sclk, sdin, dc, sce, reset)
    PIN_SCLK = sclk
    PIN_SDIN = sdin
    PIN_DC = dc
    PIN_SCE = sce
    PIN_RESET = reset
end

function LcdLocate(x, y)
    LCDWrite(LCD_C, 64 + x)
    LCDWrite(LCD_C, 128 + y)
end

function LcdCharacter(character)
    LCDWrite(LCD_D, 0x00)
    for index = 0, 5 do
        LCDWrite(LCD_D, character)
    end
    LCDWrite(LCD_D, 0x00)
end

function LcdClear()
    local c = 84 * 6
    for index = 0, c do
        tmr.delay(5)
        LCDWrite(LCD_D, 0)
    end
end

function LcdPrintChar(c)
    LCDWrite(LCD_D, 0)
    local char_index = 1 + (string.byte(c) - 32) * 5
    for index = 0, 4 do
        LCDWrite(L

Code Explanation

This Lua code initializes and interacts with a Nokia 5110 LCD module (PCD8544 controller) using an ESP8266 NodeMCU board. The code provides a basic framework for interfacing with the Nokia 5110 LCD module using the ESP8266 NodeMCU board, allowing for the display of text and basic graphics. Here’s the explanation:

SectionExplanation
Initialization and Pins– Pins for interfacing with the LCD module are configured (RESET, SCE, DC, SDIN, SCLK).
– References and credits are provided in the comments.
LCD Character Data– Character data for the LCD is defined in the chars variable. Each character is represented by a series of bytes.
Shift Out Function– Sends data to the LCD module by shifting bits out through a specified pin.
LCD Write Function– Writes data to the LCD. Sets the appropriate data/command mode and then uses shiftOut to send the data.
Setting Pin Configuration– Allows setting the pins used for communication with the LCD dynamically.
LCD Cursor Positioning– Positions the cursor at the specified coordinates on the LCD.
Writing a Character– Writes a single character to the LCD at the current cursor position.
Clearing the LCD– Clears the entire LCD display.
Printing a Character– Prints a character to the LCD, advancing the cursor position accordingly.
Initialization– Initializes the LCD module with the appropriate settings.
Test Function– A test function that initializes the LCD and prints some sample text.

Next

ESP8266 NodeMCU Interface – LCD

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

LED ON/OFF

Note : Assume the pin GPIO-5 is a LED (NodeMCU pin map is 1)

  • Set LED Mode
    • Set LED pin (gpio-5) as output using gpio.mode(pin, mode [, pullup])  function.
    • Example :  gpio.mode(1, gpio.OUTPUT)
  • Turn LED ON
    • Set LED pin (gpio-5) HIGH using gpio.write(pin, level)  function.
    • Example : gpio.write(1, gpio.HIGH)  or gpio.write(1, 1)
  • Turn LED  OFF
    • Set LED pin (gpio-5) Low using gpio.write(pin, level)  function.
    • Example : gpio.write(1, gpio.LOW) or gpio.write(1,0)

 


LED Blink Using Timer

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

ESP8266 with LED Connection Diagram

  • Will Add Soon

NodeMCU Lua code

-- http://www.ArunEworld.com/embedded/ESPressif/ESP8266/ESP82266_NodeMCU
--[[ Required NodeMCU Modules
 Timer Module
 GPIO Module
]]--

LED_Pin = 1 -- GPIO-5
LED_Blink_Time = 1000 -- ms
gpio.mode(LED_Pin, gpio.OUTPUT)
local function Blink()
 if ( 0 == gpio.read(LED_Pin)) then 
  gpio.write(LED_Pin, gpio.HIGH)
 elseif( 1 == gpio.read(LED_Pin)) then 
  gpio.write(LED_Pin, gpio.LOW)
 end 
end

tmr.alarm(0,LED_Blink_Time,1,function() Blink() end)

Follow steps

  • Connect the circuit as per the connection diagram
  • Save the above code as “AEW_LED-Blink.lua”
  • Open ESPlorer and upload the file “AEW_LED-Blink.lua”
  • Run the file  [ dofile(“AEW_LED-Blink.lua”) ]
  • Done.!(LED will Blink based on blink time)

LED Blink uisng While loop and Timer delay function

  • Use
    -- http://www.ArunEworld.com/embedded/ESPressif/ESP8266/ESP82266_NodeMCU 
    --[[ Required NodeMCU Modules Timer Module GPIO Module ]]--
    LED_Pin = 1 -- GPIO-5
    LED_Blink_Time = 1000 -- ms
    gpio.mode(LED_Pin, gpio.OUTPUT)
    
    while true do
        tmr.delay(1000000)
        if ( 0 == gpio.read(LED_Pin)) then
            gpio.write(LED_Pin, gpio.HIGH) 
        elseif( 1 == gpio.read(LED_Pin)) then
            gpio.write(LED_Pin, gpio.LOW)
        end
    end
    

     


LED Fade using PWM

  • Use this code
    pin = 1
    ------ PWM setup --------------
    pwm.setup(pin, 999, 512)    -- pwm.setup(pin, clock, duty) | set pin index 1 as pwm output, frequency is 100Hz, duty cycle is half.
    
    pwm.start(pin)          -- pwm.start(pin)
    duty = 1000
    
    for i=1000,0,-1 do
     --print(i)
     duty = i
     pwm.setduty(pin, duty)         -- pwm.setduty(pin, duty)
     tmr.delay(1000)
    end
    

     


 

 


Next :

Previous :


 

ESP8266 NodeMCU Project – Imperial March Ringtone Play


Playing the Imperial March ringtone on an ESP8266 NodeMCU involves using the NodeMCU’s capabilities to generate sound or control an external sound module. One common method is using a piezo buzzer to generate tones. Here’s a basic example of “ESP8266 Imperial March Ringtone play” using the NodeMCU and a piezo buzzer to play the Imperial March:

Read more… →

ESP8266 NodeMCU Tutorial – Web Server

The ESP8266 NodeMCU Tutorial – Web Server provides a comprehensive guide on how to set up a web server using the NodeMCU development board powered by the ESP8266 microcontroller.

Read more: ESP8266 NodeMCU Tutorial – Web Server

Simple Web Server

  • Simple web server display heap, ip, mac address some other details ..
  • First need to connect ESP8266 with WiFi Router. then access the web server using ip address
print("****** Wifi data's Initializing *********")
mode = wifi.STATION
ssid = "ArunEworld"
password = "Arun"

print("****** Setup Wifi Settings *********")
wifi.setmode(mode)
wifi.sta.config(ssid, password)

function Wif_Connect()
    WC = wifi.sta.status() --WC Wifi_Connect
    print("Wifi Status is : " .. WC)

    if WC == 0 then
        print("0.Satation is Idle ??")
        wifi.sta.autoconnect(auto)
    elseif WC == 1 then
        print("1.Satation Connecting....Wait a moment")
    elseif WC == 2 then
        print("2.password is wrong !")
    elseif WC == 3 then
        print("3.No Access Point Found !")
    elseif WC == 4 then
        print("4.Station connecting fail !")
    elseif WC == 5 then
        print("IP :" .. wifi.sta.getip())
        tmr.stop(0)
        -- dofile("AEW_Webserver.lua")
        -- print("IP :"..wifi.sta.getip())
        -- dofile("File_name.lua")
        -- please write your file name
    end
end

print("**** Webserver Running........ ****")
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
    conn:on("receive", function(client, request)
        buf = buf .. "<h1>Arun Eworld</h1>"
        buf = buf .. "Chip ID :<b>" .. node.chipid() .. "</b><BR>"
        --[[ 
        buf = buf.."Heap :<b>".. node.heap() .. "</b><BR>";
        buf = buf.."Station Mac Address :<b>".. wifi.sta.getmac() .. "</b><BR>";
        buf = buf.."AP Mac Address :<b>".. wifi.ap.getmac() .. "</b><BR>";
        buf = buf.."GetMode :<b>".. wifi.getmode() .. "</b><BR>";
        buf = buf.."Status :<b>".. wifi.sta.status() .. "</b><BR>";
        --buf = buf.."AP IP Address :<b>".. wifi.ap.getip() .. "</b><BR>";
        buf = buf.."Station IP Address :<b>".. wifi.sta.getip() .. "</b><BR>";
        buf = buf.."TMR.NOW :<b>" .. tmr.now() .. "</b><BR<BR><BR>";
        ]]--
        client:send(buf)
        client:close()
        collectgarbage()
    end)
end)

tmr.alarm(0, 5000, 1, Wif_Connect)

Code Explanation

Sure, here’s an explanation of the provided Lua code:

  1. Wifi Initialization:
    • The code begins by printing a message indicating the initialization of WiFi data.
    • It sets the WiFi mode to Station mode.
    • Defines the SSID and password for the WiFi connection.
  2. WiFi Connection Function (Wif_Connect):
    • This function is responsible for handling the WiFi connection process.
    • It retrieves the current WiFi connection status using wifi.sta.status().
    • Depending on the status, it performs different actions:
      • If the status is 0, it indicates that the station is idle, and it attempts to autoconnect.
      • If the status is 1, it indicates that the station is connecting.
      • If the status is 2, it indicates that the password is incorrect.
      • If the status is 3, it indicates that no Access Point (AP) is found.
      • If the status is 4, it indicates that the connection to the AP failed.
      • If the status is 5, it indicates a successful connection, and it prints the assigned IP address.
        • It also stops the timer (tmr.stop(0)), which triggers the connection attempt.
  3. Webserver Setup:
    • The code prints a message indicating that the web server is running.
    • It creates a TCP server (srv) that listens on port 80.
    • Upon receiving a connection, it defines a callback function to handle incoming requests.
    • The callback function constructs an HTML response (buf) containing the header <h1>Arun Eworld</h1> and the chip ID.
    • The response is sent back to the client, and the connection is closed.
  4. Timer Initialization:
    • A timer (tmr) is set to call the Wif_Connect function every 5 seconds (tmr.alarm(0, 5000, 1, Wif_Connect)).

This code initializes the WiFi connection, continuously attempts to connect to the configured network, and sets up a basic web server to handle incoming requests. (ESP8266 NodeMCU Tutorial Web Server)

TCP Server Listener

This code given below will configure the ESP to act as an Access Point and it has its own SSID=”ArunEworld” and Password=”Arun” and also act as the server which will continuously listen for a connection.

Code

This code initializes the ESP8266 module as an access point with the SSID “ArunEworld” and password “Arun”. It then creates a TCP server that listens on port 80. When a connection is established, it prints any received data and releases resources after sending a response.

print("ArunEworld - ESP8266 Server")
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="ArunEworld", pwd="Arun"})
print("Server IP Address:", wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(80, function(conn)
    conn:on("receive", function(conn, receivedData)
        print("Received Data: " .. receivedData)
    end)
    conn:on("sent", function(conn)
        collectgarbage()
    end)
end)

Result

Host pot


Code Explanation

This code initializes the ESP8266 module as an access point with the SSID “ArunEworld” and password “Arun”, creates a TCP server listening on port 80, and defines callback functions to handle received and sent data.

LineCodeExplanation
1print("ArunEworld - ESP8266 Server")Prints a message indicating the initialization of the ESP8266 server.
2wifi.setmode(wifi.STATIONAP)Sets the mode of the WiFi module to STATIONAP, enabling it to function as both a station and an access point.
3wifi.ap.config({ssid="ArunEworld", pwd="Arun"})Configures the access point with the SSID “ArunEworld” and password “Arun”.
4print("Server IP Address:", wifi.ap.getip())Prints the IP address assigned to the ESP8266 access point.
6sv = net.createServer(net.TCP)Creates a TCP server object.
7sv:listen(80, function(conn)Starts the server and listens for connections on port 80.
8conn:on("receive", function(conn, receivedData)Sets up a callback function to handle received data.
9print("Received Data: " .. receivedData)Prints the received data.
10end)Ends the “receive” callback function definition.
11conn:on("sent", function(conn)Sets up a callback function to handle data sent.
12collectgarbage()Collects garbage to free up memory.
13end)Ends the “sent” callback function definition.
14end)Ends the server callback function definition.

NEXT

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

ESP8266 NodeMCU Module – WiFi (End User Module)

Welcome to the ESP8266 NodeMCU WiFi End User Module! The ESP8266 NodeMCU is a versatile and powerful microcontroller board that features built-in WiFi connectivity. This module aims to offer a user-friendly platform for IoT (Internet of Things) projects, facilitating the connection of devices to the Internet and enabling remote interaction with them.

With the ESP8266 NodeMCU, you can quickly prototype and deploy WiFi-enabled projects without the need for extensive hardware or networking expertise. Whether you’re a hobbyist, maker, or professional developer, this module offers a convenient solution for adding wireless connectivity to your applications.

Read more: ESP8266 NodeMCU Module – WiFi (End User Module)

WiFi NodeMCU Lua Module

In this module, we’ll explore the capabilities of the ESP8266 NodeMCU, learn how to configure WiFi settings, connect to wireless networks, and develop IoT applications. By the end of this module, you’ll have the knowledge and skills to create your own WiFi-enabled projects using the ESP8266 NodeMCU.

Let’s dive into the world of WiFi and IoT with the ESP8266 NodeMCU End User Module!

This table provides a comprehensive overview of the various functions available for configuring and interacting with WiFi on the ESP8266 module.

Note: ESP8266 does not support numbers as passwords in NodeMCU firmware

General Functions:

FunctionDescription
wifi.getchannel()Gets the current WiFi channel.
wifi.getdefaultmode()Gets default WiFi operation mode.
wifi.getmode()Gets WiFi operation mode.
wifi.getphymode()Gets WiFi physical mode.
wifi.nullmodesleep()Configures whether or not WiFi automatically goes to sleep in NULL_MODE.
wifi.resume()Wake up WiFi from suspended state or cancel pending wifi suspension.
wifi.setmode()Configures the WiFi mode to use.
wifi.setphymode()Sets WiFi physical mode.
wifi.startsmart()Starts auto configuration, if successful sets up SSID and password automatically.
wifi.stopsmart()Stops the smart configuring process.
wifi.suspend()Suspend Wifi to reduce current consumption.
wifi.eventmon.register()Register/unregister callbacks for WiFi event monitor.
wifi.eventmon.unregister()Unregister callbacks for WiFi event monitor.
wifi.eventmon.reasonTable containing disconnect reasons.

Station Functions:

FunctionDescription
wifi.sta.autoconnect()Auto connects to AP in station mode.
wifi.sta.changeap()Select Access Point from list returned by wifi.
wifi.sta.clearconfig()Clears the currently saved WiFi station configuration, erasing it from the flash.
wifi.sta.config()Sets the WiFi station configuration.
wifi.sta.connect()Connects to the configured AP in station mode.
wifi.sta.disconnect()Disconnects from AP in station mode.
wifi.sta.eventMonReg()Registers callbacks for WiFi station status events.
wifi.sta.eventMonStart()Starts WiFi station event monitor.
wifi.sta.eventMonStop()Stops WiFi station event monitor.
wifi.sta.getap()Scans AP list as a Lua table into callback function.
wifi.sta.getapindex()Get index of current Access Point stored in AP cache.
wifi.sta.getapinfo()Get information of APs cached by ESP8266 station.
wifi.sta.getbroadcast()Gets the broadcast address in station mode.
wifi.sta.getconfig()Gets the WiFi station configuration.
wifi.sta.getdefaultconfig()Gets the default WiFi station configuration stored in flash.
wifi.sta.gethostname()Gets current station hostname.
wifi.sta.getip()Gets IP address, netmask, and gateway address in station mode.
wifi.sta.getmac()Gets MAC address in station mode.
wifi.sta.getrssi()Gets the RSSI (Received Signal Strength Indicator) of the Access Point which ESP8266 station connected to.
wifi.sta.setaplimit()Set Maximum number of Access Points to store in flash.
wifi.sta.sethostname()Sets station hostname.
wifi.sta.setip()Sets IP address, netmask, gateway address in station mode.
wifi.sta.setmac()Sets MAC address in station mode.
wifi.sta.sleeptype()Configures the WiFi modem sleep type to be used while station is connected to an Access Point.
wifi.sta.status()Gets the current status in station mode.

Access Point Functions:

FunctionDescription
wifi.ap.config()Sets SSID and password in AP mode.
wifi.ap.deauth()Deauths (forcibly removes) a client from the ESP access point by sending a corresponding IEEE802.
wifi.ap.getbroadcast()Gets broadcast address in AP mode.
wifi.ap.getclient()Gets table of clients connected to device in AP mode.
wifi.ap.getconfig()Gets the current SoftAP configuration.
wifi.ap.getdefaultconfig()Gets the default SoftAP configuration stored in flash.
wifi.ap.getip()Gets IP address, netmask and gateway in AP mode.
wifi.ap.getmac()Gets MAC address in AP mode.
wifi.ap.setip()Sets IP address, netmask and gateway address in AP mode.
wifi.ap.setmac()Sets MAC address in AP mode.
wifi.ap.dhcp.config()Configure the DHCP service.
wifi.ap.dhcp.start()Starts the DHCP service.
wifi.ap.dhcp.stop()Stops the DHCP service.
wifi.eventmon.register()Register/unregister callbacks for WiFi event monitor.
wifi.eventmon.unregister()Unregister callbacks for

Examples

Scan for available all station networks

  • Scans AP list as a Lua table into callback function. wifi.sta.getap()

This Lua code includes various functions related to scanning and retrieving information about available WiFi access points (APs) and their configurations. Each function defines itself separately for different purposes and formats itself for readability.

-- Print AP list in old format (format not defined)
function listap(t)
    for k, v in pairs(t) do
        print(k .. " : " .. v)
    end
end

wifi.sta.getap(listap)

-- Print AP list that is easier to read
function listap(t)
    -- (SSID : Authmode, RSSI, BSSID, Channel)
    print("\n" .. string.format("%32s", "SSID") .. "\tBSSID\t\t\t\t RSSI\t\tAUTHMODE\tCHANNEL")
    for ssid, v in pairs(t) do
        local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)")
        print(string.format("%32s", ssid) .. "\t" .. bssid .. "\t " .. rssi .. "\t\t" .. authmode .. "\t\t\t" .. channel)
    end
end

wifi.sta.getap(listap)

-- Print AP list in new format
function listap(t)
    for k, v in pairs(t) do
        print(k .. " : " .. v)
    end
end

wifi.sta.getap(1, listap)

-- Print AP list that is easier to read
function listap(t)
    -- (SSID : Authmode, RSSI, BSSID, Channel)
    print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\t RSSI\t\tAUTHMODE\t\tCHANNEL")
    for bssid, v in pairs(t) do
        local ssid, rssi, authmode, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]*)")
        print(string.format("%32s", ssid) .. "\t" .. bssid .. "\t " .. rssi .. "\t\t" .. authmode .. "\t\t\t" .. channel)
    end
end

wifi.sta.getap(1, listap)

-- Check for specific AP
function listap(t)
    print("\n\t\t\tSSID\t\t\t\t\tBSSID\t\t\t RSSI\t\tAUTHMODE\t\tCHANNEL")
    for bssid, v in pairs(t) do
        local ssid, rssi, authmode, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]*)")
        print(string.format("%32s", ssid) .. "\t" .. bssid .. "\t " .. rssi .. "\t\t" .. authmode .. "\t\t\t" .. channel)
    end
end

scan_cfg = {}
scan_cfg.ssid = "myssid"
scan_cfg.bssid = "AA:AA:AA:AA:AA:AA"
scan_cfg.channel = 0
scan_cfg.show_hidden = 1

wifi.sta.getap(scan_cfg, 1, listap)

-- Get RSSI for currently configured AP
function listap(t)
    for bssid, v in pairs(t) do
        local ssid, rssi, authmode, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]*)")
        print("CURRENT RSSI IS: " .. rssi)
    end
end

ssid, tmp, bssid_set, bssid = wifi.sta.getconfig()

scan_cfg = {}
scan_cfg.ssid = ssid

if bssid_set == 1 then
    scan_cfg.bssid = bssid
else
    scan_cfg.bssid = nil
end

scan_cfg.channel = wifi.getchannel()
scan_cfg.show_hidden = 0

ssid, tmp, bssid_set, bssid = nil, nil, nil, nil

wifi.sta.getap(scan_cfg, 1, listap)

Sets the WiFi station configuration.

This Lua code demonstrates various configurations for connecting the ESP8266 to an access point (AP) using the wifi.sta.config() function. You can choose whether to save the configuration to flash memory, specify a MAC address for the AP, or configure the station without immediately connecting to an AP.

-- Connect to Access Point (DO NOT save config to flash)
station_cfg = {}
station_cfg.ssid = "NODE-AABBCC"
station_cfg.pwd = "password"
wifi.sta.config(station_cfg)

-- Connect to Access Point (DO save config to flash)
station_cfg = {}
station_cfg.ssid = "NODE-AABBCC"
station_cfg.pwd = "password"
station_cfg.save = true
wifi.sta.config(station_cfg)

-- Connect to Access Point with specific MAC address
station_cfg = {}
station_cfg.ssid = "NODE-AABBCC"
station_cfg.pwd = "password"
station_cfg.bssid = "AA:BB:CC:DD:EE:FF"
wifi.sta.config(station_cfg)

-- Configure station but don't connect to Access point
station_cfg = {}
station_cfg.ssid = "NODE-AABBCC"
station_cfg.pwd = "password"
station_cfg.auto = false
wifi.sta.config(station_cfg)

Connect ESP8266 to WiFi Router

This Lua code initializes the WiFi module, sets it to both station and access point mode, and then connects to a specified access point with the provided SSID and password without saving the configuration to flash memory.

print("wifi init")
wifi.set.mode(wifi.STATIONAP)

-- Connect to Access Point (DO NOT save config to flash)
station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "Arun"
wifi.sta.config(station_cfg)
wifi.sta.connect()

Disconnect ESP8266 from WiFi Router

  • Disconnects from AP in station mode. wifi.sta.disconnect()

View the ESP8266 Stored Access Point information

  • Retrieve information about the Access Points cached by the ESP8266 station using the function wifi.sta.getapinfo().

This Lua code prints the stored access point information obtained from the ESP8266 module in both a non-formatted and formatted manner.

-- Print stored access point info
do
    for k, v in pairs(wifi.sta.getapinfo()) do
        if (type(v) == "table") then
            print(" " .. k .. " : " .. type(v))
            for k, v in pairs(v) do
                print("\t\t" .. k .. " : " .. v)
            end
        else
            print(" " .. k .. " : " .. v)
        end
    end
end

-- Print stored access point info (formatted)
do
    local x = wifi.sta.getapinfo()
    local y = wifi.sta.getapindex()
    print("\n Number of APs stored in flash:", x.qty)
    print(string.format(" %-6s %-32s %-64s %-18s", "index:", "SSID:", "Password:", "BSSID:"))
    for i = 1, x.qty, 1 do
        print(string.format(" %s%-6d %-32s %-64s %-18s", (i == y and ">" or " "), i, x[i].ssid, x[i].pwd and x[i].pwd or type(nil), x[i].bssid and x[i].bssid or type(nil)))
    end
end

Gets the WiFi station configuration.

This Lua code retrieves and prints the current station configuration of the ESP8266 module, both in new and old formats. It displays the SSID, password, and BSSID settings if available.

-- Get current Station configuration (NEW FORMAT)
do
    local def_sta_config = wifi.sta.getconfig(true)
    print(string.format("\tDefault station config\n\tssid:\"%s\"\tpassword:\"%s\"%s",
        def_sta_config.ssid, def_sta_config.pwd,
        (type(def_sta_config.bssid) == "string" and "\tbssid:\"" .. def_sta_config.bssid .. "\"" or "")))
end

-- Get current Station configuration (OLD FORMAT)
ssid, password, bssid_set, bssid = wifi.sta.getconfig()
print("\nCurrent Station configuration:\nSSID : " .. ssid .. "\nPassword : " .. password ..
    "\nBSSID_set : " .. bssid_set .. "\nBSSID: " .. bssid .. "\n")
ssid, password, bssid_set, bssid = nil, nil, nil, nil

Clears the currently saved WiFi station configuration

  • Clears the currently saved WiFi station configuration, erasing it from the flash. This action may be useful for certain factory-reset scenarios when a full node.restore() is not desired, or to prepare for using End-User Setup so that the SoftAP can lock onto a single hardware radio channel.
  • Ex : wifi.sta.clearconfig()

WiFi station status events

This Lua code registers event callbacks for various WiFi states, starts and stops the WiFi event monitor with different intervals, and unregisters callbacks as needed.

-- Register callbacks
wifi.sta.eventMonReg(wifi.STA_IDLE, function() print("STATION_IDLE") end)
wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print("STATION_CONNECTING") end)
wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() print("STATION_WRONG_PASSWORD") end)
wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() print("STATION_NO_AP_FOUND") end)
wifi.sta.eventMonReg(wifi.STA_FAIL, function() print("STATION_CONNECT_FAIL") end)
wifi.sta.eventMonReg(wifi.STA_GOTIP, function() print("STATION_GOT_IP") end)

-- Register callback: use previous state
wifi.sta.eventMonReg(wifi.STA_CONNECTING, function(previous_State)
    if (previous_State == wifi.STA_GOTIP) then
        print("Station lost connection with access point\n\tAttempting to reconnect...")
    else
        print("STATION_CONNECTING")
    end
end)

-- Start WiFi event monitor with default interval
wifi.sta.eventMonStart()

-- Start WiFi event monitor with 100ms interval
wifi.sta.eventMonStart(100)

-- Stop WiFi event monitor
wifi.sta.eventMonStop()

-- Stop WiFi event monitor and unregister all callbacks
wifi.sta.eventMonStop(1)

-- Unregister callback
wifi.sta.eventMonReg(wifi.STA_IDLE)

Gets current station hostname.

  • Ex : print(“Current hostname is: \””..wifi.sta.gethostname()..”\””)

Sets station hostname.

This Lua code checks if the hostname was successfully changed using the wifi.sta.sethostname() function and prints the corresponding message.

if (wifi.sta.sethostname("ArunEworld") == true) then
    print("hostname was successfully changed")
else
    print("hostname was not changed")
end

Gets IP address, netmask, and gateway address in station mode.

This Lua code retrieves and prints the current IP address, netmask, and gateway information using the wifi.sta.getip() function. It demonstrates different ways to handle the returned values.

-- Print current IP address, netmask, gateway
print(wifi.sta.getip()) -- Output: 192.168.0.111 255.255.255.0 192.168.0.1

ip = wifi.sta.getip()
print(ip) -- Output: 192.168.0.111

ip, nm = wifi.sta.getip()
print(nm) -- Output: 255.255.255.0

Gets IP address, netmask and gateway in AP mode.

This Lua code retrieves and prints the current IP address, netmask, and gateway information for the Access Point (AP) mode using the wifi.ap.getip() function. It demonstrates different ways to handle the returned values.

-- Print current IP address, netmask, gateway
print(wifi.ap.getip()) -- Output: 192.168.4.1 255.255.255.0 192.168.4.1

ip = wifi.ap.getip()
print(ip) -- Output: 192.168.4.1

ip, nm = wifi.ap.getip()
print(nm) -- Output: 255.255.255.0

ip, nm, gw = wifi.ap.getip()
print(gw) -- Output: 192.168.4.1

Gets MAC address in station mode.

  • Ex : print(wifi.sta.getmac())

Set MAC address in AP mode.

  • Ex : print(wifi.ap.setmac())

Retrieve the RSSI (Received Signal Strength Indicator).

  • Retrieve the RSSI (Received Signal Strength Indicator) from the Access Point to which the ESP8266 station is currently connected.

RSSI=wifi.sta.getrssi() print(“RSSI is”, RSSI)

Retrieves a table of clients connected to the device in AP mode.

This Lua code retrieves the client MAC addresses and IPs connected to the Access Point (AP) and prints them. It demonstrates two ways to iterate over the table returned by wifi.ap.getclient().

-- Get client MAC addresses and IPs connected to the AP
table = wifi.ap.getclient()

-- Iterate over the table to print MAC addresses and IPs
for mac, ip in pairs(table) do
    print(mac, ip)
end

-- Alternatively, using a shorter loop syntax
for mac, ip in pairs(wifi.ap.getclient()) do
    print(mac, ip)
end

Gets the current SoftAP configuration.

This Lua code retrieves and prints the SoftAP configuration in both new and old formats. It demonstrates two different ways of handling the configuration data returned by wifi.ap.getconfig().

-- Get SoftAP configuration table (NEW FORMAT)
do
    print("\n Current SoftAP configuration:")
    for k, v in pairs(wifi.ap.getconfig(true)) do
        print(" "..k.." :", v)
    end
end

-- Get current SoftAP configuration (OLD FORMAT)
do
    local ssid, password = wifi.ap.getconfig()
    print("\n Current SoftAP configuration:\n SSID : "..ssid.. "\n Password :", password)
    ssid, password = nil, nil
end

Retrieve the default SoftAP configuration stored in flash.

This Lua code retrieves and prints the default SoftAP configuration in both new and old formats. It demonstrates two different ways of handling the configuration data returned by wifi.ap.getdefaultconfig().

-- Get default SoftAP configuration table (NEW FORMAT)
do
    print("\n Default SoftAP configuration:")
    for k, v in pairs(wifi.ap.getdefaultconfig(true)) do
        print(" "..k.." :", v)
    end
end

-- Get default SoftAP configuration (OLD FORMAT)
do
    local ssid, password = wifi.ap.getdefaultconfig()
    print("\n Default SoftAP configuration:\n SSID : "..ssid.. "\n Password :", password)
    ssid, password = nil, nil
end

End User Setup NodeMCU Lua

ESP8266 NodeMCU WiFi End User Module

FunctionDescription
enduser_setup.manual()Controls whether manual AP configuration is used.
enduser_setup.start()Starts the captive portal.
enduser_setup.stop()Stops the captive portal.

Example

This Lua code sets up the ESP8266 to operate in both station and access point modes, configures the access point with the SSID “ArunEworld” and no password (open authentication), enables manual end-user setup, and starts the setup process with callbacks for success and failure.

//Configure the End User Setup
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ ssid = "ArunEworld", auth = wifi.OPEN })

enduser_setup.manual(true)
enduser_setup.start(
    function()
        print("Connected to wifi as: " .. wifi.sta.getip())
        --enduser_setup.stop()
    end,
    function(err, str)
        print("enduser_setup: Err #" .. err .. ": " .. str)
    end
);

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

ESP32 NodeMCU Module – Net

The ESP32 NodeMCU Module is a versatile development board known for its robust capabilities in IoT projects. With built-in Wi-Fi and Bluetooth connectivity, it offers seamless integration into networked environments. Its compact size and powerful features make it a preferred choice for various IoT applications, from home automation to industrial monitoring. here will discuss ESP32 NodeMCU Net Module.

Read more: ESP32 NodeMCU Module – Net

Functions

FunctionDescription
net.createConnection()Creates a client.
net.createServer()Creates a server.
net.createUDPSocket()Creates a UDP socket.
net.multicastJoin()Joins a multicast group.
net.multicastLeave()Leaves a multicast group.
net.server:close()Closes the server.
net.server:listen()Listens on a port from an IP address.
net.server:getaddr()Returns the server’s local address and port.
net.socket:close()Closes a socket.
net.socket:connect()Connects to a remote server.
net.socket:dns()Provides DNS resolution for a hostname.
net.socket:getpeer()Retrieves the port and IP of the remote peer.
net.socket:getaddr()Retrieves the local port and IP of the socket.
net.socket:hold()Throttles data reception by placing a request to block the TCP receive function.
net.socket:on()Registers callback functions for specific events.
net.socket:send()Sends data to the remote peer.
net.socket:ttl()Changes or retrieves the Time-To-Live value on the socket.
net.socket:unhold()Unblocks TCP receiving data by revoking a preceding hold().
net.udpsocket:close()Closes a UDP socket.
net.udpsocket:listen()Listens on a port from an IP address.
net.udpsocket:on()Registers callback functions for specific events.
net.udpsocket:send()Sends data to a specific remote peer.
net.udpsocket:dns()Provides DNS resolution for a hostname.
net.udpsocket:getaddr()Retrieves the local port and IP of the socket.
net.udpsocket:ttl()Changes or retrieves the Time-To-Live value on the socket.
net.dns.getdnsserver()Gets the IP address of the DNS server used to resolve hostnames.
net.dns.resolve()Resolves a hostname to an IP address.
net.dns.setdnsserver()Sets the IP of the DNS server used to resolve hostnames.

Ex : Create a server Connection

The function net.createServer([type[, timeout]]) is used to create a server with an optional timeout parameter. When you specify a timeout value, it determines the duration for which the server will wait for activity from a client before considering it inactive and closing the connection.

For example, if you create a TCP server with a timeout of 30 seconds using

-- 30s time out for a inactive client
net.createServer(net.TCP, 30) -- 30s timeout

it means that if a client connects to this server but does not send any data within 30 seconds, the server will automatically close the connection to that client.

This timeout functionality is useful for managing server resources efficiently. It allows servers to automatically clean up inactive connections, preventing them from occupying resources indefinitely. In scenarios where maintaining active connections is crucial, such as in real-time communication applications, setting a timeout ensures that resources are available for active clients and that inactive ones do not unnecessarily consume server resources.

Ex : Receive function

function receiver(sck, data)
  print(data)
  sck:close()
end

Ex : Web server function

-- server listens on 80, if data received, print data to console and send "hello world" back to caller
if sv then
  sv:listen(80, function(conn)
    conn:on("receive", receiver)
    conn:send("Arunworld")
  end)
end

TCP Server Connection(Client)

here the code for ESP32 NodeMCU Net Module example

  • Connect the WiFi Station
  • Once got IP address then run Server_Run()  Function
  • Create a connection
  • Connect the server
  • Send the Data “ArunEwolrd IOT Project” to Server
print("wifi init")
wifi.start()
wifi.mode(wifi.STATION)
 
--connect to Access Point (DO NOT save config to flash)
station_cfg={}
station_cfg.ssid="ArunEwolrd"
station_cfg.pwd="Arun"
wifi.sta.config(station_cfg)
 
wifi.sta.connect()


function Server_Run()
print("Server Running")
    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)
    sck:send("ArunEworld IOT Projects")
    end)
    srv:connect(80,"192.168.4.1")
end


--register callback
wifi.sta.on("connected", function(ev, info)
    print("Connected to Router")
    print("NodeMCU IP Connected ssid", info.ssid, "bssid", info.bssid, "Channel", info.channel, "Auth", info.auth)
end)

--register callback
wifi.sta.on("disconnected", function(ev, info)
    print("disconnected to Router")
    print("NodeMCU Disconnected ssid", info.ssid, "bssid", info.bssid, "reason", info.reason)
end)

--register callback
wifi.sta.on("authmode_changed", function(ev, info)
print("authmode_changed in Router")
print("NodeMCU authmode_changed old_mode", info.old_mode, "new_mode", info.new_mode)
end)

--register callback
wifi.sta.on("got_ip", function(ev, info)
print("GOt IP")
  print("NodeMCU IP config:", info.ip, "netmask", info.netmask, "gw", info.gw)
  Server_Run()
end)

ESP32 NodeMCU Module – I2C Interface

The ESP32 NodeMCU module supports the I2C (Inter-Integrated Circuit) communication protocol. With its built-in hardware support for I2C, the ESP32 NodeMCU module can easily interface with various I2C devices such as sensors, displays, and other peripherals. This allows for efficient data exchange between the ESP32 and I2C devices, enabling a wide range of applications in IoT, robotics, automation, and more.

Read more: ESP32 NodeMCU Module – I2C Interface

Pr-Request to Lean


ESP32 NodeMCU Module I2C Functions

FunctionDescription
i2c.address()Send (SW) or queue (HWx) I²C address and read/write mode for the next transfer.
i2c.read()Read (SW) or queue (HWx) data for a variable number of bytes.
i2c.setup()Initialize the I²C interface for master mode.
i2c.start()Send (SW) or queue (HWx) an I²C start condition.
i2c.stop()Send (SW) or queue (HWx) an I²C stop condition.
i2c.transfer()Starts a transfer for the specified hardware module.
i2c.write()Write (SW) or queue (HWx) data to the I²C bus.
i2c.slave.on()Registers or unregisters an event callback handler.
i2c.slave.setup()Initialize the I²C interface for slave mode.
i2c.slave.send()Writes send data for the master into the transmit buffer.

Code of ESP32 I2C Scanner

  • In this code used to can the i2c Devices
  • Used Software i2c and GPIO-23 as SDA and GPIO-22 as SCL of I2C Device
  • Connected DS3231 Device and check i2c address of DS3231
-- setup
id  =   i2c.SW                      --  Software
pinSDA  =   23                      --  1~12, IO index
pinSCL  =   22                      --  1~12, IO index
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.
  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")

Results

Scanning Started....
Addrss - 0 nil
Addrss - 1 nil
Addrss - 2 nil
Addrss - 3 nil
Addrss - 4 nil
Addrss - 5 nil
Addrss - 6 nil
Addrss - 7 nil
Addrss - 8 nil
Addrss - 9 nil
Addrss - 10 nil
Addrss - 11 nil
Addrss - 12 nil
Addrss - 13 nil
Addrss - 14 nil
Addrss - 15 nil
Addrss - 16 nil
Addrss - 17 nil
Addrss - 18 nil
Addrss - 19 nil
Addrss - 20 nil
Addrss - 21 nil
Addrss - 22 nil
Addrss - 23 nil
Addrss - 24 nil
Addrss - 25 nil
Addrss - 26 nil
Addrss - 27 nil
Addrss - 28 nil
Addrss - 29 nil
Addrss - 30 nil
Addrss - 31 nil
Addrss - 32 nil
Addrss - 33 nil
Addrss - 34 nil
Addrss - 35 nil
Addrss - 36 nil
Addrss - 37 nil
Addrss - 38 nil
Addrss - 39 nil
Addrss - 40 nil
Addrss - 41 nil
Addrss - 42 nil
Addrss - 43 nil
Addrss - 44 nil
Addrss - 45 nil
Addrss - 46 nil
Addrss - 47 nil
Addrss - 48 nil
Addrss - 49 nil
Addrss - 50 nil
Addrss - 51 nil
Addrss - 52 nil
Addrss - 53 nil
Addrss - 54 nil
Addrss - 55 nil
Addrss - 56 nil
Addrss - 57 nil
Addrss - 58 nil
Addrss - 59 nil
Addrss - 60 nil
Addrss - 61 nil
Addrss - 62 nil
Addrss - 63 nil
Addrss - 64 nil
Addrss - 65 nil
Addrss - 66 nil
Addrss - 67 nil
Addrss - 68 nil
Addrss - 69 nil
Addrss - 70 nil
Addrss - 71 nil
Addrss - 72 nil
Addrss - 73 nil
Addrss - 74 nil
Addrss - 75 nil
Addrss - 76 nil
Addrss - 77 nil
Addrss - 78 nil
Addrss - 79 nil
Addrss - 80 nil
Addrss - 81 nil
Addrss - 82 nil
Addrss - 83 nil
Addrss - 84 nil
Addrss - 85 nil
Addrss - 86 nil
Addrss - 87 Detected device address is  0x57 (87)
Addrss - 88 nil
Addrss - 89 nil
Addrss - 90 nil
Addrss - 91 nil
Addrss - 92 nil
Addrss - 93 nil
Addrss - 94 nil
Addrss - 95 nil
Addrss - 96 nil
Addrss - 97 nil
Addrss - 98 nil
Addrss - 99 nil
Addrss - 100 nil
Addrss - 101 nil
Addrss - 102 nil
Addrss - 103 nil
Addrss - 104 Detected device address is  0x68 (104)
Addrss - 105 nil
Addrss - 106 nil
Addrss - 107 nil
Addrss - 108 nil
Addrss - 109 nil
Addrss - 110 nil
Addrss - 111 nil
Addrss - 112 nil
Addrss - 113 nil
Addrss - 114 nil
Addrss - 115 nil
Addrss - 116 nil
Addrss - 117 nil
Addrss - 118 nil
Addrss - 119 nil
Addrss - 120 nil
Addrss - 121 nil
Addrss - 122 nil
Addrss - 123 nil
Addrss - 124 nil
Addrss - 125 nil
Addrss - 126 nil
Addrss - 127 nil
Scanning End
>

ESP32 NodeMCU I2C Interface: Code Explanation

This table format provides a structured breakdown of each section of the code along with its explanation.

SectionExplanation
Setup Section
idDefines the I2C interface as software-based.
pinSDASpecifies the GPIO pin used for the data line (SDA) of the I2C interface.
pinSCLSpecifies the GPIO pin used for the clock line (SCL) of the I2C interface.
speedSets the speed of the I2C communication to slow. Only i2c.SLOW speed is supported.
Initialization
i2c.setup()Initializes the I2C module with the specified parameters: interface ID, SDA pin, SCL pin, and speed.
Scanning for Devices
print(“Scanning Started….”)Prints a message indicating the start of device scanning.
Looping through device addressesIterates through device addresses from 0 to 127.
i2c.start()Sends an I2C start condition.
i2c.address()Sets up the I2C address and read/write mode for the next transfer.
i2c.stop()Sends an I2C stop condition.
Check StatusChecks the status of the address detection: If Status is true, prints the detected device address in hexadecimal and decimal format. If Status is false, prints “nil” for the address.
print(“Scanning End”)Prints a message indicating the end of device scanning.

Suggest


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 – Getting Started

NodeMCU Introduction

    ESP8266 NodeMCU Platform is really very good platform for beginners, you don’t need to remember all ESP8266 registers, address, and so on. You just call the lua function and make your DIY application very quick and easily. Frequently updating thier firmware based on new sensors, and many interfaces. Here below discussed many things and you can lean all the followings

FAQ,

  • what are the different IDE’s are available for ESP8266 NodeMCU Platform?
  • How to build a firmware for ESP8266?
  • How to upload the firmware in to ESP8266 chip?
  • Hello world examples : Printing letters in Serial (UART) and LED Blink.
  • Reference Links

Read more… →