echo '' ;

Category Archives: ESP8266

ESP8266 NodeMCU Module – MQTT

Functions

  • mqtt.Client()  – Creates a MQTT client.
  • mqtt.client:close()  – Closes connection to the broker.
  • mqtt.client:connect() – Connects to the broker specified by the given host, port, and secure options.
  • mqtt.client:lwt( ) – Setup Last Will and Testament (optional).
  • mqtt.client:on()  – Registers a callback function for an event.
  • mqtt.client:publish()  – Publishes a message.
  • mqtt.client:subscribe()  – Subscribes to one or several topics.
  • mqtt.client:unsubscribe()  – Unsubscribes from one or several topics.

 

MQTT Example

  • MQTT subscribe and publish the data to
-- Required Modules :Mqtt,Wifi
-- https://www.aruneworld.com/
-- Tested By    : Arun(20170527)
-- Example Name : AEW_Mqtt.lua
---------------------------------------------------------------------------------
station_cfg={}
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "ArunEworld.com"    --please change your SSID and Passworld

print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()


--Initializing Mqtt
DEVICE_NAME     =   "ArunEworld-"..node.chipid()
PUBLISH_TOPIC   =   "ArunEworld/"..DEVICE_NAME.."-Result"
SUBSCRIBE_TOPIC =   "ArunEworld/"..DEVICE_NAME
CLIENT_ID       =   DEVICE_NAME
USERNAME        =   "username"              --  please change your username
PASSWORD        =   "Password"              --  please change your Password
HOSTNAME        =   "mqtt.aruneworld.com"   --  Please change your port
PORT            =   "Port_Number"                       --  Please change your port number

-- Mqtt Setup
m = mqtt.Client(CLIENT_ID, 120, USERNAME, PASSWORD, 0)
    m:connect(HOSTNAME, PORT, 0, function(conn) 
    m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Online", 1, 0, function(conn) end)
    m:subscribe(SUBSCRIBE_TOPIC, 1, function(conn)  end)
end)

--Mqtt Receive function
m:on("message", function(client, topic, payload)        
        if payload ~= nil then
            print(payload)
        else
            print("Mqtt Reccived nill payload message")
        end
    collectgarbage("collect")
end)

--Mqtt Send function
local function Send_MQTT(strings)
    m:publish(PUBLISH_TOPIC,strings, 1, 0, function(conn)   end)
end

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

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

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

 


 Read and Write files using MQTT

  • transfer files over mqtt
-- For More info :- https://www.aruneworld.com/ 
-- Tested By : Arun(20170527)
-- Required Modules : CJSON, FILE, MQTT, WiFi,

station_cfg={}
DEVICE_NAME = node.chipid()
station_cfg.ssid= "ArunEworld" station_cfg.pwd= "Arun"
PUBLISH_TOPIC = "MQTT_File_Ex_PUB"
SUBSCRIBE_TOPIC = "MQTT_File_Ex_SUB"
CLIENT_ID = DEVICE_NAME
USERNAME = ""
PASSWORD = ""
HOSTNAME = "iot.eclipse.org"
PORT = 1883

print("wifi init")
wifi.setmode(wifi.STATIONAP)
wifi.sta.config(station_cfg)
wifi.sta.connect()

-- test transfer files over mqtt.
m_dis={}            --Created the table and name is m_dis
function dispatch(m,t,pl)
    if pl~=nil and m_dis[t] then
        m_dis[t](m,pl)
    end
end

function pubfile(m,filename)
    file.close()
    file.open(filename)
    repeat
    local pl=file.read(1024)
    if pl then m:publish("/topic2",pl,0,0) end
    until not pl
    file.close()
end
-- payload(json): {"cmd":xxx,"content":xxx}
function topic1func(m,pl)
    print("get1: "..pl)
    local pack = cjson.decode(pl)
    if pack.content then
        if pack.cmd == "open" then file.open(pack.content,"w+")
        elseif pack.cmd == "write" then file.write(pack.content)
        elseif pack.cmd == "close" then file.close()
        elseif pack.cmd == "remove" then file.remove(pack.content)
        elseif pack.cmd == "run" then dofile(pack.content)
        elseif pack.cmd == "read" then pubfile(m, pack.content)
        end
    end
end

m_dis["/topic1"]=topic1func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
--m=mqtt.Client()
m = mqtt.Client(CLIENT_ID, 20, USERNAME, PASSWORD, 0)
m:on("connect",function(m) 
    print("connection "..node.heap()) 
    m:subscribe("/topic1",0,function(m) print("sub done") end)
    m:publish(PUBLISH_TOPIC,DEVICE_NAME.." is Live", 1, 0, function(m) print("[LOG]:- Mqtt "..DEVICE_NAME.." is Live in Online Mode") end)
    
    end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
--m:connect(192.168.18.88,1883,0,1)
--host = "iot.eclipse.org"
m:connect(HOSTNAME,1883,0,1)

-- usage:
-- another client(pc) subscribe to /topic2, will receive the test.lua content.
-- and publish below message to /topic1
-- {"cmd":"open","content":"test.lua"}
-- {"cmd":"write","content":"print([[hello world]])\n"}
-- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
-- {"cmd":"write","content":"test.lua"}
-- {"cmd":"run","content":"test.lua"}
-- {"cmd":"read","content":"test.lua"}

 


 

MQTT to cloud

-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
    if pl~=nil and m_dis[t] then
        m_dis[t](m,pl)
    end
end
function topic1func(m,pl)
    print("get1: "..pl)
end
function topic2func(m,pl)
    print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m) 
    print("connection "..node.heap()) 
    m:subscribe("/topic1",0,function(m) print("sub done") end)
    m:subscribe("/topic2",0,function(m) print("sub done") end)
    m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
    end )
m:on("offline", function(conn)
    print("disconnect to broker...")
    print(node.heap())
end)
m:on("message",dispatch )
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("m11.cloudmqtt.com",11214,0,1)
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time() 
    m:publish("/topic1",pl,0,0)
    end)

 

 

 


Next :

Previous :


 

ESP8266 NodeMCU Interface – ADC

ADC

ESP8266 with  ADC Interface

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

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

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

Circuit Diagram

 

Code

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

Results

 



 

ESP8266 NodeMCU Interface – DHT11

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

Read more… →

ESP8266 NodeMCU Module – File

 


File Modes

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

File Functions

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

Create a New file

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

File – Hello world Program

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

 


Next :

Previous :


 

ESP8266 NodeMCU Interface – 7 Segment Display

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

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

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

Required

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

Code

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

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

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

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

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

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

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

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

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

--init MCP23017
init(MCP23017_ADDRESS)

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

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

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

Code Explanation

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

NEXT

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

ESP8266 NodeMCU Interface – Button

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

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

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

Uses – Button

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

Advantage and Disadvantage

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

