echo '' ;

Archives

ESP32 Mongoose OS Interface -MQTT

 

Mongoose OS Credentials configure

Two way to configure the MQTT Credentials  in Mongoose OS file. This Example tested with mongoose os , demo-js app, windows 10, 64bit, mos tool, ESP32 DevKitC from ESPressif.

  • First one is using mos tool  UI
    • GO to 127.0.0.1:1992/  –> Device Config  –> Change the MQTT Credential in MQTT Setting  and Save with Reboot
    • Afterwards its generate the new file name is conf9.json
  • Second methods is change the mqtt Credential in conf0.json  file

 

Required

  • ESP32 Any kind of boards
  • Mongoose OS firmware
  • Mos Tool
  • MQTT Server Credentials
  • WiFi Crendentials

Note : This ESP32 Mongoose OS interface – MQTT is tested with Windows 10 64bit machine, mos tool(Web Browser based IDE for Mongoose OS), ESp32 DevkitC board from ESPressif.

 

Follow

  • Make sure already set your WiFi Credentials (otherwise MQTT is not work, also check the MQTT Connected status in Terminal windows)

 

Code : init.js  file

load('api_config.js');
load('api_events.js');
load('api_gpio.js');
load('api_mqtt.js');
load('api_sys.js');

let button = Cfg.get('pins.button');
let topic = '/devices/' + Cfg.get('device.id') + '/events';

print('button GPIO:', button);

let getInfo = function() {
  return JSON.stringify({
    total_ram: Sys.total_ram(),
    free_ram: Sys.free_ram()
  });
};

// Publish to MQTT topic on a button press. Button is wired to GPIO pin 0
GPIO.set_button_handler(button, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 20, function() {
  let message = getInfo();
  let ok = MQTT.pub(topic, message, 1);
  print('Published:', ok, topic, '->', message);
}, null);

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

 

Output

  • Results : {“free_ram”:148676,”total_ram”:229296}
  • Topic : /device/esp32_0255EC/events

 


 

 

ESP32 Get Start


let Get Start with ESP32,

ESP32 Features

  • The ESP32 WiFi and Bluetooth chip is the generation of Espressif products.
  • It has a dual-core 32-bit MCU, which integrates WiFi HT40 and Bluetooth/BLE 4.2 technology inside.
  • It is equipped with a high-performance dual-core Tensilica LX6 MCU.
  • One core handles high-speed connection and the other for standalone application development.
  • The dual-core MCU has a 240 MHz frequency and a computing power of 600 DMIPS.
  • In addition, it supports Wi-Fi HT40, Classic Bluetooth/BLE 4.2, and more GPIO resources.
  •  ESP32 chip integrates a wealth of hardware peripherals, including Capacitive touch sensors, Hall sensors, low noise sensor amplifiers, SD card interfaces, Ethernet interfaces,  High-speed SDIO / SPI, UART,  I2S, and I2C, etc. Lets ESP32 get the Start
Read more… →

ESP32 ArduinoCore Interface – OW (DS18B20)

The ESP32 ArduinoCore Interface for OneWire (OW) communication protocol is a crucial aspect of interfacing with digital temperature sensors like the DS18B20. This interface allows the ESP32 microcontroller to communicate with one or more DS18B20 temperature sensors using the OneWire protocol.

Read more: ESP32 ArduinoCore Interface – OW (DS18B20)

Components

ComponentDescription
ESP32 MicrocontrollerA powerful microcontroller with built-in Wi-Fi and Bluetooth capabilities.
DS18B20 Temperature SensorsDigital temperature sensors manufactured by Maxim Integrated, known for high accuracy readings.
OneWire LibraryProvides functions for communication over the OneWire bus, essential for interfacing with DS18B20 sensors.
DallasTemperature LibrarySimplifies communication with DS18B20 sensors by providing high-level functions and features.

Code

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 22
#define TEMPERATURE_PRECISION 12 // Lower resolution

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

int numberOfDevices;
DeviceAddress tempDeviceAddress;

