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 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 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… →