echo '' ;

Arduino Interface – Buzzer

In the realm of Arduino Interface Buzzer, can bring your projects to life with sound. We’ll explore how to connect and control a buzzer, from simple beeps to complex melodies. Throughout this guide, we’ll cover wiring, coding, and examples, whether you’re new to Arduino or a seasoned maker. Let’s dive in and unlock the potential of Arduino buzzers together!

So, let’s embark on this sonic journey and unlock the potential of Arduino interfacing with buzzers!

uses of buzzers

Use CaseDescription
Alarm SystemsBuzzers are commonly used in alarm systems to provide audible alerts for security breaches or emergencies.
Timers and RemindersBuzzers in timers and reminders signal task completion or remind users of events.
NotificationsBuzzers in electronics notify users of messages, alerts, or events.
Industrial MachineryBuzzers in industrial machinery signal malfunctions, task completion, or safety alerts.
Games and ToysIn gaming, arcade machines, and toys, buzzers create sound effects, enhancing the experience.
DIY ProjectsMakers use buzzers in DIY projects like interactive installations, instruments, or home automation.

Application of Buzzer

ApplicationDescription
Alarm SystemsBuzzers in security systems offer audible alerts for intrusions or emergencies.
Timer and Reminder SystemsBuzzers signal task completion or remind users of appointments in timers and reminders.
Industrial MachineryIn industry, buzzers in machinery signal errors, task completion, or safety alerts.
Home AppliancesBuzzers in appliances like microwaves, washers, and dishwashers signal cycle end or errors.
AutomotiveIn cars, buzzers signal seatbelt warnings, parking alerts, or low fuel levels.
Games and EntertainmentBuzzers enhance gaming experiences in consoles, arcades, and interactive toys with sound effects.

Circuit Diagram

Read more… →

Arduino Interface – UART(Serial)

This tutorial is “Arduino Interface UART(Serial)”. The Universal Asynchronous Receiver-Transmitter (UART) is a fundamental component in microcontroller communication, enabling data exchange between devices. In the realm of Arduino, mastering UART opens doors to interfacing with a plethora of sensors, actuators, and other devices.

Read more: Arduino Interface – UART(Serial)

In this guide, we’ll delve into the basics of UART communication with Arduino. Whether you’re a hobbyist embarking on your first Arduino project or an experienced developer seeking a refresher, this tutorial aims to demystify UART and equip you with the knowledge to integrate it seamlessly into your projects.

Let’s embark on this journey to unravel the intricacies of UART communication with Arduino, from understanding the principles behind UART to implementing it in your own circuits and code.

Use cases

The Arduino UART (Serial) interface offers a wide range of uses across various projects and applications.

ApplicationDescription
Sensor IntegrationInterface with various sensors like temperature sensors, IMUs, GPS modules for data collection.
Wireless CommunicationEstablish wireless links using Bluetooth, Wi-Fi, or Zigbee modules for remote control & IoT.
Display OutputCommunicate with LCDs, OLEDs to present information in projects like digital clocks, weather stations.
Data LoggingLog data to external storage devices for long-term recording in environmental monitoring, tracking systems.
Human-Machine InterfaceCommunicate with external devices like keypads, RFID readers for user interaction in systems.
Control InterfacesControl motors, relays, servo motors for robotics, automated systems, or interactive installations.
Debugging and Serial CommunicationUse for debugging, real-time monitoring, and data transfer between Arduino and PC.
Interfacing with Other DevicesCommunicate with other microcontrollers like Raspberry Pi, ESP8266, enabling collaborative projects.

Print Hello World in Serial terminal

Code

void setup() 
{
  Serial.begin(9600);
  while (! Serial); // Wait untilSerial is ready - Leonardo
  Serial.println("ArunEworld : Hello World");
}
 
void loop() 
{
 
}
Read more… →

Arduino Interface – RGB LED

The Arduino microcontroller platform’s versatility in interfacing with various components has earned it renown, making it a go-to for electronics and DIY projects. This tutorial is about “Arduino Interface RGB LED”. One exciting application is controlling RGB (Red, Green, Blue) LEDs to create a spectrum of colors, perfect for beginners and enthusiasts alike.

Read more… →

Arduino Interface – LED

This article is a continuation of the series on “Arduino Interface – LED” and carries the discussion on Turn ON/OFF, and blinking of LED in the Arduino Environment.

  • LED (light-emitting diode): LED is a simple diode that emits light in a forward bias
  • Arduino: is an open-source, board that has a Microchip ATmega328P microcontroller on it.

Pre-Request

  • PC
  • Arduino IDE setup or web-based IDE