Importance of Buttons

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

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

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

Types of buttons

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

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

Button Interrupt Counter

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

Required

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

Code

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

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

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

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

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

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

Code Explanation

Source URLs and Testing Information:

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

Initial Variables Setup:

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

Interrupt Handler Function (counter):

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

Setting up Interrupt Trigger:

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


Interrupt Example of ESP8266 NodeMCU Interface – Button

Code

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

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

    trig(pin, "down", pin1cb)
end

Code Explanation

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

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

Variable Initialization:

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

GPIO Configuration:

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

Callback Function:

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

Callback Logic:

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

Trigger Setup:

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

Interrupt

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

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

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

NEXT

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

ESP8266 NodeMCU Tutorial – Get Google Time

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

Code for Get Google Time using NodeMCU in ESP8266

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

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

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

end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
  print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\treason: "..T.reason)
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
  print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
  sta_ip = T.IP
end)



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

end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
  print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..T.BSSID.."\n\treason: "..T.reason)
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
  print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..T.netmask.."\n\tGateway IP: "..T.gateway)
  sta_ip = T.IP
end)



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

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

Result

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

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

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

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

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

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


ESP8266 NodeMCU Project – WiFi Status Indicator

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

Read more: ESP8266 NodeMCU Project – WiFi Status Indicator

Features

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

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

Required for ESP8266 WiFi Status Indicator

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

Code

ESP8266 WiFi Status Indicator

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

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

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

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

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

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

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

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

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

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

Code Explanation

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

Module Import and Test Information:

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

Initialization:

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

WiFi Initialization:

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

WiFi Event Monitoring:

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

Function Definitions:

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

Main Loop:

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

Comments:

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

NEXT

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

ESP8266 NodeMCU Module – I2C

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

Pr-Request to Lean

ESP8266 I2C Core

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


ESP8266 I2C Scanner

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

Code

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

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

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

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

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

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

print("Scanning End")

Explanation

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

Setup:

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

Initialization:

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

Scanning for Devices:

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

Printing Results:

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

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

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

ESP8266 I2C Example

Code

id = 0
sda = 1
scl = 2

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

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

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

Code Explanation

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

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

See Also

NEXT

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

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

Code

 

// https://www.aruneworld.com/
// Tested By  : Arun(20170430)
// Example Name : AEW_Button_Message.js
// Firmware  : Mongoose OS for ESP32
//*******************************//

// This example demonstrates how to react on a button press
// by printing a message on a console.
//
// To try this example,
//   1. Download <code>{{EJS10}}</code> tool from https://mongoose-os.com/software.html
//   2. Run <code>{{EJS11}}</code> tool and install Mongoose OS
//   3. In the UI, navigate to the <code>{{EJS12}}</code> tab and load this example

// Load Mongoose OS API
load('api_gpio.js');

let pin = 0;   // GPIO 0 is typically a 'Flash' button
GPIO.set_button_handler(pin, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 200, function(x) {
  print('Button press, pin: ', x);
}, true);

print('Flash button is configured on GPIO pin ', pin);
print('Press the flash button now!');

 


Next :

Previous :


 

ESP8266 Mongoose-OS Tutorials – TCP Web Server

Welcome to the ESP8266 Mongoose-OS Tutorials on the TCP Web Server. In this series of tutorials, we will explore how to create a TCP Web Server using the ESP8266 microcontroller and the Mongoose-OS firmware.

The ESP8266 is a powerful microcontroller known for its built-in WiFi capability, making it suitable for IoT (Internet of Things) projects. Mongoose-OS is an open-source firmware for microcontrollers that provides a development environment for building IoT applications. “ESP8266 Mongoose OS Tutorials TCP Web Server”

In this tutorial series, we will demonstrate how to create a TCP Web Server using Mongoose-OS on the ESP8266. We will cover topics such as setting up the development environment, writing code to create a TCP server, handling incoming connections, and sending data over the network.

Whether you’re a beginner or an experienced developer, these tutorials will provide you with the knowledge and skills to create your own TCP Web Server on the ESP8266 using Mongoose-OS.

Let’s get start!

TCP Web Server Uses

UseDescription
Data LoggingLogging data received from clients, such as sensor readings or system status updates, for later analysis or archival purposes.
Remote MonitoringProviding remote access to real-time data, allowing users to monitor and control devices or systems from anywhere with an internet connection.
Home AutomationControlling smart home devices remotely, such as lights, thermostats, or security cameras, to manage home environments more conveniently.
Industrial ControlMonitoring and controlling machinery, production processes, or environmental conditions in industrial settings, enabling remote access for maintenance.
IoT ApplicationsExchanging data between connected IoT devices, gathering sensor data from remote locations, or controlling IoT devices remotely.
CommunicationFacilitating communication between devices on a network, allowing them to exchange data, synchronize operations, or coordinate tasks.
Remote ConfigurationRemotely configuring devices or systems, updating settings, adjusting parameters, or performing firmware upgrades without physical access to the device.
Real-Time NotificationsSending real-time notifications to connected clients, such as alerts, alarms, or status updates, to keep users informed of important events.
Custom ApplicationsBuilding custom applications tailored to specific needs, such as remote control interfaces, monitoring dashboards, or interactive user interfaces.
Distributed SystemsIntegrating into distributed systems or networked applications to enable communication and data exchange between multiple nodes or components.

Code

// https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_mongoose-os/
// Tested By : Arun(20170430)
// Example Name : AEW_TCP_Web_Server.js
// Firmware : Mongoose OS for ESP32

//*******************************//

// This example demonstrates how to create a TCP echo server.
//
// To try this example,
// 1. Download mos tool from https://mongoose-os.com/software.html
// 2. Run mos tool and install Mongoose OS
// 3. In the UI, navigate to the Examples tab and load this example

// Load Mongoose OS API
load('api_net.js');

let port = '1234';

Net.bind(port, function(conn, ev, ev_data) {
    if (ev !== Net.EV_ACCEPT) return;
    Net.send(conn, JSON.stringify({a: 1, b: 'hey!'}));
    Net.close(conn);
}, true);

print('TCP server is listening on port ', port);

Code Explanation

Line(s)Explanation
1-4Comments providing information about the source of the code, the tester, example name, and firmware used.
7Load the Mongoose OS API module to enable network functionality.
9Define the port number (e.g., ‘1234’) on which the TCP server will listen for incoming connections.
11-18Bind a TCP server to the specified port. When a connection is accepted, send a JSON-encoded message {a: 1, b: 'hey!'} to the client and close the connection.
15Check if the event received is an accept event.
16Send a JSON-encoded message {a: 1, b: 'hey!'} to the client.
17Close the connection after sending the message.
19Print a message indicating that the TCP server is listening on the specified port.

NEXT

