echo '' ;

Category Archives: Embedded

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>{{EJS0}}</code> tool from https://mongoose-os.com/software.html
//   2. Run <code>{{EJS1}}</code> tool and install Mongoose OS
//   3. In the UI, navigate to the <code>{{EJS2}}</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>{{EJS7}}</code> tool from https://mongoose-os.com/software.html
//   2. Run <code>{{EJS8}}</code> tool and install Mongoose OS
//   3. In the UI, navigate to the <code>{{EJS9}}</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 NodeMCU Project – 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 :


 

Embedded Interface – ADC

The analog-to-digital converter (ADC) converts the continuous analog signal into a flow of digital values. To achieve this, the converter must establish the rate at which new digital values sample from the analog signal. This rate is termed the sampling rate or sampling frequency of the converter.

Read more: Embedded Interface – ADC

ADC

A successive approximation ADC uses a comparator to narrow the input voltage range. Digital systems store values in binary format, with resolution usually in bits, often a power of two. Furthermore, one can define resolution electrically and represent it in volts. Consequently, we call the smallest voltage change needed to alter the output code level the least significant bit.

ADC Advantage:

AspectDescription
High PrecisionADCs provide high precision in converting analog signals into digital form, thereby ensuring an accurate representation of the original signal. Consequently, this precision allows for reliable data processing and analysis.
CompatibilityModern digital systems find digital signals more compatible, as they can easily process, transmit, and store them using digital devices. Additionally, this compatibility enhances the efficiency and effectiveness of digital systems in various applications.
Noise ImmunityDigital signals are less susceptible to noise interference during transmission or processing compared to analog signals. Consequently, this leads to better signal integrity and more reliable data transmission in digital communication systems.
Signal ProcessingDigital signals allow for advanced signal processing techniques such as filtering, modulation, and encryption. As a result, this enhances the versatility of digital systems, enabling them to adapt to a wide range of applications and requirements.
Ease of IntegrationADCs can be integrated into various electronic devices, providing a seamless interface between analog sensors or sources and digital processing units. Consequently, this integration enhances the functionality and performance of electronic systems by enabling accurate and efficient conversion of analog signals into digital data.

Disadvantage:

AspectDescription
Sampling Rate LimitationsADCs are limited by their sampling rate, which determines the maximum frequency of signals they can accurately capture. Consequently, inadequate sampling rates can lead to aliasing and loss of signal fidelity, compromising the accuracy of the digital representation of analog signals.
Quantization ErrorDuring the analog-to-digital conversion process, quantization error can occur. Consequently, this can lead to inaccuracies in the representation of the original analog signal, affecting the fidelity of the digital output.
Complexity and CostHigh-resolution ADCs, capable of accurately capturing fine details in analog signals, can be complex and expensive. Consequently, for applications demanding high-speed or high-precision conversion, these ADCs may pose challenges due to their complexity and cost.
Conversion TimeADCs require a finite amount of time to convert analog signals into digital form. As a result, this causes latency in real-time systems or applications that demand rapid signal processing.
Dynamic Range LimitationsADCs have a limited dynamic range, which can affect their ability to accurately capture signals with a wide range of amplitudes. Consequently, this limitation can potentially cause distortion or loss of information in the converted signal, particularly when dealing with signals of varying amplitudes.

Features of ADC

  1. Resolution: This refers to the number of bits used to represent the analog input in digital form. Higher resolution ADCs can represent smaller voltage changes, providing greater precision.
  2. Sampling Rate: The rate at which the ADC samples the analog input signal and converts it into digital form. It is typically measured in samples per second (SPS) or Hertz (Hz).
  3. Input Range: The range of analog input voltages that this can accurately convert into digital values without distortion or clipping.
  4. Accuracy: This refers to how closely the digital output of the ADC matches the true analog input signal.
  5. Speed: The time taken by the ADC to complete one conversion cycle, including sampling and conversion.

ADC Application