void setup(void) {
  Serial.begin(115200);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
  numberOfDevices = sensors.getDeviceCount();
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(numberOfDevices, DEC);
  Serial.println(" devices.");
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");
  for(int i=0;i<numberOfDevices; i++) {
    if(sensors.getAddress(tempDeviceAddress, i)) {
      Serial.print("Found device ");
      Serial.print(i, DEC);
      Serial.print(" with address: ");
      printAddress(tempDeviceAddress);
      Serial.println();
      Serial.print("Setting resolution to ");
      Serial.println(TEMPERATURE_PRECISION, DEC);
      sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);
      Serial.print("Resolution actually set to: ");
      Serial.print(sensors.getResolution(tempDeviceAddress), DEC);
      Serial.println();
    } else {
      Serial.print("Found ghost device at ");
      Serial.print(i, DEC);
      Serial.print(" but could not detect address. Check power and cabling");
    }
  }
  delay(5000);
}

void printTemperature(DeviceAddress deviceAddress) {
  float tempC = sensors.getTempC(deviceAddress);
  Serial.print("Temp C: ");
  Serial.println(tempC);
  Serial.print("Temp F: ");
  Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}

void loop(void) { 
  Serial.print("Requesting temperatures...");
  sensors.requestTemperatures();
  Serial.println("DONE");
  for(int i=0;i<numberOfDevices; i++) {
    if(sensors.getAddress(tempDeviceAddress, i)) {
      Serial.print("Temperature for device: ");
      Serial.println(i,DEC);
      printTemperature(tempDeviceAddress);
      delay(3000);
    }
  }
}