MongooseOS
Mongoose-OS Interface
ESP8266 MongooseOS Interface LED
ESP8266 MongooseOS Interface Button
Mongoose OS Tutorials
ESP8266 MongooseOS Tutorials Web Server
Others
ESP8266 MongooseOS All Post

ESP8266 Mongoose-OS Interface – LED

To turn on the led you need to load the gpio_api.js file.


LED Turn ON/OFF

Note : This below example was tested mongoose os with java script app demo-js in ESP8266 NodeMCU Dev Board(ESP-12E)

  • This below example turn on the LED GPIO-4 (NodeMCU Dev Board digital pin 2)
  • Set the GPIO pin mode as OUPUT uisng gpio set mode function ex: GPIO.set_mode(led, GPIO.MODE_OUTPUT)
  • Turn off the LED call the gpio write function with low-0 ex : GPIO.write(led, 0) .
  • Turn on the LED call the gpio write function with low-1 ex : GPIO.write(led, 1) .

Code

load('api_gpio.js');
 
// Configure LED
let led = 4; //lde pin GPIO04
GPIO.set_mode(led, GPIO.MODE_OUTPUT);
GPIO.write(led,1);

 


LED turn ON/OFF using button

  • Use Boot button(GPIO-0)
  • The example code used blink in-build LED, It’s connected to GPIO-10.
  • You can change any other pin Ex : led = 4; // Get LED GPIO-04 pin; 
  • Note : Code 1 and Two are same application and functionality. Main difference is calling function.

Code 1 :

  • Used GPIO-0 pin (Boot button in NodeMCU Dev Board), as interrupt and used Button interrupt handler function.
// http://www.ArunEworld.com/Embedded/ESPressif/ESP8266/ESP8266_Mongoose-os/
// Tested By  : Arun(20170430)
// Example Name : AEW_LED-Blink_Using_Button.js
// Firmware  : Mongoose OS for ESP32
//*******************************//
// This example demonstrates how to react on a button press by toggling LED.
//
// To try this example,
//   1. Download <code>{{EJS17}}</code> tool from https://mongoose-os.com/software.html
//   2. Run <code>{{EJS18}}</code> tool and install Mongoose OS
//   3. In the UI, navigate to the <code>{{EJS19}}</code> tab and load this example

// Load Mongoose OS API
load('api_gpio.js');

// Configure LED
let led = ffi('int get_led_gpio_pin()')();  // Get built-in LED GPIO pin
GPIO.set_mode(led, GPIO.MODE_OUTPUT);

let pin = 0;   // GPIO 0 is typically a 'Flash' button
GPIO.set_button_handler(pin, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 200, function(x) {
  let value = GPIO.toggle(led);
  print('Button press, pin:', x, 'LED pin:', led, ' Value: ', value);
}, true);

print('Flash button is configured on GPIO pin ', pin);
print('Press the flash button now!');

 

Code 2:

  • In this code i was used GPIO-0 pin (Boot button in NodeMCU dev Kit) as interrupt and used interrupt handler function.
  • If your using interruot handler function then you need o enable the interrupt using GPIO.enable_int(pin)  function
load('api_gpio.js');

GPIO.set_mode(4, 1);
//GPIO.write(10, 0);


GPIO.set_int_handler(0, GPIO.INT_EDGE_NEG, function(pin) {
   print('Pin', 0, 'got interrupt');
   GPIO.toggle(4);
   
}, null);
GPIO.enable_int(0);

 

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 Arduino-Core – Basics

The ESP8266 Arduino Core is a software framework that enables developers to program ESP8266 microcontrollers using the Arduino programming language and environment. This core provides a set of libraries and tools that simplify the development process for projects involving the ESP8266 chip. Here will discuss ESP8266 Arduino-Core Basics.

ESP8266 Arduino Core serves as a powerful tool for developing IoT (Internet of Things) applications, home automation systems, sensor networks, and more, using the ESP8266 microcontroller platform with the simplicity and flexibility of the Arduino ecosystem.

Read more: ESP8266 Arduino-Core – Basics

Call SDK Functions

  •  Required Hardware ESP8266 with Programmer (or)  NodeMCU Dev Kit
  • Required Software Tools Arduino IDE with ESP8266 Core

Code

/* 
  https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_arduino-core/
  Tested By  : Arun(20170219)
  Example Name : AEW_CallSDKFunctions.ino
 */
/**
 * TestEspApi by Max Vilimpoc
 * This code is released to the public domain.
 * 
 * Test out the Expressif ESP8266 Non-OS API, exhaustively trying out 
 * as many of the built-in functions as possible.
 * 
 * Some of the code is based on examples in:
 * "20A-ESP8266__RTOS_SDK__Programming Guide__EN_v1.3.0.pdf"
 */

#ifdef ESP8266
extern "C" {
#include "user_interface.h"
}
#endif

// Set up output serial port (could be a SoftwareSerial
// if really wanted).

Stream& ehConsolePort(Serial);

// Wired to the blue LED on an ESP-01 board, active LOW.
//
// Cannot be used simultaneously with Serial.print/println()
// calls, as TX is wired to the same pin. 
//
// UNLESS: You swap the TX pin using the alternate pinout.
const uint8_t LED_PIN = 1;

const char * const RST_REASONS[] =
{
    "REASON_DEFAULT_RST",
    "REASON_WDT_RST",
    "REASON_EXCEPTION_RST",
    "REASON_SOFT_WDT_RST",
    "REASON_SOFT_RESTART",
    "REASON_DEEP_SLEEP_AWAKE",
    "REASON_EXT_SYS_RST"
};

const char * const FLASH_SIZE_MAP_NAMES[] =
{
    "FLASH_SIZE_4M_MAP_256_256",
    "FLASH_SIZE_2M",
    "FLASH_SIZE_8M_MAP_512_512",
    "FLASH_SIZE_16M_MAP_512_512",
    "FLASH_SIZE_32M_MAP_512_512",
    "FLASH_SIZE_16M_MAP_1024_1024",
    "FLASH_SIZE_32M_MAP_1024_1024"
};

const char * const OP_MODE_NAMES[] 
{
    "NULL_MODE",
    "STATION_MODE",
    "SOFTAP_MODE",
    "STATIONAP_MODE"
};

const char * const AUTH_MODE_NAMES[] 
{
    "AUTH_OPEN",
    "AUTH_WEP",
    "AUTH_WPA_PSK",
    "AUTH_WPA2_PSK",
    "AUTH_WPA_WPA2_PSK",
    "AUTH_MAX"
};

const char * const PHY_MODE_NAMES[]
{
    "",
    "PHY_MODE_11B",
    "PHY_MODE_11G",
    "PHY_MODE_11N"
};