ApplicationDescription
Industrial AutomationADCs monitor and control analog sensors like temperature, pressure, and flow sensors in industrial automation systems.
Medical InstrumentationADCs convert signals from medical sensors like ECG or blood pressure monitors into digital data for analysis in medical instrumentation.
Audio ProcessingADCs convert analog audio signals from microphones or musical instruments into digital format for storage or processing in audio applications.
Automotive SystemsADCs are integrated into automotive systems for functions like engine control, airbag deployment, and sensor data acquisition for driver assistance systems.
Communication SystemsADCs convert analog signals, such as voice or data, into digital format for transmission over digital communication networks in communication systems.
Test and MeasurementADCs capture and analyze analog signals with high precision in test and measurement equipment, supporting applications like oscilloscopes and data loggers.
Consumer ElectronicsADCs in consumer electronics, like smartphones and digital cameras, convert various analog signals into digital data for processing or display.
Renewable Energy SystemsADCs monitor and control the generation and distribution of electrical power in renewable energy systems like solar or wind power inverters.

Next Topic

Embedded Interface 7 Segment (Add Soon)
Embedded Interface ADC (Add Soon)
Embedded Interface Button (Add Soon)
Embedded Interface EEPROM (Add Soon)
Embedded Interface LCD (Add Soon)
Embedded Interface LCD HD44780 (Add Soon)
Embedded Interface LED
Embedded Interface MCP23017
Embedded Interface Motor (Add Soon)
Embedded Interface PCF8574 and PCF8574A
Embedded Interface RTC (Add Soon)
Embedded Interface Switch
Embedded Interface Touch Kypad
Embedded Interface RGB LED (Add Soon)

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 :


 

ESP8266 NodeMCU Interface – LED

LED ON/OFF

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

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

 


LED Blink Using Timer

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

ESP8266 with LED Connection Diagram

  • Will Add Soon

NodeMCU Lua code

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

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

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

Follow steps

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

LED Blink uisng While loop and Timer delay function

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

     


LED Fade using PWM

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

     


 

 


Next :

Previous :


 

ESP8266 NodeMCU Project – Imperial March Ringtone Play


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

Read more… →

ESP8266 NodeMCU Tutorial – Web Server

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

Read more: ESP8266 NodeMCU Tutorial – Web Server

Simple Web Server

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

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

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

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

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

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

Code Explanation

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

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

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

TCP Server Listener

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

Code

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

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

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

Result

Host pot


Code Explanation

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

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

NEXT

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

ESP8266 NodeMCU Module – WiFi (End User Module)

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

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

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

WiFi NodeMCU Lua Module

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

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

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

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

General Functions:

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

Station Functions:

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

Access Point Functions:

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

Examples

Scan for available all station networks

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

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

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

wifi.sta.getap(listap)

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

wifi.sta.getap(listap)

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

wifi.sta.getap(1, listap)

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

wifi.sta.getap(1, listap)

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

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

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

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

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

scan_cfg = {}
scan_cfg.ssid = ssid

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

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

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

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

Sets the WiFi station configuration.

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

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

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

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

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

Connect ESP8266 to WiFi Router

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

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

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

Disconnect ESP8266 from WiFi Router

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

View the ESP8266 Stored Access Point information

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

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

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

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

Gets the WiFi station configuration.

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

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

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

Clears the currently saved WiFi station configuration

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

WiFi station status events

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

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

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

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

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

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

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

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

Gets current station hostname.

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

Sets station hostname.

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

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

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

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

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

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

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

Gets IP address, netmask and gateway in AP mode.

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

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

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

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

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

Gets MAC address in station mode.

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

Set MAC address in AP mode.

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

Retrieve the RSSI (Received Signal Strength Indicator).

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

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

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

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

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

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

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

Gets the current SoftAP configuration.

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

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

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

Retrieve the default SoftAP configuration stored in flash.

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

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

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

End User Setup NodeMCU Lua

ESP8266 NodeMCU WiFi End User Module

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

Example

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

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

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

NEXT

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

Embedded Interface – Motor

Example

  • DC Motor
  • Stepper Motor
    • Bipor Stepper Motor
    • Unipolar Stepper Motor.
  • Servo Motor

 

Next Topic

Embedded Interface 7 Segment (Add Soon)
Embedded Interface ADC (Add Soon)
Embedded Interface Button (Add Soon)
Embedded Interface EEPROM (Add Soon)
Embedded Interface LCD (Add Soon)
Embedded Interface LCD HD44780 (Add Soon)
Embedded Interface LED
Embedded Interface MCP23017
Embedded Interface Motor (Add Soon)
Embedded Interface PCF8574 and PCF8574A
Embedded Interface RTC (Add Soon)
Embedded Interface Switch
Embedded Interface Touch Kypad
Embedded Interface RGB LED (Add Soon)

Embedded Interface – LCD