Components Required

  • LED – 1 Nos,
  • Resistor, 220 Ohm – 1Nos
  • Breadboard (Optional: If required)
  • Arduino UNO
  • Jumper wires

Turn On/Off LED

The program simply turns ON and OFF LED with some delay between them.

  • For Turn OFF LED – Set digital pin Low digitalWrite(LED_BUILTIN, LOW);
  • For Turn ON LED – Set digital pin high digitalWrite(LED_BUILTIN, HIGH);

 

Read more… →

Embedded Interface – Switch

 

Slide Switch

 

Rotary Switch

 

Push Switch

These are either normally on (Push-to-break0, or normally off(Push-to-make). They can be latched, So they stay pressed down after you remove your finger, like the switches on a torch.

 

Micro Switch

 

Reed Switch

These are magnetically activated


 

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)
C Programming Language

C Quiz-1

Participating in a C quiz can offer several benefits for individuals looking to improve their programming skills and knowledge of the C programming language. Here are some potential advantages:

  1. Skill Enhancement: Quizzes often cover a range of topics within C programming, allowing participants to test and enhance their skills in areas such as syntax, data types, control structures, functions, and more.
  2. Knowledge Validation: Quizzes can help individuals gauge their understanding of key concepts in C programming. By answering questions, participants can identify areas where they need to focus on improving their knowledge.
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

Workshop : 20171001-Internet Of Things Using ESP8266

“If you think that the internet has changed your life, think again. The IoT is about to change it all over again!” –

— Brendan O’Brien, Aria systems


Workshop : Internet Of Things using ESP8266

ESP8266 is popular Wi-Fi chip and Internet of things is one of the fastest growing technologies. So we thought to conduct a technical workshop about IOT using ESP8266. You’ll learn the basic concepts and features of the Internet of Things and will be able to build projects using the ESP8266 NodeMCU platform. You’ll also discover fundamental concepts of cloud computing, sensor reading, connecting the ESP8266 to the Internet, wireless interfaces and controlling devices with Android phones. You’ll also learn to use the most popular open platforms for managing sensor data from the ESP8266, how to trigger actuators remotely, and how to read information on your Android Smart Phones. if you attend this workshop you will able to do IOT projects by you-self also you can help others to lean about IOT. Interested, can join this workshop. The duration is seven hours in a day and details are mentioned below and refer the image also.

Session-1 (Morning)

  • Overview of Internet of things.
  • Get started with ESP8266 and development board.
  • Basics interface : GPIO,Timer, File System, WiFi.
  • Basic Experiments : LED, RGB LED, Buzzer, Button, Relay.
  • Some More Experiments : PWM, WiFi, TCP, UDP, SNPT, RTC, MQTT.

Session-2 (Afternoon)

  • Real time Project 1 : Smart Device Control with monitor (Home Automation devices-Online/Offline).
  • Real Time Project 2 : Smart RGB Light (Online/Offline).
  • Project 3 : Network Status Indicator.
  • Project 4 : Data Logger.

Goal

  • Workshop is to make the students skill full and efficient for Internet of things related concepts.
  • The students to do their final year projects by them-self.
  • Apply Internet of things application in your day-to-day.

Participation Prerequisites

To participate in the workshop, you will need the following:

  • A laptop – Windows(Latest) and at least one free USB port with internet connection.
  • A micro-USB cable with data lines that fits your USB port.
  • A Mobile with WiFi, Host-spot feature and internet connection.
  • A breadboard and arduino board with cable.(Optional)
  • You will need a install this software( I will give at workshop)
  • Java
    • Windows Offline (32-Bit)
    • Windows Offline (64-bit)
  • Keep on this below software’s
    • ESPlorer
    • Notepad++. : Windows Offline (32-Bit)
  • Please note that the workshop will be in mostly English (Local Language-Prefers).

Participation will receive in additional, at the workshop!

  • Wi-Fi development board,
  • LED,
  • RGB LED,
  • Female-female connector cables,
  • Piezoelectric speaker,
  • Magnetic Reed Switch
  • Magnet
  • Certificate will provide end of the workshop to each participate,
  • End of the session we will provide all kind of workshop materials like PPT, documents, videos and source code.

Venue

Department of Electronics and Communication Engineering,
Mahendra Engineering College
Salem – Thiruchengode Highway,
Mahendhirapuri, Namakkal District,
Mallasamudram, Tamil Nadu, India-637503.


Registration

Note : Once you registered, you will get a conformation message to registered mobile and e-mail.

This event was held. you can’t register. contact Mr.Arun.

 


Payment Method