const char * const EVENT_NAMES[]
{
    "EVENT_STAMODE_CONNECTED",
    "EVENT_STAMODE_DISCONNECTED",
    "EVENT_STAMODE_AUTHMODE_CHANGE",
    "EVENT_STAMODE_GOT_IP",
    "EVENT_SOFTAPMODE_STACONNECTED",
    "EVENT_SOFTAPMODE_STADISCONNECTED",
    "EVENT_MAX"
};

const char * const EVENT_REASONS[]
{
    "",
    "REASON_UNSPECIFIED",
    "REASON_AUTH_EXPIRE",
    "REASON_AUTH_LEAVE",
    "REASON_ASSOC_EXPIRE",
    "REASON_ASSOC_TOOMANY",
    "REASON_NOT_AUTHED",
    "REASON_NOT_ASSOCED",
    "REASON_ASSOC_LEAVE",
    "REASON_ASSOC_NOT_AUTHED",
    "REASON_DISASSOC_PWRCAP_BAD",
    "REASON_DISASSOC_SUPCHAN_BAD",
    "REASON_IE_INVALID",
    "REASON_MIC_FAILURE",
    "REASON_4WAY_HANDSHAKE_TIMEOUT",
    "REASON_GROUP_KEY_UPDATE_TIMEOUT",
    "REASON_IE_IN_4WAY_DIFFERS",
    "REASON_GROUP_CIPHER_INVALID",
    "REASON_PAIRWISE_CIPHER_INVALID",
    "REASON_AKMP_INVALID",
    "REASON_UNSUPP_RSN_IE_VERSION",
    "REASON_INVALID_RSN_IE_CAP",
    "REASON_802_1X_AUTH_FAILED",
    "REASON_CIPHER_SUITE_REJECTED",
};

const char * const EVENT_REASONS_200[]
{
    "REASON_BEACON_TIMEOUT",
    "REASON_NO_AP_FOUND"
};

void wifi_event_handler_cb(System_Event_t * event)
{
    ehConsolePort.print(EVENT_NAMES[event->event]);
    ehConsolePort.print(" (");
    
    switch (event->event)
    {
        case EVENT_STAMODE_CONNECTED:
            break;
        case EVENT_STAMODE_DISCONNECTED:
            break;
        case EVENT_STAMODE_AUTHMODE_CHANGE:
            break;
        case EVENT_STAMODE_GOT_IP:
            break;
        case EVENT_SOFTAPMODE_STACONNECTED:
        case EVENT_SOFTAPMODE_STADISCONNECTED:
            {
                char mac[32] = {0};
                snprintf(mac, 32, MACSTR ", aid: %d" , MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid);
                
                ehConsolePort.print(mac);
            }
            break;
    }

    ehConsolePort.println(")");
}

void print_softap_config(Stream & consolePort, softap_config const& config)
{
    consolePort.println();
    consolePort.println(F("SoftAP Configuration"));
    consolePort.println(F("--------------------"));

    consolePort.print(F("ssid:            "));
    consolePort.println((char *) config.ssid);

    consolePort.print(F("password:        "));
    consolePort.println((char *) config.password);

    consolePort.print(F("ssid_len:        "));
    consolePort.println(config.ssid_len);

    consolePort.print(F("channel:         "));
    consolePort.println(config.channel);

    consolePort.print(F("authmode:        "));
    consolePort.println(AUTH_MODE_NAMES[config.authmode]);

    consolePort.print(F("ssid_hidden:     "));
    consolePort.println(config.ssid_hidden);

    consolePort.print(F("max_connection:  "));
    consolePort.println(config.max_connection);

    consolePort.print(F("beacon_interval: "));
    consolePort.print(config.beacon_interval);
    consolePort.println("ms");

    consolePort.println(F("--------------------"));
    consolePort.println();
}

void print_system_info(Stream & consolePort)
{
    const rst_info * resetInfo = system_get_rst_info();
    consolePort.print(F("system_get_rst_info() reset reason: "));
    consolePort.println(RST_REASONS[resetInfo->reason]);

    consolePort.print(F("system_get_free_heap_size(): "));
    consolePort.println(system_get_free_heap_size());

    consolePort.print(F("system_get_os_print(): "));
    consolePort.println(system_get_os_print());
    system_set_os_print(1);
    consolePort.print(F("system_get_os_print(): "));
    consolePort.println(system_get_os_print());

    system_print_meminfo();

    consolePort.print(F("system_get_chip_id(): 0x"));
    consolePort.println(system_get_chip_id(), HEX);

    consolePort.print(F("system_get_sdk_version(): "));
    consolePort.println(system_get_sdk_version());

    consolePort.print(F("system_get_boot_version(): "));
    consolePort.println(system_get_boot_version());

    consolePort.print(F("system_get_userbin_addr(): 0x"));
    consolePort.println(system_get_userbin_addr(), HEX);

    consolePort.print(F("system_get_boot_mode(): "));
    consolePort.println(system_get_boot_mode() == 0 ? F("SYS_BOOT_ENHANCE_MODE") : F("SYS_BOOT_NORMAL_MODE"));

    consolePort.print(F("system_get_cpu_freq(): "));
    consolePort.println(system_get_cpu_freq());

    consolePort.print(F("system_get_flash_size_map(): "));
    consolePort.println(FLASH_SIZE_MAP_NAMES[system_get_flash_size_map()]);
}

void print_wifi_general(Stream & consolePort)
{
    consolePort.print(F("wifi_get_channel(): "));
    consolePort.println(wifi_get_channel());
    
    consolePort.print(F("wifi_get_phy_mode(): "));
    consolePort.println(PHY_MODE_NAMES[wifi_get_phy_mode()]);
}

void secure_softap_config(softap_config * config, const char * ssid, const char * password)
{
    size_t ssidLen     = strlen(ssid)     < sizeof(config->ssid)     ? strlen(ssid)     : sizeof(config->ssid);
    size_t passwordLen = strlen(password) < sizeof(config->password) ? strlen(password) : sizeof(config->password);

    memset(config->ssid, 0, sizeof(config->ssid));
    memcpy(config->ssid, ssid, ssidLen);

    memset(config->password, 0, sizeof(config->password));
    memcpy(config->password, password, passwordLen);

    config->ssid_len = ssidLen;
    config->channel  = 1;
    config->authmode = AUTH_WPA2_PSK;
//    config->ssid_hidden = 1;
    config->max_connection = 4;
//    config->beacon_interval = 1000;
}