LCD stands for Liquid Crystal Display. It’s a type of flat-panel display technology commonly used in TVs, computer monitors, smartphones, and other electronic devices. This work by sandwiching a layer of liquid crystals between two transparent electrodes and two polarizing filters. When an electric current passes through the liquid crystals, they align to allow varying amounts of light to pass through, creating images or text on the screen. LCDs are known for their sharp image quality, energy efficiency, and relatively low cost compared to other display technologies like OLED (Organic Light Emitting Diode).

Read more: Embedded Interface – LCD

Sure, here are some advantages and disadvantages of LCD displays:

Advantages:

  1. Energy Efficiency: LCDs typically consume less power compared to older display technologies like CRTs (Cathode Ray Tubes), making them more energy-efficient.
  2. Slim Profile: LCD panels are generally thin and lightweight, making them suitable for slim and portable devices such as laptops, tablets, and smartphones.
  3. Sharp Image Quality: LCDs can produce high-resolution images with excellent clarity and color accuracy, providing a visually pleasing viewing experience.
  4. Versatility: LCD technology is versatile and can be used in various applications, including TVs, computer monitors, digital signage, and automotive displays.
  5. Longevity: LCD panels have a relatively long lifespan compared to some other display technologies when properly maintained, providing years of reliable use.

Disadvantages:

  1. Limited Viewing Angles: LCDs may exhibit color distortion or brightness loss when viewed from extreme angles, making them less suitable for applications where multiple viewers may be viewing the screen from different angles.
  2. Potential Motion Blur: Some LCD displays, especially those with slower response times, may suffer from motion blur, resulting in less-than-optimal performance for fast-moving content such as gaming or sports.
  3. Backlight Uniformity Issues: LCDs rely on a backlight source to illuminate the screen, and sometimes there can be issues with backlight uniformity, leading to uneven brightness or “clouding” in certain areas of the display.
  4. Limited Contrast Ratio: While modern LCDs have improved contrast ratios, they may still not match the deep blacks and high contrast levels achievable with technologies like OLED.
  5. Risk of Dead Pixels: LCD panels may develop dead pixels over time, resulting in small, permanently lit or unlit spots on the screen, which can be distracting, especially in high-resolution displays.

Despite these disadvantages, LCD technology remains widely used and continues to be improved upon with advancements in backlighting, panel technology, and image processing algorithms.

Examples

  • Display Character
  • Display String
  • Display Decimal
    • Display one Digit Decimal
    • Display Two Digit Decimal
    • Display Three Digit Decimal
  • Auto scroll Display
  • Blink
  • Cursor On/Off
  • Custom Character
  • Display
  • Hello world
  • Scroll
  • Serial Display
  • Set Cursor
  • Text Direction

Interface with Micro-controllers

Different LCD Displays

  • Nokia 5110 LCD Module with PCD8544 
  • Nokia 6610 
  • OLEDs 
  • 2×16 LCD- hd44780 
  • Nextion Display 

Next Topic

Embedded Interface 7 Segment (Add Soon)
Embedded Interface ADC (Add Soon)
Embedded Interface Button (Add Soon)
Embedded Interface EEPROM (Add Soon)
Embedded Interface LCD (Add Soon)
Embedded Interface LCD HD44780 (Add Soon)
Embedded Interface LED
Embedded Interface MCP23017
Embedded Interface Motor (Add Soon)
Embedded Interface PCF8574 and PCF8574A
Embedded Interface RTC (Add Soon)
Embedded Interface Switch
Embedded Interface Touch Kypad
Embedded Interface RGB LED (Add Soon)

Embedded Interface – 7 Segment Display

Example

  • One 7-Segment Display
    • Display Character
    • Display Decimal
  • Multi 7 Segment Display
    • Display Character
    • Display Decimal

Next Topic

Embedded Interface 7 Segment (Add Soon)
Embedded Interface ADC (Add Soon)
Embedded Interface Button (Add Soon)
Embedded Interface EEPROM (Add Soon)
Embedded Interface LCD (Add Soon)
Embedded Interface LCD HD44780 (Add Soon)
Embedded Interface LED
Embedded Interface MCP23017
Embedded Interface Motor (Add Soon)
Embedded Interface PCF8574 and PCF8574A
Embedded Interface RTC (Add Soon)
Embedded Interface Switch
Embedded Interface Touch Kypad
Embedded Interface RGB LED (Add Soon)

Embedded Interface – Button