void printAddress(DeviceAddress deviceAddress) {
  for (uint8_t i = 0; i < 8; i++) {
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

Code Explanation

Code SectionExplanation
#include <OneWire.h>Includes the OneWire library for communication with devices using the OneWire protocol.
#include <DallasTemperature.h>Includes the Dallas Temperature library for interfacing with Dallas/Maxim temperature ICs.
#define ONE_WIRE_BUS 22Defines the GPIO pin (pin 22) where the OneWire data wire is connected to the ESP32.
#define TEMPERATURE_PRECISION 12Defines the resolution for temperature readings (12 bits for lower resolution).
OneWire oneWire(ONE_WIRE_BUS);Initializes a OneWire object with the specified GPIO pin.
DallasTemperature sensors(&oneWire);Initializes a DallasTemperature object using the previously created OneWire object.
int numberOfDevices;Declares a variable to store the number of temperature devices found on the bus.
DeviceAddress tempDeviceAddress;Declares a variable to store the address of a found temperature device.
void setup(void)Begins the setup function, which is called once when the program starts. Initializes serial communication and the sensor library.
Serial.begin(115200);Starts serial communication with a baud rate of 115200.
sensors.begin();Initializes the Dallas Temperature library.
numberOfDevices = sensors.getDeviceCount();Retrieves the number of temperature devices found on the OneWire bus.
for(int i=0;i<numberOfDevices; i++)Loops through each temperature device found on the bus.
sensors.getAddress(tempDeviceAddress, i)Retrieves the address of the i-th device and stores it in tempDeviceAddress.
sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);Sets the resolution of the temperature device to the defined precision.
void printTemperature(DeviceAddress deviceAddress)Declares a function to print the temperature of a device with the given address.
void loop(void)Begins the loop function, which runs continuously after setup.
sensors.requestTemperatures();Requests temperature readings from all connected devices on the bus.
for(int i=0;i<numberOfDevices; i++)Loops through each temperature device found on the bus.
printTemperature(tempDeviceAddress);Prints the temperature of the i-th device.
void printAddress(DeviceAddress deviceAddress)Declares a function to print the address of a device.

Functionality of

  1. Initialization: The interface initializes the OneWire communication by defining the GPIO pin to which the OneWire data wire is connected. It also initializes the DallasTemperature library, which simplifies communication with DS18B20 sensors.
  2. Device Detection: Upon initialization, the interface detects the number of DS18B20 sensors connected to the OneWire bus. It retrieves the unique address of each sensor and sets their resolution if detected.
  3. Temperature Reading: The interface periodically requests temperature readings from all connected DS18B20 sensors. It then retrieves the temperature data and converts it to Celsius and Fahrenheit scales for further processing or display.

NEXT

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

ESP32 ArduinoCore Interface – ADC

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

ADC

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

ADC Pins

PinADC ChannelGPIO Number
GPIO32ADC1_CH432
GPIO33ADC1_CH533
GPIO34ADC1_CH634
GPIO35ADC1_CH735
GPIO36ADC1_CH036
GPIO37ADC1_CH137
GPIO25ADC2_CH825
GPIO26ADC2_CH926

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

Code

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

  This example code is in the public domain.
*/

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

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

Code Explanation of ESP32 ArduinoCore Interface ADC

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

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

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

Loop Routine:

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

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

Advantage of ESP32 ArduinoCore Interface ADC

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

NEXT

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

ESP32 Mongoose-OS Interface – WiFi

WiFi Status Monitor

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

 


Next :

Previous :


 

ESP32 NodeMCU Module – Net

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

Read more: ESP32 NodeMCU Module – Net

Functions

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

Ex : Create a server Connection

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

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

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

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

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

Ex : Receive function

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

Ex : Web server function

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

TCP Server Connection(Client)

here the code for ESP32 NodeMCU Net Module example

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


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


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

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

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

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

ESP32 NodeMCU Module – I2C Interface

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

Read more: ESP32 NodeMCU Module – I2C Interface

Pr-Request to Lean


ESP32 NodeMCU Module I2C Functions

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

Code of ESP32 I2C Scanner

  • In this code used to can the i2c Devices
  • Used Software i2c and GPIO-23 as SDA and GPIO-22 as SCL of I2C Device
  • Connected DS3231 Device and check i2c address of DS3231
-- setup
id  =   i2c.SW                      --  Software
pinSDA  =   23                      --  1~12, IO index
pinSCL  =   22                      --  1~12, IO index
speed   =   i2c.SLOW                    --  only i2c.SLOW supported

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

print("Scanning Started....")
for count = 0,127 do
  i2c.start(id)                         --  Send an I²C start condition.
  Status = i2c.address(id, count, i2c.TRANSMITTER)      --  Setup I²C address and read/write mode for the next transfer.
  i2c.stop(id)                          --  Send an I²C stop condition.
    if Status == true then
        print("Addrss - "..count.." Detected device address is  0x" .. string.format("%02x", count) .. " (" .. count ..")") 
    elseif Status == false then
        print("Addrss - "..count.." nil") 
    end
end
print("Scanning End")

Results

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

ESP32 NodeMCU I2C Interface: Code Explanation

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

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

Suggest


NEXT

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

ESP32 Lua-RTOS – IDE Setup and Firmware Flash

Lua RTOS is an open-source real-time operating system (RTOS) designed to run Lua applications on microcontrollers and other embedded systems. It aims to provide a lightweight and efficient platform for developing embedded applications with Lua scripting capabilities.Here will discuss ESP32 Lua RTOS Flash Firmware tutorial.

Overall, Lua RTOS is a versatile and lightweight operating system that empowers developers to build embedded applications with Lua scripting capabilities. Its integration with popular microcontroller platforms and active community support make it a compelling choice for IoT and embedded systems development. We tested with EPSressif ESP-Wroom-32 Dev Board and ESP32 Core firmware with the ESPressif Flash tool.

Read more: ESP32 Lua-RTOS – IDE Setup and Firmware Flash

Overview of Lua RTOS

FeatureDescription
LanguageLua RTOS is built on Lua, a lightweight scripting language. Lua is known for its simplicity, ease of use, and flexibility, making it ideal for embedded systems development.
Real-Time Operating SystemLua RTOS provides a real-time operating system (RTOS) environment for embedded systems. It offers task scheduling, inter-task communication, and synchronization mechanisms.
Supported HardwareLua RTOS supports various microcontroller architectures, including ESP32, ESP8266, STM32, and others. It is highly portable and can be adapted to different hardware platforms.
MultitaskingLua RTOS enables multitasking, allowing multiple Lua scripts to run concurrently as separate tasks. Tasks can communicate and synchronize through message passing and semaphores.
File SystemLua RTOS includes a file system API for accessing files on external storage devices such as SD cards or SPI flash memory. It supports file operations like reading, writing, and listing.
NetworkingLua RTOS supports networking protocols such as TCP/IP, UDP, MQTT, and HTTP. It allows embedded devices to communicate over Ethernet, Wi-Fi, or other network interfaces.
Peripheral SupportLua RTOS provides APIs for interfacing with various peripherals such as GPIO, UART, SPI, I2C, ADC, DAC, and more. Developers can easily control and communicate with hardware components.
Development EnvironmentLua RTOS development can be done using lightweight text editors or integrated development environments (IDEs) with Lua support. It offers flexibility in choosing development tools.
CommunityLua RTOS has an active community of developers and users who contribute to its development, share knowledge, and provide support through forums, mailing lists, and social media.

This table summarizes the key features and characteristics of Lua RTOS, providing an overview of its capabilities and suitability for embedded systems development.

Setting up Lua RTOS

StepDescription
1. Obtain Lua RTOSDownload Lua RTOS from the official repository or source.
2. Install prerequisitesInstall any required dependencies, such as Git and GCC, according to Lua RTOS documentation.
3. Set up development environmentConfigure your development environment, including setting up a terminal and text editor.
4. Initialize project directoryCreate a new directory for your Lua RTOS project.
5. Write your Lua codeDevelop Lua scripts and application logic within the project directory.
6. Configure Lua RTOSCustomize Lua RTOS configuration files to match your project requirements.
7. Compile Lua RTOSUse the provided build system to compile Lua RTOS for your target hardware platform.
8. Flash Lua RTOSFlash the compiled Lua RTOS image to your target hardware using tools like esptool.py.
9. Test your applicationVerify the functionality of your Lua RTOS application on the target hardware platform.
10. Iterate and improveContinuously refine your Lua RTOS application based on testing feedback and requirements.

Firmware

Where to get Lua-RTOS firmware? (Pr-compiled binaries)


Flash Tool

The software and hardware resources required for downloading firmware to flash are
listed below.

  • Hardware:
    o 1 x module to which firmware is downloaded
    o 1 x PC (Windows 7 [64 bits], Windows 10)
  • Software:
    Download Tool: Flash Download Tool ESpressif Flash Download Tool,

This tool supports the following SOCs

  • ESP32 series
  • ESP8266 series
  • ESP32-S2 series
  • ESP32-C3 series
  • ESP32-S3 series
  • ESP32-C2 series
  • ESP32-C6 series
  • ESP32-H2 series

Steps to follow

Download the appropriate firmware for your ESP32 board from the provided link. Once you’ve downloaded the appropriate firmware, unzip the file anywhere on your machine. Similarly, download the Flash tool from the same link and unzip it. Next, open the flash tool designed for ESP32 and configure the following parameters:

  • Baud rate: 921600
  • Flash mode: “dio”
  • Flash frequency: “40m”

For flashing the firmware, use the following addresses:

  • Bootloader.WHITECAT-ESP32-N1.bin – Address: 0x1000
  • lua_rtos.WHITECAT-ESP32-N1.bin – Address: 0x10000
  • partitions_singleapp.WHITECAT-ESP32-N1.bin – Address: 0x8000

For flashing the file system, use:

  • spiff_image.WHITECAT-ESP32-N1.Bin

Once the flashing process is complete, you’re all set.

Note: Make sure to adjust the “esp-idf path” and “usb path” as per your requirements.


Connect to the Console

Connect any UART Serial Tool to your device and configure the following parameters:

  • Speed: 115200 bauds
  • Data bits: 8
  • Stop bits: 1
  • Parity: None
  • Terminal emulation: VT100

Ensure these settings are accurately configured for seamless communication between your devices.

after connecting esp32 to the PC you will see the following.

   /\       /\
  /  \_____/  \
/_____________\
W H I T E C A T

Lua RTOS beta 0.1 build 1479953238 Copyright (C) 2015 - 2017 whitecatboard.org
cpu ESP32 at 240 Mhz
spiffs0 start address at 0x180000, size 512 Kb
spiffs0 mounted
spi2 at pins sdi=012/sdo=013/sck=014/cs=015
sd0 is at spi2, pin cs=015
sd0 type II, size 1943552 kbytes, speed 15 Mhz
sd0a partition type 0b, sector 227, size 1943438 kbytes
fat init file system
fat0 mounted
redirecting console messages to file system ...

Lua RTOS beta 0.1 powered by Lua 5.3.4


Executing /system.lua ...
Executing /autorun.lua ...

/ >

ESP32 Lua RTOS Flash Firmware tutorial

ESP32 Mongoose OS – Basic Examples

This article is about ESP32 Mongoose OS – Basic Examples, Let’s go through a basic example of using UART (Universal Asynchronous Receiver-Transmitter), Button and blinking an LED using an ESP32 by Mongoose OS.

Mongoose OS is an open-source IoT operating system designed for low-power, connected microcontrollers. Below is a basic example to get you started with Mongoose OS on an ESP32. This example demonstrates how to create a simple firmware that blinks an LED.

This is a basic example to help you get started with Mongoose OS on an ESP32. It blinks an LED using the GPIO capabilities provided by Mongoose OS. From here, you can explore additional features and libraries provided by Mongoose OS to build more sophisticated IoT applications. Refer to the Mongoose OS documentation for detailed information and advanced usage.

Setup Required

  • PC
  • UART Terminal (Putty, Visual Studio Serial Terminal, DockLight)
  • LEDs

UART Serial

Print words, string, text, symbols

print('------------****************----------------');
print('ArunEworld');

ESP32 Mongoose OS – Basic Examples of UART Communication

// https://github.com/cesanta/mongoose-os/blob/master/fw/examples/mjs_uart/init.js
// Load Mongoose OS API
load('api_timer.js');
load('api_uart.js');
load('api_sys.js');

// Uart number used for this example
let uartNo = 1;
// Accumulated Rx data, will be echoed back to Tx
let rxAcc = "";

let value = false;

// Configure UART at 115200 baud
UART.setConfig(uartNo, {
  baudRate: 115200,
  esp32: {
    gpio: {
      rx: 16,
      tx: 17,
    },
  },
});

// Set dispatcher callback, it will be called whenver new Rx data or space in
// the Tx buffer becomes available
UART.setDispatcher(uartNo, function(uartNo, ud) {
  let ra = UART.readAvail(uartNo);
  if (ra > 0) {
    // Received new data: print it immediately to the console, and also
    // accumulate in the "rxAcc" variable which will be echoed back to UART later
    let data = UART.read(uartNo);
    print("Received UART data:", data);
    rxAcc += data;
  }
}, null);

// Enable Rx
UART.setRxEnabled(uartNo, true);

// Send UART data every second
Timer.set(1000 /* milliseconds */, true /* repeat */, function() {
  value = !value;
  UART.write(
    uartNo,
    "Hello UART! "
      + (value ? 'Tick' : 'Tock')
      + " uptime: " + JSON.stringify(Sys.uptime())
      + " RAM: " + JSON.stringify(Sys.free_ram())
      + (rxAcc.length > 0 ? (" Rx: " + rxAcc) : "")
      + "\n"
  );
  rxAcc = "";
}, null);

GPIO Module

Read more… →

ESP32 ArduinoCore Interface – Wi-Fi

The ESP32 ArduinoCore interface for Wi-Fi provides a straightforward and flexible way to enable Wi-Fi connectivity in projects developed using the ESP32 microcontroller platform with the Arduino IDE. With this interface, developers can easily incorporate Wi-Fi functionality into their projects, enabling devices to connect to wireless networks, access the internet, and communicate with other devices over Wi-Fi.

Features and Capabilities

  1. Access Point (AP) Mode: The ESP32 can act as an access point, allowing other devices to connect to it and access resources or services hosted by the ESP32.
  2. Station (STA) Mode: The ESP32 can connect to existing Wi-Fi networks as a client, enabling devices to access the internet or communicate with other networked devices.
  3. Soft Access Point (SoftAP) Mode: This mode enables the ESP32 to simultaneously act as both an access point and a station, allowing it to connect to an existing Wi-Fi network while also providing Wi-Fi access to other devices.
  4. Wi-Fi Protected Setup (WPS): The ESP32 supports WPS, a method for easily configuring Wi-Fi network security settings without needing to enter a password manually.
  5. Advanced Configuration Options: The interface provides access to advanced configuration options for fine-tuning Wi-Fi settings, such as specifying static IP addresses, setting up captive portals, and configuring Wi-Fi sleep modes to optimize power consumption.
  6. Event Handling: Developers can implement event handlers to respond to Wi-Fi-related events, such as successful connections, disconnections, or errors, allowing for more robust and responsive Wi-Fi functionality.
  7. Security Features: The ESP32 ArduinoCore interface supports various Wi-Fi security protocols, including WPA and WPA2, to ensure secure communication over Wi-Fi networks.

Overall, the ESP32 ArduinoCore interface for Wi-Fi simplifies the process of adding Wi-Fi connectivity to ESP32-based projects, making it easier for developers to create IoT devices, home automation systems, and other wireless applications.

Scan WiFi

Note: You can use Arduino example code instead of the below code because both are the same  (File > Example > WiFi> WiFiScan)

/* https://aruneworld.com/embedded/espressif/esp32
 * Tested By  : Arun(20170429)
 * Example Name : AEW_WiFi_Scan.ino
 *  This sketch demonstrates how to scan WiFi networks.
 *  The API is almost the same as with the WiFi Shield library,
 *  the most obvious difference being the different file you need to include:
 */
#include "WiFi.h"

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

    // Set WiFi to station mode and disconnect from an AP if it was previously connected
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);

    Serial.println("Setup done");
}