void setup() 
{
    // Reuse default Serial port rate, so the bootloader
    // messages are also readable.
    
    Serial.begin(74880);

    // Try pushing frequency to 160MHz.
    system_update_cpu_freq(SYS_CPU_160MHZ);

    Serial.println();
    Serial.println(F("ESP starting."));

    // System usually boots up in about 200ms.
    
    Serial.print(F("system_get_time(): "));
    Serial.println(system_get_time());

    // set_event_handler_cb_stream(Serial);
    wifi_set_event_handler_cb(wifi_event_handler_cb);

    print_system_info(Serial);

    Serial.print(F("wifi_get_opmode(): "));
    Serial.print(wifi_get_opmode());
    Serial.print(F(" - "));
    Serial.println(OP_MODE_NAMES[wifi_get_opmode()]);

    Serial.print(F("wifi_get_opmode_default(): "));
    Serial.print(wifi_get_opmode_default());
    Serial.print(F(" - "));
    Serial.println(OP_MODE_NAMES[wifi_get_opmode_default()]);

    Serial.print(F("wifi_get_broadcast_if(): "));
    Serial.println(wifi_get_broadcast_if());

    softap_config config;
    wifi_softap_get_config(&config);
    secure_softap_config(&config, "TestAP", "testtesttest");
    wifi_softap_set_config(&config);
    print_softap_config(Serial, config);

    print_wifi_general(Serial);

    // This doesn't work on an ESP-01.
    // wifi_set_sleep_type(LIGHT_SLEEP_T);

    // Try this dirty little thing.
    // Doesn't work because ESP-01 module doesn't link XPD_DCDC -> RST.
    // ESP.deepSleep(15000);
}

void loop() 
{
    Serial.print(F("system_get_time(): "));
    Serial.println(system_get_time());
    delay(1000);
}

Result

wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname: 
wifi_station_get_hostname:

Test ESP8266 API

ESP8266 Arduino-Core Basics

Code

/*
 https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_arduino-core/esp8266_arduino-core-basics/
 Tested By  : Arun(20170219)
 Example Name : AEW_TestEspAPI.ino
*/
/**
 * TestEspApi by Max Vilimpoc
 * This code is released to the public domain.
 * 
 * Test out the Expressif ESP8266 Non-OS API, exhaustively trying out 
 * as many of the built-in functions as possible.
 * 
 * Some of the code is based on examples in:
 * "20A-ESP8266__RTOS_SDK__Programming Guide__EN_v1.3.0.pdf"
 */

#ifdef ESP8266
extern "C" {
#include "user_interface.h"
}
#endif

// Set up output serial port (could be a SoftwareSerial
// if really wanted).

Stream& ehConsolePort(Serial);

// Wired to the blue LED on an ESP-01 board, active LOW.
//
// Cannot be used simultaneously with Serial.print/println()
// calls, as TX is wired to the same pin. 
//
// UNLESS: You swap the TX pin using the alternate pinout.
const uint8_t LED_PIN = 1;

const char * const RST_REASONS[] =
{
    "REASON_DEFAULT_RST",
    "REASON_WDT_RST",
    "REASON_EXCEPTION_RST",
    "REASON_SOFT_WDT_RST",
    "REASON_SOFT_RESTART",
    "REASON_DEEP_SLEEP_AWAKE",
    "REASON_EXT_SYS_RST"
};

const char * const FLASH_SIZE_MAP_NAMES[] =
{
    "FLASH_SIZE_4M_MAP_256_256",
    "FLASH_SIZE_2M",
    "FLASH_SIZE_8M_MAP_512_512",
    "FLASH_SIZE_16M_MAP_512_512",
    "FLASH_SIZE_32M_MAP_512_512",
    "FLASH_SIZE_16M_MAP_1024_1024",
    "FLASH_SIZE_32M_MAP_1024_1024"
};

const char * const OP_MODE_NAMES[] 
{
    "NULL_MODE",
    "STATION_MODE",
    "SOFTAP_MODE",
    "STATIONAP_MODE"
};

const char * const AUTH_MODE_NAMES[] 
{
    "AUTH_OPEN",
    "AUTH_WEP",
    "AUTH_WPA_PSK",
    "AUTH_WPA2_PSK",
    "AUTH_WPA_WPA2_PSK",
    "AUTH_MAX"
};

const char * const PHY_MODE_NAMES[]
{
    "",
    "PHY_MODE_11B",
    "PHY_MODE_11G",
    "PHY_MODE_11N"
};

const char * const EVENT_NAMES[]
{
    "EVENT_STAMODE_CONNECTED",
    "EVENT_STAMODE_DISCONNECTED",
    "EVENT_STAMODE_AUTHMODE_CHANGE",
    "EVENT_STAMODE_GOT_IP",
    "EVENT_SOFTAPMODE_STACONNECTED",
    "EVENT_SOFTAPMODE_STADISCONNECTED",
    "EVENT_MAX"
};

const char * const EVENT_REASONS[]
{
    "",
    "REASON_UNSPECIFIED",
    "REASON_AUTH_EXPIRE",
    "REASON_AUTH_LEAVE",
    "REASON_ASSOC_EXPIRE",
    "REASON_ASSOC_TOOMANY",
    "REASON_NOT_AUTHED",
    "REASON_NOT_ASSOCED",
    "REASON_ASSOC_LEAVE",
    "REASON_ASSOC_NOT_AUTHED",
    "REASON_DISASSOC_PWRCAP_BAD",
    "REASON_DISASSOC_SUPCHAN_BAD",
    "REASON_IE_INVALID",
    "REASON_MIC_FAILURE",
    "REASON_4WAY_HANDSHAKE_TIMEOUT",
    "REASON_GROUP_KEY_UPDATE_TIMEOUT",
    "REASON_IE_IN_4WAY_DIFFERS",
    "REASON_GROUP_CIPHER_INVALID",
    "REASON_PAIRWISE_CIPHER_INVALID",
    "REASON_AKMP_INVALID",
    "REASON_UNSUPP_RSN_IE_VERSION",
    "REASON_INVALID_RSN_IE_CAP",
    "REASON_802_1X_AUTH_FAILED",
    "REASON_CIPHER_SUITE_REJECTED",
};

const char * const EVENT_REASONS_200[]
{
    "REASON_BEACON_TIMEOUT",
    "REASON_NO_AP_FOUND"
};

void wifi_event_handler_cb(System_Event_t * event)
{
    ehConsolePort.print(EVENT_NAMES[event->event]);
    ehConsolePort.print(" (");
    
    switch (event->event)
    {
        case EVENT_STAMODE_CONNECTED:
            break;
        case EVENT_STAMODE_DISCONNECTED:
            break;
        case EVENT_STAMODE_AUTHMODE_CHANGE:
            break;
        case EVENT_STAMODE_GOT_IP:
            break;
        case EVENT_SOFTAPMODE_STACONNECTED:
        case EVENT_SOFTAPMODE_STADISCONNECTED:
            {
                char mac[32] = {0};
                snprintf(mac, 32, MACSTR ", aid: %d" , MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid);
                
                ehConsolePort.print(mac);
            }
            break;
    }

    ehConsolePort.println(")");
}