Note : You can pay the workshop fee by two ways – Online/Offline. One we received your payment you will get a message to your registered mobile and e-mail.

Online : Pay using Paytm

  • Pay workshop fee (money) scan QR code image
  • In Optional description write  “ArunEworld_Workshop_20170821” ,space. “You_Name” “ArunEworld_Workshop_20170821″<space>”You_Name”  (Ex : ArunEworld_Workshop_20170821 Raja)

Offline : Pay to Workshop organizer

Contact: Mr.Giri.K , Assistant Professor, Mahendra College of Engineering,

Contact Number : +919003503908.

 


Attendees List

Once you complete registration successfully, then your name will be listed below automatically.

 

 


Contact Organizer

Mr. Giri. K (girik@mahendra.info, +919003503908)
Department of Electronics and Communication Engineering,
Mahendra Engineering College
Salem – Thiruchengode Highway,
Mahendhirapuri, Namakkal District,
Mallasamudram, Tamil Nadu, India-637503.


Workshop full details and resource

Click this below link to see the syllabus, contents, videos and more, etc..

  • 20170807-Workshop_IOT_ESP8266 Details

 


 

ESP8266 NodeMCU Interface – ADXL345

The ESP8266 NodeMCU is a popular development board based on the ESP8266 microcontroller, which offers built-in Wi-Fi capabilities, making it ideal for Internet of Things (IoT) projects. In this project, we’ll explore how to interface the ESP8266 NodeMCU with the ADXL345 accelerometer sensor.

Read more: ESP8266 NodeMCU Interface – ADXL345

ADXL345

The ADXL345 is a small, thin, ultralow power, 3-axis accelerometer with high resolution (13-bit) measurement at up to ±16 g. It’s suitable for various applications, including tilt sensing, motion detection, and vibration monitoring.

By combining the ESP8266 NodeMCU with the ADXL345 sensor, we can create IoT applications that can monitor and analyze motion or vibrations remotely over Wi-Fi. This interface allows us to gather data from the accelerometer sensor and transmit it to a server, cloud platform, or display it on a web page.

Throughout this project, we’ll cover the hardware setup, including connecting the ADXL345 sensor to the ESP8266 NodeMCU, and the software implementation, which involves programming the ESP8266 NodeMCU to communicate with the ADXL345 sensor and transmit the data. With this interface, you’ll be able to leverage the power of the ESP8266 NodeMCU and the capabilities of the ADXL345 sensor to create versatile IoT applications for motion sensing and monitoring.

Code

Make sure you have the necessary libraries and setup to run this code on your hardware.

-- www.ArunEworld.com 
sda = 2 -- GPIO-4 
scl = 1 -- GPIO-5 

print("ArunEworld")

-- Initialize the ADXL345 sensor
adxl345.init(sda, scl)

-- Delay for 3000000 microseconds (3 seconds)
tmr.delay(3000000)

-- Read data from the ADXL345 sensor
print(adxl345.read())

-- Define a function to read accelerometer data
function ADXL_read() 
    -- Read accelerometer data
    local x, y, z = adxl345.read() 
    -- Print accelerometer data
    print("X-axis:", x)
    print("Y-axis:", y)
    print("Z-axis:", z)
    -- Alternatively, you can print all axes at once using the following line:
    -- print(string.format("X = %d, Y = %d, Z = %d", x, y, z))
end 

-- Set up a timer to call the ADXL_read function every 1000 milliseconds (1 second)
tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)

Code Explanation

LineCodeExplanation
1sda = 2Assigns pin 2 to the variable sda, representing the Serial Data (SDA) pin.
2scl = 1Assigns pin 1 to the variable scl, representing the Serial Clock (SCL) pin.
4print("ArunEworld")Prints the message “ArunEworld” to the console.
7adxl345.init(sda, scl)Initializes the ADXL345 sensor with the SDA and SCL pins defined earlier.
10tmr.delay(3000000)Delays the execution of the program for 3 seconds (3000000 microseconds).
13print(adxl345.read())Reads data from the ADXL345 sensor and prints it to the console.
16function ADXL_read() ... endDefines a function named ADXL_read to read accelerometer data from the ADXL345 sensor.
19tmr.alarm(0, 1000, tmr.ALARM_AUTO, ADXL_read)Sets up a timer to call the ADXL_read function every 1000 milliseconds (1 second) repeatedly.

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

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 :


 

PIC Interface – PWM

 

Functions

  • pwm_init()
  • pwm_dutycycle(unsigned int duty)

Example : Generate predefined PWM using four buttons