void loop()
{
    Serial.println("scan start");

    // WiFi.scanNetworks will return the number of networks found
    int n = WiFi.scanNetworks();
    Serial.println("scan done");
    if (n == 0) {
        Serial.println("no networks found");
    } else {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i) {
            // Print SSID and RSSI for each network found
            Serial.print(i + 1);
            Serial.print(": ");
            Serial.print(WiFi.SSID(i));
            Serial.print(" (");
            Serial.print(WiFi.RSSI(i));
            Serial.print(")");
            Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
            delay(10);
        }
    }
    Serial.println("");

    // Wait a bit before scanning again
    delay(5000);
}

Serial Terminal Output

scan start
scan done
5 networks found
1: ArunEworld (-34)*
2: Exuber_365 (-59)*
3: Bangalore Police (-66)*
4: Tagos-2.4 (-80)*
5: RRL_Internet (-93)*

Code Explanation

Certainly! Here’s the code with explanations provided as snippets:

#include "WiFi.h"

This line includes the WiFi library necessary for working with WiFi on the ESP32.

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

    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);

    Serial.println("Setup done");
}

In the setup() function:

  • The code initializes serial communication at a baud rate of 115200.
  • The WiFi mode is set to station mode (WIFI_STA) and any previous connection is disconnected using WiFi.disconnect().
  • The code adds a delay of 100 milliseconds.
  • The code prints “Setup done” to the serial monitor.