Examples

  • LED ON/OFF Using Button
  • Button De-bounce
  • Four Button (UP, DOWN, ENTER, BACK)
    • Set Value By Four_Buttons using 7 Segment Display
    • Set Value By Four_Buttons using LCD Display
  • Matrix Keypad
    • Set Value by Matrix Keypad using 7 Segment Display
    • Set Value by Matrix Keypad using LCD Display
    • Display characters by Matrix Keypad using 7 Segment Display
    • Display characters by Matrix Keypad using LCD Display

 

Next Topic

Embedded Interface 7 Segment (Add Soon)
Embedded Interface ADC (Add Soon)
Embedded Interface Button (Add Soon)
Embedded Interface EEPROM (Add Soon)
Embedded Interface LCD (Add Soon)
Embedded Interface LCD HD44780 (Add Soon)
Embedded Interface LED
Embedded Interface MCP23017
Embedded Interface Motor (Add Soon)
Embedded Interface PCF8574 and PCF8574A
Embedded Interface RTC (Add Soon)
Embedded Interface Switch
Embedded Interface Touch Kypad
Embedded Interface RGB LED (Add Soon)

Embedded Interface – LED

LED (Light Emitted Diode)

Symbol

How to Identify the LED’s Positive and Negative Leads ?

  • Long lead is positive(+) and small lead is negative(-)
  • Round circle lead is positive(+) and flat lead is negative(-)

LED Chemical Substance

Summary of LED’s Colors and Common Chemistries

ColorWavelengthMaterials
   
Amber605-620 nmGallium arsenide phosphide, Aluminum gallium indium phosphide
Blue430-505 nmIInGaN (Indium Gallium Nitride), Gallium nitride, Silicon carbide, Sapphire, Zinc selenide
Green550-570 nmAluminum gallium phosphide, Gallium nitride
Infra-Red850-940 nmGallium arsenide, AL GaAs (Aluminum Gallium Arsenide)
Red630-660 nmAL GaAs (Aluminum Gallium Arsenide), Gallium arsenide phosphide, Gallium phosphide
Ultraviolet370-400 nmIndium gallium nitride, Aluminum gallium nitride
Violet410-420nm 
Yellow585-595 nmAluminum gallium phosphide, Gallium arsenide phosphide, Gallium phosphide

Light wave length

WaveLenthLED APPLICATION
410nm-420nm(violet)Skin therapy
430nm-470nm(blue)Dental curing instrument
470nm(blue)White LED’s using phosphor, blue for RGB white
520nm-530nm(green)Green traffic signal lights, amber for RGBA white lights
580nm-590nm(amber)Red signal lights, red for RGBA white lights
630nm-640nm(red)Blood oximetry
660nm(deep red)Skin therapy
680nm(deep red)Night vision illuminators and beacons for use with night vision goggles or CCD’S
800nm-850nm(near IR)Photo electric controls
940nm(near IR)Convert illumination CCD based systems

Reference  : http://www.goldwynled.com/knowledge-bank/leds-basics


GLOW LEDs

LEDs ON

LEDs OFF

LEDs Blink

Application

  • Status Indicator
  • WiFi Router Status Indicator (Blink LEDs-Internet Status)
  • Charge level Indication in mobile power-bank [Blink LEDs – Single RGB LEDs or Multiple Color LEDs)
  • Bike Automation
    • Bike Turn Indicator (LED Blink – while turned)
    • Bike Side stand indicator (LED Glow -if Side stand is not took)
  • Car Automation
    • Car Turn Indicator (LED Blink – while turned)
    • Car Door Status indicator(LED Glow -if Door is not close or opened)

LED Examples

  • ON/OFF
  • Blink using the Delay Function
  • Blink using the Timer Function
  • Status Indicator(Using condition Check)Button

ESP32 NodeMCU Module – Net

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

Read more: ESP32 NodeMCU Module – Net

Functions

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

Ex : Create a server Connection

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

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

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

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

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

Ex : Receive function

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

Ex : Web server function

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

TCP Server Connection(Client)

here the code for ESP32 NodeMCU Net Module example

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


function Server_Run()
print("Server Running")
    srv = net.createConnection(net.TCP, 0)
    srv:on("receive", function(sck, c) print(c) end)
    -- Wait for connection before sending.
    srv:on("connection", function(sck, c)
    sck:send("ArunEworld IOT Projects")
    end)
    srv:connect(80,"192.168.4.1")
end


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

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

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

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