void print_softap_config(Stream & consolePort, softap_config const& config)
{
    consolePort.println();
    consolePort.println(F("SoftAP Configuration"));
    consolePort.println(F("--------------------"));

    consolePort.print(F("ssid:            "));
    consolePort.println((char *) config.ssid);

    consolePort.print(F("password:        "));
    consolePort.println((char *) config.password);

    consolePort.print(F("ssid_len:        "));
    consolePort.println(config.ssid_len);

    consolePort.print(F("channel:         "));
    consolePort.println(config.channel);

    consolePort.print(F("authmode:        "));
    consolePort.println(AUTH_MODE_NAMES[config.authmode]);

    consolePort.print(F("ssid_hidden:     "));
    consolePort.println(config.ssid_hidden);

    consolePort.print(F("max_connection:  "));
    consolePort.println(config.max_connection);

    consolePort.print(F("beacon_interval: "));
    consolePort.print(config.beacon_interval);
    consolePort.println("ms");

    consolePort.println(F("--------------------"));
    consolePort.println();
}

void print_system_info(Stream & consolePort)
{
    const rst_info * resetInfo = system_get_rst_info();
    consolePort.print(F("system_get_rst_info() reset reason: "));
    consolePort.println(RST_REASONS[resetInfo->reason]);

    consolePort.print(F("system_get_free_heap_size(): "));
    consolePort.println(system_get_free_heap_size());

    consolePort.print(F("system_get_os_print(): "));
    consolePort.println(system_get_os_print());
    system_set_os_print(1);
    consolePort.print(F("system_get_os_print(): "));
    consolePort.println(system_get_os_print());

    system_print_meminfo();

    consolePort.print(F("system_get_chip_id(): 0x"));
    consolePort.println(system_get_chip_id(), HEX);

    consolePort.print(F("system_get_sdk_version(): "));
    consolePort.println(system_get_sdk_version());

    consolePort.print(F("system_get_boot_version(): "));
    consolePort.println(system_get_boot_version());

    consolePort.print(F("system_get_userbin_addr(): 0x"));
    consolePort.println(system_get_userbin_addr(), HEX);

    consolePort.print(F("system_get_boot_mode(): "));
    consolePort.println(system_get_boot_mode() == 0 ? F("SYS_BOOT_ENHANCE_MODE") : F("SYS_BOOT_NORMAL_MODE"));

    consolePort.print(F("system_get_cpu_freq(): "));
    consolePort.println(system_get_cpu_freq());

    consolePort.print(F("system_get_flash_size_map(): "));
    consolePort.println(FLASH_SIZE_MAP_NAMES[system_get_flash_size_map()]);
}

void print_wifi_general(Stream & consolePort)
{
    consolePort.print(F("wifi_get_channel(): "));
    consolePort.println(wifi_get_channel());
    
    consolePort.print(F("wifi_get_phy_mode(): "));
    consolePort.println(PHY_MODE_NAMES[wifi_get_phy_mode()]);
}

void secure_softap_config(softap_config * config, const char * ssid, const char * password)
{
    size_t ssidLen     = strlen(ssid)     < sizeof(config->ssid)     ? strlen(ssid)     : sizeof(config->ssid);
    size_t passwordLen = strlen(password) < sizeof(config->password) ? strlen(password) : sizeof(config->password);

    memset(config->ssid, 0, sizeof(config->ssid));
    memcpy(config->ssid, ssid, ssidLen);

    memset(config->password, 0, sizeof(config->password));
    memcpy(config->password, password, passwordLen);

    config->ssid_len = ssidLen;
    config->channel  = 1;
    config->authmode = AUTH_WPA2_PSK;
//    config->ssid_hidden = 1;
    config->max_connection = 4;
//    config->beacon_interval = 1000;
}

void setup() 
{
    // Reuse default Serial port rate, so the bootloader
    // messages are also readable.
    
    Serial.begin(74880);

    // Try pushing frequency to 160MHz.
    system_update_cpu_freq(SYS_CPU_160MHZ);

    Serial.println();
    Serial.println(F("ESP starting."));

    // System usually boots up in about 200ms.
    
    Serial.print(F("system_get_time(): "));
    Serial.println(system_get_time());

    // set_event_handler_cb_stream(Serial);
    wifi_set_event_handler_cb(wifi_event_handler_cb);

    print_system_info(Serial);

    Serial.print(F("wifi_get_opmode(): "));
    Serial.print(wifi_get_opmode());
    Serial.print(F(" - "));
    Serial.println(OP_MODE_NAMES[wifi_get_opmode()]);

    Serial.print(F("wifi_get_opmode_default(): "));
    Serial.print(wifi_get_opmode_default());
    Serial.print(F(" - "));
    Serial.println(OP_MODE_NAMES[wifi_get_opmode_default()]);

    Serial.print(F("wifi_get_broadcast_if(): "));
    Serial.println(wifi_get_broadcast_if());

    softap_config config;
    wifi_softap_get_config(&config);
    secure_softap_config(&config, "TestAP", "testtesttest");
    wifi_softap_set_config(&config);
    print_softap_config(Serial, config);

    print_wifi_general(Serial);

    // This doesn't work on an ESP-01.
    // wifi_set_sleep_type(LIGHT_SLEEP_T);

    // Try this dirty little thing.
    // Doesn't work because ESP-01 module doesn't link XPD_DCDC -> RST.
    // ESP.deepSleep(15000);
}