void loop()
{
    Serial.println("scan start");

    int n = WiFi.scanNetworks();
    Serial.println("scan done");

    if (n == 0) {
        Serial.println("no networks found");
    } else {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i) {
            Serial.print(i + 1);
            Serial.print(": ");
            Serial.print(WiFi.SSID(i));
            Serial.print(" (");
            Serial.print(WiFi.RSSI(i));
            Serial.print(")");
            Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
            delay(10);
        }
    }

    Serial.println("");

    delay(5000);
}

In the loop() function:

  • The code begins by printing “scan start” to the serial monitor.
  • Next, the ESP32 scans for nearby WiFi networks using the WiFi.scanNetworks() function, storing the number of networks found in variable n.
  • After completing the scan, the code prints “scan done” to the serial monitor.
  • The code prints the number of networks found when it detects networks, followed by details of each network, including index, SSID (network name), RSSI (signal strength), and encryption type.
  • If no networks are found (when n == 0), the message “no networks found” is printed.
  • When networks are found, the code prints the number of networks found, followed by details of each network, including index, SSID (network name), RSSI (signal strength), and encryption type.
  • Finally, the code adds a delay of 5 seconds before initiating the next scan.

These snippets provide an overview of how the code initializes WiFi and continuously scans for nearby networks, printing details to the serial monitor.