Code

  • Define Port-B as input and RB0, RB1, RB2 and RB3 used as button input
  • Generate PWM using PWM functions

Note  :  UN-command the line depend on your preferred compiler.

//www.ArunEworld.com/embedded/microchip/pic_mcu/
#include<pic.h> // for Hi-Tech Compiler

#define _XTAL_FREQ 4000000

//short currduty1=16;
void init()
{
    PORTB=0X00;
    TRISB=0X0f;
}

void pwm_dutycycle(unsigned int duty)
{
    CCPR1L=duty;
    CCP1CON&=0xCF;
    CCP1CON=(CCP1CON|(0X30&(duty<<4)));
}

void pwm_init()
{
    TRISC=0X00;
    CCP1CON=0X0C;
    PR2=96;
    TMR2=0;
    T2CON=0x7B;
    pwm_dutycycle(0);
    T2CON=0X7F;
}

void delay(unsigned int de) {   while(de--);    }

void main()
{
    pwm_init();
    while(1)
    {
        if(RB0) {   /*delay(100);*/ pwm_dutycycle(0);   }
        if(RB1) {   /*delay(100);*/ pwm_dutycycle(64);  }
        if(RB2) {   /*delay(100);*/ pwm_dutycycle(128); }
        if(RB3) {   /*delay(100);*/ pwm_dutycycle(255); }
    }   
} 

 

Result :

 


Next :

previous :


 

ESP8266 NodeMCU Module – NET

The “ESP8266 NodeMCU Module NET” introduces a comprehensive set of functionalities for network communication on the ESP8266 platform using the NodeMCU firmware. This module empowers developers to create versatile IoT applications by enabling connections over Wi-Fi, TCP/IP, and UDP protocols.

Read more: ESP8266 NodeMCU Module – NET

With the NET module, developers can perform various networking tasks such as creating clients and servers, establishing UDP sockets, managing multicast groups, and interacting with DNS servers. This module provides a wide range of functions for initiating, managing, and terminating network connections, as well as for resolving hostnames and configuring DNS servers.

Whether it’s setting up a web server, connecting to cloud services, or implementing peer-to-peer communication, the ESP8266 NodeMCU Module NET offers the necessary tools and capabilities to facilitate seamless networking operations. It serves as a foundational component for building connected devices and IoT solutions powered by the ESP8266 platform.

NET Module Functions for ESP8266 NodeMCU

ConstantDescription
net.createConnection()Creates a client.
net.createServer()Creates a server.
net.createUDPSocket()Creates a UDP socket.
net.multicastJoin()Join multicast group.
net.multicastLeave()Leave multicast group.
net.server:close()Closes the server.
net.server:listen()Listen on port from IP address.
net.server:getaddr()Returns server local address/port.
net.socket:close()Closes socket.
net.socket:connect()Connect to a remote server.
net.socket:dns()Provides DNS resolution for a hostname.
net.socket:getpeer()Retrieve port and IP of remote peer.
net.socket:getaddr()Retrieve local port and IP of socket.
net.socket:hold()Throttle data reception by placing a request to block the TCP receive function.
net.socket:on()Register callback functions for specific events.
net.socket:send()Sends data to remote peer.
net.socket:ttl()Changes or retrieves Time-To-Live value on socket.
net.socket:unhold()Unblock TCP receiving data by revocation of a preceding hold().
net.udpsocket:close()Closes UDP socket.
net.udpsocket:listen()Listen on port from IP address.
net.udpsocket:on()Register callback functions for specific events.
net.udpsocket:send()Sends data to specific remote peer.
net.udpsocket:dns()Provides DNS resolution for a hostname.
net.udpsocket:getaddr()Retrieve local port and IP of socket.
net.udpsocket:ttl()Changes or retrieves Time-To-Live value on socket.
net.dns.getdnsserver()Gets the IP address of the DNS server used to resolve hostnames.
net.dns.resolve()Resolve a hostname to an IP address.
net.dns.setdnsserver()Sets the IP of the DNS server used to resolve hostnames.

Example :1 TCP Connection in local

The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends a message to the server. It also includes event handlers to handle Wi-Fi connection events.

  • Create a TCP connection and communicate with TCP server
  • Set IP of Server

Code

-- www.ArunEworld.com
print("ArunEworld : TCP Example")

-- Connect to Access Point (DO NOT save config to flash)
wifi.setmode(wifi.STATIONAP)

station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()