void loop() 
{
    Serial.print(F("system_get_time(): "));
    Serial.println(system_get_time());
    delay(1000);

Result

ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16 
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
¡H¨MA�starting.
system_get_time(): 282250
system_get_rst_info() reset reason: REASON_EXT_SYS_RST
system_get_free_heap_size(): 49016
system_get_os_print(): 0
system_get_os_print(): 1
system_get_chip_id(): 0xD98DD7
system_get_sdk_version(): 1.5.3(aec24ac9)
system_get_boot_version(): 5
system_get_userbin_addr(): 0x1000
system_get_boot_mode(): SYS_BOOT_NORMAL_MODE
system_get_cpu_freq(): 160
system_get_flash_size_map(): FLASH_SIZE_4M_MAP_256_256
wifi_get_opmode(): 2 - SOFTAP_MODE
wifi_get_opmode_default(): 2 - SOFTAP_MODE
wifi_get_broadcast_if(): 2

SoftAP Configuration
--------------------
ssid:            TestAP
password:        testtesttest
ssid_len:        6
channel:         1
authmode:        AUTH_WPA2_PSK
ssid_hidden:     0
max_connection:  4
beacon_interval: 11298ms
--------------------

wifi_get_channel(): 1
wifi_get_phy_mode(): PHY_MODE_11N
system_get_time(): 386190
system_get_time(): 1387316
system_get_time(): 2387360
system_get_time(): 3387405
system_get_time(): 4387450
system_get_time(): 5387495
system_get_time(): 6387539

RTC User Memory

Code

/*
 https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_arduino-core/esp8266_arduino-core-basics/
 Tested By  : Arun(20170219)
 Example Name : AEW_RTCUserMemory.ino
*/

// Example: Storing struct data in RTC user rtcDataory
//
// Struct data with the maximum size of 512 bytes can be stored
// in the RTC user rtcDataory using the ESP-specifc APIs.
// The stored data can be retained between deep sleep cycles.
// However, the data might be lost after power cycling the ESP8266.
//
// This example uses deep sleep mode, so connect GPIO16 and RST
// pins before running it.
//
// Created Mar 30, 2016 by Macro Yau.
//
// This example code is in the public domain.

// CRC function used to ensure data validity
uint32_t calculateCRC32(const uint8_t *data, size_t length);

// helper function to dump memory contents as hex
void printMemory();

// Structure which will be stored in RTC memory.
// First field is CRC32, which is calculated based on the
// rest of structure contents.
// Any fields can go after CRC32.
// We use byte array as an example.
struct {
  uint32_t crc32;
  byte data[508];
} rtcData;

void setup() {
  Serial.begin(115200);
  Serial.println();
  delay(1000);

  // Read struct from RTC memory
  if (ESP.rtcUserMemoryRead(0, (uint32_t*) &rtcData, sizeof(rtcData))) {
    Serial.println("Read: ");
    printMemory();
    Serial.println();
    uint32_t crcOfData = calculateCRC32(((uint8_t*) &rtcData) + 4, sizeof(rtcData) - 4);
    Serial.print("CRC32 of data: ");
    Serial.println(crcOfData, HEX);
    Serial.print("CRC32 read from RTC: ");
    Serial.println(rtcData.crc32, HEX);
    if (crcOfData != rtcData.crc32) {
      Serial.println("CRC32 in RTC memory doesn't match CRC32 of data. Data is probably invalid!");
    }
    else {
      Serial.println("CRC32 check ok, data is probably valid.");
    }
  }

  // Generate new data set for the struct
  for (int i = 0; i < sizeof(rtcData); i++) {
    rtcData.data[i] = random(0, 128);
  }
  // Update CRC32 of data
  rtcData.crc32 = calculateCRC32(((uint8_t*) &rtcData) + 4, sizeof(rtcData) - 4);
  // Write struct to RTC memory
  if (ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcData, sizeof(rtcData))) {
    Serial.println("Write: ");
    printMemory();
    Serial.println();
  }

  Serial.println("Going into deep sleep for 5 seconds");
  ESP.deepSleep(5e6);
}

void loop() {
}

uint32_t calculateCRC32(const uint8_t *data, size_t length)
{
  uint32_t crc = 0xffffffff;
  while (length--) {
    uint8_t c = *data++;
    for (uint32_t i = 0x80; i > 0; i >>= 1) {
      bool bit = crc & 0x80000000;
      if (c & i) {
        bit = !bit;
      }
      crc <<= 1;
      if (bit) {
        crc ^= 0x04c11db7;
      }
    }
  }
  return crc;
}

void printMemory() {
  char buf[3];
  for (int i = 0; i < sizeof(rtcData); i++) {
    sprintf(buf, "%02X", rtcData.data[i]);
    Serial.print(buf);
    if ((i + 1) % 32 == 0) {
      Serial.println();
    }
    else {
      Serial.print(" ");
    }
  }
  Serial.println();
}

Result

3F 34 14 6D 36 50 4F 51 7B 57 20 64 6A 4E 20 12 3C 2E 37 1E 23 1E 4F 28 23 16 1D 3F 4E 6F 36 3D
7E 5E 60 05 7D 37 3E 4B 53 40 74 64 09 0A 40 13 3E 05 09 5D 49 63 1C 15 37 50 76 02 5D 75 10 07
4C 2A 73 65 49 78 6E 3C 02 50 1D 6D 0D 16 77 15 10 48 31 02 57 1A 60 3B 41 16 6A 78 3F 0B 1D 2D
39 58 3D 58 5E 72 06 7A 79 52 24 6A 77 68 38 4D 5A 02 43 09 4A 75 4B 04 78 3B 52 7C 20 34 60 1F
51 5F 44 08 26 04 3B 1E 77 73 13 49 4B 11 3A 06 42 1E 59 6D 63 4D 1F 2D 2E 3D 51 00 77 50 28 46
44 78 7A 07 42 21 73 75 44 60 7C 68 23 5B 44 31 47 5E 73 67 69 47 2A 0A 34 05 14 62 61 13 07 02
77 3B 3F 1F 3B 75 77 23 64 34 7D 38 41 00 4E 73 07 5E 7B 02 69 37 65 52 3D 3B 09 10 3B 21 44 36
55 4E 45 20 19 25 0D 38 37 37 66 4A 7B 48 64 45 04 4E 3E 28 55 6F 6E 3F 6F 62 0D 58 71 04 49 53
3F 60 37 22 06 52 4B 5A 56 20 07 22 21 0C 17 32 33 5B 5F 37 06 26 2C 19 6C 25 4E 24 0F 45 0B 3E
5A 4A 03 36 2A 3F 34 78 44 12 42 07 3D 3F 7D 42 1C 73 1F 3D 76 1B 5B 0C 3A 07 1E 64 36 73 6E 77
1A 21 40 76 03 01 16 1F 3E 31 0D 6C 2B 72 7A 24 49 15 50 7C 6A 08 16 72 3F 36 5C 7D 29 15 1B 31
06 31 7A 07 1E 46 28 51 68 4F 5C 1F 1C 33 55 2E 54 0D 24 3F 01 47 32 2B 6B 22 1D 44 2E 2C 65 10
44 37 4A 52 3F 11 7B 3D 68 7B 23 17 42 1B 43 23 57 31 7F 31 7D 21 15 0A 2C 2D 16 21 5C 14 17 16
6E 5E 7D 70 2E 67 79 75 30 34 40 2A 61 3A 74 43 0A 7A 12 7F 7D 48 51 52 22 43 4D 6F 08 4C 65 46
7E 07 76 29 29 59 64 3D 6E 64 5B 61 61 34 7B 0B 02 0D 1B 05 66 49 1D 4A 26 29 1B 4D 7C 03 64 34
0F 2F 73 0D 18 20 74 30 02 00 30 4C 34 62 36 25 42 25 65 52 3E 73 0B 3B 15 31 33 29 00 00 00 00