ESP32 ArduinoCore Interface – Basic Example

When programming the ESP32 using the Arduino IDE, you typically use the ESP32 Arduino core, which provides a set of libraries and APIs to facilitate development. In this tutorial, we can discuss ESP32 ArduinoCore Interface Basic Example of Serial, GPIO, Timer, etc

Explore the fundamental features of the ESP32 microcontroller through an introductory example utilizing the ArduinoCore interface. This tutorial covers Serial communication, GPIO configuration for digital input and output, and Timer usage for precise timing operations. Ideal for beginners and hobbyists, this basic example demonstrates how to implement essential functionalities such as blinking an LED, reading button inputs, and handling timer interrupts, providing a solid foundation for further exploration and development with the ESP32 platform.”

Read more… →

ESP32 Lua-RTOS Module – PIO

The PIO (Programmable Input/Output) module in the ESP32 Lua-RTOS is a versatile feature that allows users to configure and control the GPIO pins of the ESP32 microcontroller dynamically. It provides an interface for performing various operations such as digital input, digital output, and pulse-width modulation (PWM) generation, among others.

Functionalities and Capabilities

  1. Digital Input/Output: The PIO module allows users to configure GPIO pins as digital inputs or outputs. Digital inputs can be used to read the state of external sensors or switches, while digital outputs can drive external devices such as LEDs, relays, or motors.
  2. Interrupt Handling: It supports interrupt handling on GPIO pins, allowing users to trigger actions based on changes in pin states. This feature is useful for implementing event-driven applications where real-time responses to external events are required.
  3. Pull-up/Pull-down Resistors: The PIO module enables users to enable or disable the internal pull-up or pull-down resistors on GPIO pins, ensuring stable and reliable signal readings.
  4. Pulse-Width Modulation (PWM): It provides support for generating PWM signals on GPIO pins, allowing users to control the intensity of analog devices such as LEDs, motors, or servos.
  5. Pin Configuration: Users can dynamically configure the functionality and characteristics of GPIO pins using the PIO module, including setting pin modes (input/output), configuring interrupt triggers, and adjusting PWM parameters.
  6. Low-Level Access: The PIO module offers low-level access to GPIO pins, allowing users to directly manipulate pin states and registers for advanced control and customization.
  7. Resource Management: It provides mechanisms for managing GPIO pin resources efficiently, preventing conflicts and ensuring proper allocation of resources across different tasks or modules.

Overall, the PIO module in the ESP32 Lua-RTOS enhances the flexibility and versatility of the ESP32 microcontroller, enabling users to implement a wide range of GPIO-based applications with ease and efficiency. Whether for simple digital I/O tasks or more complex PWM generation and interrupt handling, the PIO module offers powerful capabilities for interacting with external devices and sensors in Lua-RTOS projects.

Read more… →

ESP32 – Board Types

The ESP32 is a versatile microcontroller with a variety of development boards available. Different ESP32 various board types have different features, pin configurations, and capabilities.

When working with an ESP32 board, make sure to select the appropriate board type in the Arduino IDE or the other platform you are using. This ensures that the correct pin configurations and settings are applied during programming. The availability of features can vary between different boards, so it’s essential to choose a board that aligns with the requirements of your project.

Read more… →