function TCP_CONNECTION_func()
    TCP_Conn = net.createConnection(net.TCP, 0)
    TCP_Conn:connect(80, '192.168.1.102') -- Change your server IP

    TCP_Conn:on("connection", function(TCP_Conn, payload)
        print("Connection_func : ")
        print(payload)
    end)

    TCP_Conn:on("receive", function(TCP_Conn, payload)
        print("Received : " .. payload)
    end)

    TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")
end

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

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

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

Code Explanation

Certainly! Here’s an explanation of the provided Lua code:

  1. Print Statement:
   print("ArunEworld : TCP Example")

This line prints out the string "ArunEworld : TCP Example". It serves as an informational message indicating the purpose of the code.

  1. Wi-Fi Configuration:
   wifi.setmode(wifi.STATIONAP)

This line sets the Wi-Fi mode to STATIONAP, allowing the device to connect to an existing Wi-Fi network as a station while also creating an access point.

   station_cfg = {}
   station_cfg.ssid = "ArunEworld"
   station_cfg.pwd = "ArunEworld.com"
   wifi.sta.config(station_cfg)
   wifi.sta.connect()

These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.

  1. TCP Connection Setup:
   function TCP_CONNECTION_func()
       TCP_Conn = net.createConnection(net.TCP, 0)
       TCP_Conn:connect(80, '192.168.1.102') -- Change your server IP
   end

This function sets up a TCP connection to the specified server IP address (192.168.1.102) on port 80.

  1. TCP Event Handlers:
   TCP_Conn:on("connection", function(TCP_Conn, payload)
       print("Connection_func : ")
       print(payload)
   end)

This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which prints out the connection payload.

   TCP_Conn:on("receive", function(TCP_Conn, payload)
       print("Received : " .. payload)
   end)

This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.

  1. Sending Data:
   TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")

This line sends a message to the TCP server after the connection is established.

  1. Wi-Fi Event Monitoring:
   wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
       -- Event handler for when the Wi-Fi station is connected
       -- Print out details about the connection
   end)

   -- Similar event handlers are registered for other Wi-Fi events like disconnection and obtaining an IP address.

Example :1 TCP Connection to httpbin.org  site (Onlin)

print("ww.ArunEworld.com")
print("wifi init")

--wifi.start() -- commented out

wifi.setmode(wifi.STATIONAP) -- connect to Access Point (DO NOT save config to flash)

station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()

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)
    -- 'Connection: close' rather than 'Connection: keep-alive' to have server
    -- initiate a close of the connection after final response (frees memory
    -- earlier here), https://tools.ietf.org/html/rfc7230#section-6.6
    sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
end)

srv:connect(80, 'httpbin.org')

Explanation

The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends an HTTP GET request to retrieve data from httpbin.org. Any received data is printed to the console.

  1. Print Statements:
   print("ww.ArunEworld.com")
   print("wifi init")

These lines print out the strings "ww.ArunEworld.com" and "wifi init". They are for informational purposes and help indicate the progress of the program.

  1. Wi-Fi Configuration:
   wifi.setmode(wifi.STATIONAP)

This line sets the Wi-Fi mode to STATIONAP, which allows the device to connect to an existing Wi-Fi network as a station while also creating an access point.

   station_cfg = {}
   station_cfg.ssid = "ArunEworld"
   station_cfg.pwd = "ArunEworld.com"
   wifi.sta.config(station_cfg)
   wifi.sta.connect()

These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.

  1. TCP Connection Setup:
   srv = net.createConnection(net.TCP, 0)

This line creates a TCP connection object named srv.

   srv:on("receive", function(sck, c)
       print(c)
   end)

This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.

   srv:on("connection", function(sck, c)
       sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
   end)

This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which sends an HTTP GET request to httpbin.org. The request includes the path /get and necessary headers.

  1. Connect to Server:
   srv:connect(80, 'httpbin.org')

This line initiates the connection to the server at httpbin.org on port 80 (the standard HTTP port).


See also


Next

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

ESP8266 NodeMCU Module – Timer

In Lua on the ESP8266 NodeMCU module, you can use the tmr module to work with a timer. Here’s a basic guide on using the ESP8266 NodeMCU Module – Timer. The tmr Module provides 7 (0-6) static timer functions of the timer module. we can’t use more than 7. Also, you can create an object-based timer function with a custom name.

we can use this timer function in the following applications

  • To blink an LED for a certain time duration its like a repeated process.
  • To monitor the WiFi Status of ESP8266 IP address.
Read more… →

ESP8266 NodeMCU Module – MQTT

Functions

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

 

MQTT Example

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

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


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

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

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

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

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

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

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

 


 Read and Write files using MQTT

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

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

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

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

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

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

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

 


 

MQTT to cloud

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

 

 

 


Next :

Previous :