CRC32 of data: 7927D498
CRC32 read from RTC: 7927D498
CRC32 check ok, data is probably valid.
Write: 
4A 64 61 6D 6E 6C 29 0D 59 02 2A 59 0F 3F 76 5E 0F 3E 21 6C 0B 3F 6A 2E 67 4E 6D 05 3F 51 18 50
61 4C 4C 18 0D 0C 0A 07 2D 7E 6D 7F 4E 15 0A 61 15 6D 4F 0E 2B 35 70 45 61 2D 32 48 58 56 60 64
01 7B 3B 45 32 5F 64 7F 71 4C 61 43 00 48 0C 1E 42 76 51 5B 2C 3B 0C 39 68 5F 75 21 25 6C 76 5D
6E 4C 45 3A 12 44 23 25 4E 32 37 4C 44 01 51 62 71 34 53 5F 0C 39 49 67 03 57 13 0F 42 23 45 5C
7B 7F 47 76 73 26 45 65 3E 0C 02 10 20 28 53 68 1B 02 63 3F 26 3D 39 6E 70 09 1C 48 2F 0E 4F 49
1A 04 6F 15 3B 34 5C 76 20 54 02 20 5E 1A 47 38 14 31 69 07 02 60 7E 2F 79 34 43 4B 75 3D 55 3C
41 76 7C 69 3A 74 48 69 75 7B 04 29 71 27 08 04 6D 13 08 70 34 4E 26 43 10 02 1C 0B 57 22 2F 74
0F 0B 59 46 47 35 1B 45 0B 14 32 24 11 29 2E 29 6F 50 4D 75 31 68 4E 3B 00 1D 10 41 0C 2C 55 23
5C 7C 59 25 09 1F 37 56 21 1A 0D 12 56 6B 63 28 2B 75 06 5B 72 56 61 04 68 64 5F 2E 12 13 78 04
3C 43 10 18 63 37 63 74 37 6D 44 22 3D 67 75 68 53 24 03 7F 20 08 7A 59 5B 04 5F 35 4F 42 1E 64
6F 3F 70 54 06 3B 17 4B 1A 70 36 38 38 5D 01 7A 3B 60 02 7D 14 3C 4D 16 3F 30 3A 73 28 1F 3C 0A
0F 00 56 27 73 55 2C 77 21 59 68 0A 68 72 75 76 32 01 2E 0D 04 3E 37 67 75 04 5E 33 13 17 1A 24
1B 59 18 0E 50 41 79 4D 06 7E 4C 70 48 46 37 3D 45 01 6B 0D 3E 64 2E 40 3C 26 7F 04 15 7F 0D 26
66 27 66 53 15 0D 16 6B 02 3E 67 17 60 42 6A 20 78 16 21 75 61 60 50 05 02 6D 4D 1B 1E 50 7B 33
7F 0E 30 0A 6F 16 6E 49 28 53 19 14 11 11 30 56 44 21 3A 55 74 21 47 17 63 1B 28 44 0A 60 53 57
3B 4E 5F 5E 3B 50 04 42 24 4F 31 72 71 35 24 15 2A 4B 18 16 0F 5D 43 5B 60 4F 57 6D 02 69 5D 6C


Going into deep sleep for 5 seconds

Result

Flash real id:   001640E0
Flash real size: 4194304

Flash ide  size: 524288
Flash ide speed: 40000000
Flash ide mode:  DIO
Flash Chip configuration wrong!

Check Flash Configuration

This Arduino sketch tests whether the ESP8266 microcontroller’s hardware configuration matches the EEPROM settings of the Integrated Development Environment (IDE).

Here’s a breakdown of what the code does:

  1. Setup Function: The setup function is executed once when the microcontroller starts up. In this sketch, it initializes serial communication with a baud rate of 115200.
  2. Loop Function: The loop function is executed repeatedly as long as the microcontroller is powered on. Inside the loop, it performs the following actions:
    • ESP.getFlashChipRealSize(): Retrieves the actual size of the flash memory chip.ESP.getFlashChipSize(): Retrieves the size of the flash memory chip as defined in the IDE settings.ESP.getFlashChipMode(): Retrieves the flash mode of the chip as defined in the IDE settings.
    The sketch then prints out the retrieved values via serial communication, along with additional information about the flash chip configuration.
    • If the actual size of the flash memory chip (realSize) differs from the size defined in the IDE settings (ideSize), it indicates a configuration mismatch, and a corresponding error message is printed.
    • If the sizes match, the sketch prints a message indicating that the flash chip configuration is correct.
  3. Delay: After printing the flash chip configuration, the loop waits for 5 seconds before repeating the process.

This sketch is useful for verifying that the EEPROM settings in the IDE match the actual hardware configuration of the ESP8266 chip. It can help troubleshoot issues related to flash memory configuration mismatches.

Code

/* 
  https://www.aruneworld.com/embedded/espressif/esp8266/esp8266_arduino-core/esp8266_arduino-core-basics/
  Tested By  : Arun(20170219)
  Example Name : AEW_CheckFlashConfiguration.ino
 
 
 ESP8266 CheckFlashConfig by Markus Sattler
 
 This sketch tests if the EEPROM settings of the IDE match to the Hardware
 
 */

void setup(void) {
    Serial.begin(115200);
}

void loop() {

    uint32_t realSize = ESP.getFlashChipRealSize();
    uint32_t ideSize = ESP.getFlashChipSize();
    FlashMode_t ideMode = ESP.getFlashChipMode();

    Serial.printf("Flash real id:   %08X\n", ESP.getFlashChipId());
    Serial.printf("Flash real size: %u\n\n", realSize);

    Serial.printf("Flash ide  size: %u\n", ideSize);
    Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
    Serial.printf("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));

    if(ideSize != realSize) {
        Serial.println("Flash Chip configuration wrong!\n");
    } else {
        Serial.println("Flash Chip configuration ok.\n");
    }

    delay(5000);
}

ESP8266 Arduino-Core Interface – ADC

ADC

Required

  • Required Hardware – ESP8266 with Programmer (or)  NodeMCU Dev Kit
  • Required Software Tools  – Arduino IDE with ESP8266 Core

Circuit

Code

/* 
  http://www.ArunEworld.com/Embedded/ESPressif/ESP8266/ESP8266_Arduino-Core/
  Tested By  : Arun(20170219)
  Example Name : AEW_ADC-Interface.ino
 */
 /*
  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
}

 

Result

3
2
3
4
3
3
4
3
2
3
4
2
2

 


Next :

Previous :


 

ESP8266 Arduino-Core Interface – Button

Button – Digital Read Serial

  • Required Hardware ESP8266 with Programmer (or)  NodeMCU Dev Kit
  • Required Software Tools Arduino IDE with ESP8266 Core

Code

/* 
  http://www.ArunEworld.com/Embedded/ESPressif/ESP8266/ESP8266_Arduino-core/ESP8266-Arduino-Core-Interface-Button
  Tested By  : Arun(20170219)
  Example Name : AEW_ADC-Interface.ino
 */
 /*
  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
}

 

Output

0
1
1
1
0
0

 


Next :

Previous :