ESP32 OTA (Over The Air) Programming
Hello readers, hope you all are doing great. In this tutorial, we are going to discuss a mechanism that allows users to update the ESP32 with a new program wirelessly or over the air (without using a USB cable to upload a new program).
| Where To Buy? |
|---|
| No. | Components | Distributor | Link To Buy |
| 1 | ESP32 | Amazon | Buy Now |
Over-The-Air (OTA) programming
Fig. 1 ESP32 OTA
- OTA programming is the mean by which a product manufacturer or product service provider can update the features or functionality of the device wirelessly or over the air, after the device has been deployed in the field where connecting a cable or uploading the code serially is difficult.
- One key advantage of OTA is that a single central node can send an update to multiple ESPs on the same network.
- The device must have a provisioning client capable of receiving, processing, and setting parameters in order to receive, process, and set parameters in a mobile device over the air.
Applications of OTA programming
Mobile Phones:
- In order to improve the compatibility with hardware and enhance the stability of software and applications, software updates are required.
- OTA updates are intended to improve the underlying operating system, time zone rules, read-only apps installed on the system partition these updates have no effect on user-installed applications.
IoT (internet of things) application:
- The ability to wirelessly download an application, configuration, or firmware to internet-enabled devices, also known as IoT, is referred to as over-the-air (OTA). It works in the same way that our computers, laptops, tablets, and phones do.
- Application, where sensor nodes are frequently placed in remote or difficult-to-reach locations OTA programming can be used.
Fig. 2 OTA programming for IoT
How does OTA programming work?
There are two methods of OTA implementation.
- Basic OTA: In the basic OTA method the program is updated into ESP32 over the air using Arduino IDE.
- OTA web updater: In web updater OTA the program is updated over the air using a web browser.
Implementing OTA Update feature using ESP32
In this tutorial, we will discuss only the basic OTA method using Arduino IDE and ESP32 module.
If you want to know more about the basics of ESP32 and how to get started with Arduino IDE, then follow the tutorial Introduction to ESP32 Programming Series.
- For Basic OTA programming with ESP32, it is required to install the python 2.7.x version in your system.
- Follow the link to download python: https://www.python.org/downloads/
- Install the python into your system.
- Upload the basic OTA code into ESP32 using the serial port.
- Upload the new ESP32 test code over the air using the network port into esp32 module.
To implement the Basic OTA method, an example is available is Arduino IDE.
- You can find the code through File> Examples> ArduinoOTA> BasicOTA.
- An image has been attached below for reference:
Fig. 3
Arduino IDE Code
- It is required to first upload the basic OTA code serially (using serial com port).
- Because in default mode the ESP32 is not ready for OTA updates (as there is no inbuilt OTA firmware available inside the ESP32 board).
- Only after that you can access the OTA feature
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
const char* ssid = "SSID";
const char* password = "Password";
void setup() {
Serial.begin(115200);
Serial.println("Booting");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
ArduinoOTA.handle();
}
Code Description
- The first step is to add all the necessary header files. Here we are using four header files.
- WiFi.h: This header file allows the ESP32 board to connect to the internet. It can serve either as a server or a client.
- ESPmDNS.h: This library is used to implement multicast DNS query support for the ESP32 chip. A multicast UDP service is used to provide local network service.
- WiFiUdp.h: This is a library for Arduino wifi shield. It is used to send data to a UDP host over a wireless network.
- ArduinoOTA.h: this library allows users to update the code in the ESP32 board using wifi instead of using the serial port.
- Next, you need to add your wifi credentials. Enter the SSID and password.
Arduino Setup() Function
- Inside the setup () function, the first task is to begin the serial monitor at a 115200 baud rate so that, you can print the results and other required details on the serial monitor for verification purposes.
- Set ESP32 Wi-Fi module in station mode(esp32 will act as a client device) using WiFi.mode() function.
- Enable ESP32’s Wi-Fi module using WiFi.begin() function which is using SSID and password as arguments.
- Wait until the ESP32 is not connected with the wifi network.
- ESP.restart() function will reset the ESP32. ESP.restart() function tells SDK to reboot.
- If an error occurred in OTA programming, print the error on the serial monitor
- ArduinoOTA.begin() function is used to initialize the OTA updater.
- Wi-Fi.lockIP() is used to fetch the IP address.
- Print the IP address on the serial monitor.
Arduino Loop() Function
- Inside the loop() function, ArduinoOTA.handle() function is used for updating the ESP32 code over the air using the network port instead of the serial port.
- Compile the code and upload serially using serial com port.
- Open the serial monitor, set the baud rate to 115200.
- You can see the IP address on the serial monitor once the ESP32 is connected to the Wi-Fi network.
Fig. 11 Serial monitor
Uploading new program into ESP32 module Over the Air
Code
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
const char* ssid = "public";
const char* password = "ESP32@123";
//variabls for blinking an LED with Millis
const int led = 2; // ESP32 Pin to which onboard LED is connected
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 1000; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
void setup() {
pinMode(led, OUTPUT);
Serial.begin(115200);
Serial.println("Booting");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
ArduinoOTA.handle();
//loop to blink without delay
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
}
- In the test code, which we are going to upload using a wireless network port over the air, a LED blinking function is added just to test whether the OTA functionality is working fine or not.
Note: It is required to upload the OTA programming handler code every time you upload a new code into ESP32 over the air. So that, OTA programming remains enabled for future use.
Code Description
- Add the required header files.
- Enter Wi-FI credentials over which you are going to upload the code wirelessly.
- Define the GPIO pin to which LED is connected.
- GPIO 2 is connected to the inbuilt LED.
- To add delay, we are using timers instead of delay() function.
- The variable interval is defining the time delay.
- Set LED’s state to low.
Arduino Setup() Function
- Although in the example code serial monitor is initialized but it is not required anymore as we are using the network port for communication.
- Initialize ESP32 Wi-Fi in station mode using WiFi.mode() function.
- Wait until esp32 is connected to the Wi-Fi network.
- ArduinoOTA.begin() function is used to initialize the OTA updater.
- Wi-Fi.lockIP() is used to fetch the IP address.
- Print the IP address on the serial monitor.
Arduino Loop() Function
- Blink the LED after every 1000ms or 1sec delay as defined in variable ‘interval’.
- Compile the above code.
- Go to the Tools menu, then click on port and select the network port as shown in the image below.
This concludes the tutorial. I hope you found this helpful. In the next tutorial, we will discuss the OTA web updater in ESP32.
Accident Detection System using Arduino
Hello everyone, Welcome to our new project. Our new project plays a very important role in our daily life as it is directly connected to our lives. In this project, we are going to design an Accident Detection module. Accidents are the most common thing we hear about in the news, and in social media. Everyone here or there has seen accidents or has been with one. So when any such incidents happen, we inform respective stations or hospitals in that emergency situation. But what about the accidents that happen at night, or in places where there is very less crowd or you are alone. So, to address this issue and provide a potential solution for that, we are going to learn how to detect an accident automatically and inform nearby aid/help stations.
We can use this useful project for an engineering project’s showcase for electronics, electrical engineering students, and can be used in real-life situations where it can help people in disastrous situations.
According to WHO, research says that in the current scenario, 1.3 million people are the victims of road traffic crashes, and 40% of these accidents of all fatal accidents occur at night. In most cases, the accidents are not reported immediately, or the injured doesn’t receive any help during that time. The time between the accident and the arrival of medical help for the injured can sometimes make the difference between his life or death. In the future, we can interface with the vehicle airbag system. This will optimize the proposed technology to the maximum extent and result in the finest accident detection system possible. In this Modern era, everything is being automated and with this project, we are going to automate this process with some electronic components and Arduino. So Let’s dive in. Here's the video demonstration of this project:
| Where To Buy? |
|---|
| No. | Components | Distributor | Link To Buy |
| 1 | NEO-6M | Amazon | Buy Now |
| 2 | SIM900 | Amazon | Buy Now |
| 3 | Arduino Uno | Amazon | Buy Now |
Software to Install:
Instead of using real components, we will design this project using Proteus Simulation. Working with simulation before attempting to make it with real components is also a smart practice. We can figure out the issue that may arise while working on real components and avoid any kind of damage to our components by simulating it.
Proteus is a very fascinating tool that allows us to simulate and create electronic circuits. Despite the fact that Proteus software contains a large library of electronics components, it still lacks pre-installed modules such as Arduino boards, GPS or GSM modules, and so on.
Let’s install the required libraries which, we are going to use in this project:
You can download this whole project for example Proteus Simulation and Arduino Code, by tapping the below button
Accident Detection System using Arduino
Project Overview:
These are required components for Accident Detection, which are as follows:
- Arduino Uno: Arduino Uno is a development board from the Arduino family, which is the main component of this project. The Microcontroller i.e., Arduino is responsible for the decisions that are going to be processed in the project.
- Accelerometer: An accelerometer is a device that measures acceleration, which is the change in speed (velocity) per unit time. By measuring acceleration we can get information like object inclination and vibration which helps in detecting unusual activities/ accidents.
- GSM: A GSM/GPRS Module is a device that is actually responsible for the wireless communication with the GSM Network, in this case, it is responsible for sending the appropriate information to rescue stations.
Components Needed:
- Arduino Uno
- GPRS Module
- Accelerometer
- GSM Module
- Bread Board
- Jumper Wires
Component details:
Arduino Uno:
- The Arduino UNO is one of the Arduino family's programmable, open-source microcontroller boards.
- It includes an Atmel Microchip ATMega328P microcontroller with an 8-bit RISC processing core and 32 KB flash memory from Atmel.
- It has 14 digital I/O pins, including 6 PWM pins and 6 analog I/O pins with a resolution of 10 bits (0-1024).
- It comes with one hardware UART, one I2C, and one SPI peripheral.
- We can use the Arduino UNO with a voltage range of 7-12 volts, but not more than 9 volts is recommended because it may damage the Arduino board
- To power the Arduino UNO we can use a USB-B cable (the same cable that we use to upload the sketch to Arduino UNO), a DC power jack, or the Vin pin on the board.
GPS Module:
- The Global Positioning System (GPS) is a space-based global navigation satellite system that gives accurate location and timing in all weather and at all times around the world.
- It sendLongitude, latitude, height, and time are the four variables that a GPS receiver determines.
- Data determined by the module will be sent to the microcontroller (Arduino Uno) through the UART protocol.
- With a USB interface, the GPS module is simple to operate. It operates on a 3.2 to 5V supply range, allowing it to interface with both 3.3V and 5V microcontrollers.
- It has a default baud rate of 9600 and can be modified as per our requirement.
- We have used this to get the current location of the user.
Accelerometer:
- Accelerometer sensors are integrated circuits (ICs) that are used to measure acceleration, inclination, and various parameters regarding the x,y,z axes. It is the main component to detect the accident.
- Here we used the MEMS (Microelectromechanical Systems) accelerometer. These types of accelerometers are used where we have to measure the vibration or shock without any fixed reference.
- It monitors changes in the capacitance and converts that value to analog output voltage.
- Gyro Range of the Accelerometer sensor is ± 250, 500, 1000, 2000 °/s (may vary depending upon the sensor).
- Accelerometer Range of the sensor module is ± 2 ± 4 ± 8 ± 16 g (may vary depending upon the sensor).
GSM module:
- This module is used to send the notification to the rescue station or the emergency numbers.
- It communicates with the Arduino UNO using the UART protocol.
- It works in a voltage range of 3.5 - 5 volts.
- There are different types of GSM modules available but in this project, we have used the SIM900D module.
- We operate them using the AT commands. As there are hundreds of AT commands but we will use some basic only just to send the message.
Proteus Simulation of Accident Detection Circuit:
Now, it is time to start designing the main circuit of Accident detection in Proteus Simulation software.
- Most importantly, ensure that Proteus is installed on your PC/Laptop and download all the required libraries for Proteus ahead of starting the designing steps.
- For this project, we are going to use libraries for Arduino Uno, GPRS Module, GSM module.
- To add the libraries in the Proteus suite we have to go to the C drive then LabCenter Electronics >> Proteus 8 professional >> Data >> Library and paste the downloaded library files here.
- The download links of all the libraries have been provided to you in the above sections, please go check them out.
- Let’s start the making of a new project, open the new project in Proteus.
- After that enter the name of your new project.
- Now our working area will be open here we will import all the required components which we are going to use.
- The following components need to be selected from the Proteus component library. We’ll connect the components and make the circuit complete.
- Now we have imported all the required components for this project, after this, we will start connecting them.
Circuit Diagram and Working:
- There are two modules GPRS and GSM modules, both communicate using the UART protocol but in the Arduino UNO there is only one hardware UART’s provision. Now, you may have doubts about how we are going to connect them. No worries, we will handle that on the coding side by declaring the different pins as UART pins.
- We can use different pins for UART using the SoftSerial library of Arduino, which will be discussed in the code.
- We will use the digital pins for UART connections, digital pins 2 and 3 for communication of the GSM module, which means connecting the Rx and Tx of the GSM module with the D2 and D3 pins of Arduino UNO respectively.
- Connect the Rx and Tx of the GPRS module with the D10 and D11 pins of Arduino UNO respectively.
- As modules are connected, now we will connect the accelerometer. As it will not be possible to simulate the accelerometer in Proteus so we have used the potentiometers to change the value of the X-axis, Y-axis and Z-axis.
- You may have doubts about how we can replace the accelerometer with potentiometers. As we will use the MEMS accelerometer, which sends the analog voltages for each axis, so we can simulate that using the potentiometer because we will receive the same type of data.
- We need three potentiometers, one for each axis. Potentiometers of the X-axis, Y-axis and Z-axis will be connected to A1, A2 and A3 pins of Arduino respectively.
- We will connect a serial terminal for debugging purposes.
Arduino code for Accident Detection System
Before going to start the coding, it would be easy if you understood the circuit diagram connections.
- When we start writing the code(called a sketch in Arduino IDE), we will first include all of the necessary libraries for this project.
- So, if the essential libraries aren't already installed in the Arduino IDE, our first step would be to get them.
- Here we use mainly two libraries, one for serial communication and parsing data from the GPS module.
- By heading to 'Sketch > Include Library > Manage Library' in the Arduino IDE, we can install libraries related to Arduino. We can now search for our essential libraries in the library manager. We can also use zip files to install the libraries.
- As we've installed all the specified libraries. Let’s include them in our sketch.
- Now, we are declaring D2 and D3 pins for serial communication with GPRS modules and declaring GPS objects as well, which will pretty much do all the grunt work with the NMEA data.
- After that, we will declare variables to store the GPS module data.
- Now, we are declaring pins and variables for the accelerometer which we will use in our project. Here, we are using Analog Pins because we are reading the analog voltages from the potentiometer.
- We need to declare two threshold values for change in acceleration when an accident is detected.
- The min and max values can vary. So, it is highly recommended to measure the values by accelerometer for devices using.
Void Setup():
- It is one of the most important functions which will execute only once in the whole process.
- As we are using a GPS module in our project, We should first start serial communication between the components and Monitor them through “Serial Monitor” in the Arduino IDE.
- “Serial.begin” is used to set up the serial configuration for the device which is connected to the Serial Port of the Arduino. Here, we will set the baud rate for that device i.e 9600 in our case.
- “serial_connection.begin(9600)” is used to set up the UART configuration for the GPS module. As the GPS module communicates to the Arduino at the baud rate of 9600.
- We are using an Accelerometer in the circuit and it was clearly explained in detail that it will sense the x,y,z coordinates of the device and send them to Arduino.
- Here, we have initialized a for loop to collect the sample data for x, y, and z coordinates of the device in the ideal state.
- Afterward, the sample coordinates have been successfully measured by the Accelerometer sensor, but we need an average value for smoothing the sample coordinate values. So here, we will calculate the average of each coordinate and print them in the serial monitor.
- After the setup, we will write our main application code in the Void loop function.
Void loop():
- It is the second most important function of Arduino code. It will come to action after the execution of “void setup()”
- We'll write the code required to run in a continuous loop in this part. So this is where we'll write our primary application code.
- As a result, when the code gets to the void loop portion, We firstly take the NMEA data from the GPS module and print it in the serial monitor.
- Wait a minute, NMEA??, I can understand all the questions in your mind. Let us give you a simple explanation regarding NMEA and its applications.
- The word NMEA stands for the National Marine Electronics Association, which is a mode of communication that existed before inventing GPS. NMEA-format GPS data can be accessed with a wide variety of GPS receivers, instead of creating a new custom interface every time. Thus, it makes our lives easier using the GPS Module.
- When we are printing the NMEA data into the serial monitor, it will be printed in a specific structure. This NMEA data was output from a GPS receiver:
“$GPGGA,191605.00,4521.7785210,N,07331.7656561,W,2,19,1.00,674.354,M,19.900,M,0.90,0000*60”
- All NMEA signals start with the ‘ $ ’ character and for every data field such as coordinates, and various parameters are separated by a comma. The data further includes Timestamp, Latitude, Longitude, Quality indicator, Number of satellites involved, Altitude, etc., which is not necessary to remember. Make sure to get the data from the GPS module. If we have succeeded in this step and get the data on the serial monitor, then we are good to go for further processing.
- The “if” statement is to process the NMEA data and separate the data into the required format if there is any location updated to the GPS receiver.
- As we have already received NMEA data in the previous step, the data will be separated into Latitude, Longitude and Altitude.
- In the Loop function, the values of GPS and accelerometer will be continuously tracked.
- Here, the analog values of x,y,z coordinates are being measured and printed in the serial monitor.
- These are not the values we measured in the void setup, those were the values to take the readings in the ideal state of the device.
- But in the loop, the values are the present x,y and z coordinates measured by the accelerometer.
- This is the condition for accident detection, we have already discussed before that in the void loop the x,y,z coordinate values are continuously extracted and the “if” statement here compares the recent values with fixed min and max values of the coordinates.
- If the recent values are indistinct or do not match with threshold values i.e., max value and min value, then it indicates that an accident has been detected.
- When the accident detection condition is satisfied, the GPRS module will be activated and will call to rescue stations for aid/help and their home.
- Here, we have programmed to give a call 5 times to the appropriate numbers in the “for” loop.
- And the process also includes a messaging feature along with calling to rescue stations.
- When the same accident condition is satisfied, the messaging feature will be activated and we are going to send the alerting message including the Location, Latitude, Longitude, and Google map location link by appending latitude and longitude values the to respective numbers.
Results / Working:
We have successfully completed our Accident detection project and it’s ready to test!
- Before going to start the simulation, we need to import the hex files of Arduino code in the Proteus, to do so click on the Arduino and browse to the hex file of the code and select.
- Now we need to add the program files for the GPS and GPRS modules.
- Here we should note that we only need to upload the program files for the modules while we are working in simulation. In the real modules, they come up with pre-installed codes.
Now we have done all the prerequisites of simulation.
- Let’s power the circuit and start the simulation, firstly the void setup function will run and it will initialize all the required pins and variables and will read the ideal state values of the potentiometer.
- Now to simulate the accident case, we will change the values from the potentiometer, so when the potentiometer’s value changes and the falls in the Min and Max value range the if condition will be stratified.
- After this GSM module will call the stored number 5 times and send the GPS location with Google maps link in that.
- We have used some serial monitors for debug purposes, you can see the current state of the project using them.
I hope you have a good understanding of how our Accident Detection project works and that you have liked it. Although I believe we have covered almost everything, please let us know if you have any questions or suggestions in the comments section.
Thank you very much for reading this project. All the best for your projects!
Using DAC with STM32
A Digital to Analog Converter(DAC) performs the task of converting digital words of n bits into voltages whose amplitude will be proportional to the value of the code expressed by the words themselves. Since the input binary words represent a succession of finite codes, the voltage coming out of a DAC cannot be continuous over time but is made up of as many levels as the converted codes are. This means that the devices to which the analog signal produced by a DAC is sent must filter it with a low-pass characteristic (integrating action). The operating criterion of a DAC is simple: in fact, it is sufficient to have a succession of as many voltages as there are convertible codes, obtained for example by means of a weighted resistance network (i.e. the value proportional to the code implied in the binary word). The conversion consists in sending the voltage corresponding to the code applied to the input to the output of the converter.
One of the simplest and most classic DACs is the R-2R ladder, but today there are more complex objects with optimization in the signal reconstruction. Below is shown a 3bit R-2R ladder DAC.
In practice, the circuit is an inverting adder where the bits (B0, B1, ... Bn) command a switch. The output voltage in the case of the 3-bit DAC is:
Vout= -1/2*B1*Vref - (1/4)*B1*Vref- (1/8)*B1*Vref
If the 3bit string is D and Vref is equal to the logical voltage of 3.3V
Vout= (3.3*D)/2^3
The typical output characteristic is shown in the following figure.
Compared to the weighted resistor DAC, the R-2R scale DAC has the advantage of using only two resistive values. Therefore, it is more easily achievable with integrated circuit technology.
| Where To Buy? |
|---|
| No. | Components | Distributor | Link To Buy |
| 1 | STM32 Nucleo | Amazon | Buy Now |
DAC on STM32 platform
Many of the STM32 microcontrollers have on board at least one DAC (generally 12 bit) with the possibility of buffering the output signal (with internal operational amplifier OP-AMP). The use of the DAC finds various applications, for example, it can be used to reconstruct a sampled signal or to generate any waveform (sine wave, square wave, sawtooth, etc.), to generate a reference voltage (for example for a digital comparator).
The DAC peripheral can be controlled in two ways:
- Manually
- Using a Data Memory Access (DMA) with a trigger source (can be an internal timer or external source).
DAC in manual mode
In this modality we can drive DAC to on/off a LED, to generate a reference voltage, etc. We will use a NUCLEO STM32L053R8 board to show as configure DAC with STCube. This NUCLEO has available a DAC with only one channel (in general every DAC has one or more channels) with resolution up to 12bit with a maximum bus speed of 32 MHz and a maximum sampling rate of 4 Msps. First, let's see how to initialize the peripherals using STCube Tool:
Configuration of DAC in manual mode
DAC Initialization
- Select DAC with following path: “Pinout & Configuration”-> Analog -> DAC. Select the Output 1 (OUT1 Configuration):
- In Configuration->Parameter Setting select Output Buffer= Enable and Trigger = None
- The GPIO PA4 is associated to DAC Output1. PA4 has been configurated in Analog Mode, No Pull-Up and No Pull-Down.
System Reset and Clock Control (RCC) Initialization
- Select RCC with following path: “Pinout & Configuration”-> System Core -> RCC. “High Speed Clock” (HSE) and “Low Speed Clock” (LSE) select for both “Crystal/Ceramic Resonator”.
Now we are ready to generate the initialization code.
Diving into the initialization code
At this point, let's look at the generated code:
- In “Private variables” we find DAC_HandleTypeDef hdac, it is an instance to C struct that need to manipulate the DAC peripheral:
typedef struct
{
DAC_TypeDef *Instance; /*!< Register base address */
__IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */
HAL_LockTypeDefLock; /*!< DAC locking object */
DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */
#if defined (DAC_CHANNEL2_SUPPORT)
DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */
#endif
__IO uint32_t ErrorCode; /*!< DAC Error code
}DAC_HandleTypeDef;
- In “Private function prototypes” the function prototype used to initialize and configure the peripherals:
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DAC_Init(void);
/* USER CODE BEGIN PFP */
- Where we find the initialization select in STCube Tool.
Driving DAC to generate a reference voltage
Now, before writing our application, let's see what functions the HAL library makes available to handle the DAC.
- HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel): need to enable DAC and start conversion of channel.
- “hdac” is a pointer to DAC structure
- “Channel” is the selected DAC channel
- HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel): need to disable DAC and start the conversion of the channel.
- “hdac” is a pointer to DAC structure
- “Channel” is the selected DAC channel
- HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data): is used to set in DAC channel register the value passed.
- “hdac” is pointer to DAC structure
- “Channel” is the selected DAC channel
- “Alignment” needs to select the data alignment; we can select three configurations, because the DAC wants the data in three integer formats:
- “DAC_ALIGN_8B_R” to configure 8bit right data alignment;
- “DAC_ALIGN_12B_L” to configure 12bit left data alignment;
- “DAC_ALIGN_12B_R” to configure 12bit left data alignment.
- “Data” is the data loaded in the DAC register.
The voltage output will be:
Vout,DAC = (Vref*data)/2^nb
where nb is a resolution (in our case 12bit), Vref is voltage reference (in our case 2 Volt) and the passed data.
So, to set DAC output to 1 Volt data must be 2047 (in Hexadecimal 0x7FF) so we call the function this way:
HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, 0x7FF);
To set the output voltage to 3.3 Volt we call function in this way:
HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, 0xFFF);
To verify that change the value in our main we write the following code and then we check the output connecting it to the oscilloscope probe.
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_DAC_Init();
while (1)
{
/* USER CODE END WHILE */
HAL_DAC_Start(&hdac, DAC_CHANNEL_1);
HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, 0x7FF);
HAL_Delay(1000);
HAL_DAC_Stop(&hdac, DAC_CHANNEL_1);
HAL_Delay(1000);
HAL_DAC_Start(&hdac, DAC_CHANNEL_1);
HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, 0x7FF);
HAL_Delay(1000);
HAL_DAC_Stop(&hdac, DAC_CHANNEL_1);
HAL_Delay(1000); /* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
We expect the output voltage to change every second by repeating the following sequence: 1V - 0V - 2V – floating (as shown in the figure below)
The signal displayed on the oscilloscope checks the sequence we expected. In the first second the output voltage from the DAC is 1V then in the next second 0V then 2V and in the last second of the sequence, the output is floating.
Using DAC in Data Memory Access (DMA) mode with a Timer
In this modality we can drive DAC to on/off a LED, to generate a reference voltage, etc. We will use a NUCLEO STM32L053R8 board to show as configure DAC with STCube. This NUCLEO has available a DAC with only one channel (in general every DAC has one or more channels) with resolution up to 12bit with a maximum bus speed of 32 MHz and a maximum sampling rate of 4 Msps. First, let's see how to initialize the peripherals using STCube Tool:
Configuration DAC in DMA mode
- Select DAC with following path: “Pinout & Configuration”-> Analog -> DAC. Select the Output 1 (OUT1 Configuration):
- In “Parameter Settings” the Output Buffer is enabled, Timer 6 is selected as Trigger Out Event and Wave generation mode is disabled.
- Activate DMA to handle DAC using channel 2. The direction is Memory to Peripheral. The buffer mode is “circular”, and the data length is a word.
- Set interrupt related channel 2 of DMA
TIM 6 Configuration
- We use TIM6 because is one of two timers used by uP to trigger the DAC output. At the moment we do not change the initial configuration, later we will see what we need.
- TIM6 -> NVIC Setting: flag “TIM6 interrupt and DAC1/DAC2 underrun error interrupts” to activate interrupts.
Now we are ready to generate the initialization code. Before we need to learn as the waveform can be generated using DAC.
Sinewave generation
Let's see mathematically how to reconstruct a sinewave starting from a given number of samples. The greater the number of samples, the more "faithful" the reconstructed signal will be. So, the sampling step is 2pi / ns where ns is the number of samples in this way, we have to save our samples in a vector of length ns. The values ??of every single element of the vector will be given by the following equation:
S[i] = (sin(i*(2p/ns))+1)
We know that the sinusoidal signal varies between 1 and -1 so it is necessary to shift it upwards to have a positive sinewave (therefore not with a null average value) therefore it must be moved to the middle of the reference voltage. To do this, it is necessary to retouch the previous equation with the following:
S[i] = (sin(i*(2p/ns))+1)*((0xFFF+1)/2)
Where 0xFFF is the maximum digital value of DAC (12bit) when the data format is 12 bits right aligned.
To set the frequency of the signal to be generated, it is necessary to handle the frequency of the timer trigger output (freq.TimerTRGO, in our case we use the TIM6) and the number of samples.
Fsinewave = freq.TimerTRGO/ns
In our case, we define Max_Sample = 1000 ( is uint32_t variable) and let's redefine some values of the timer 6 initialization.
static void MX_TIM6_Init(void)
{
/* USER CODE BEGIN TIM6_Init 0 */
/* USER CODE END TIM6_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM6_Init 1 */
/* USER CODE END TIM6_Init 1 */
htim6.Instance = TIM6;
htim6.Init.Prescaler = 1;
htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
htim6.Init.Period = 100;
htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim6) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim6, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM6_Init 2 */
/* USER CODE END TIM6_Init 2 */
}
We have changed the following parameters:
htim6.Init.Prescaler = 1;
htim6.Init.Period = 100;
So with 1000 samples, the output sinewave will be a frequency of 10 Hz. We can change the number of samples (being careful not to use too few samples) or the “Init.Prescaler” and “Init.Period” values of timer 6.
Driving DAC in DMA mode with Timer
Using the DAC in DMA mode the HAL library makes available to handle the DAC another function to set the DAC output.
HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment)
Compared to the manual function we find two more parameters:
- uint32_t* pData is the peripheral buffer address;
- uint32_t Length is the length of data to be transferred from the memory to DAC peripheral.
As you can see from the following code we first need to include the "math.h" library, define the value of pigreco (pi 3.14155926), and write a function to save the sampled sinewave values in a array (we wrote a function declared as get_sineval () ).
#include "math.h"
#define pi 3.14155926
DAC_HandleTypeDef hdac;
DMA_HandleTypeDef hdma_dac_ch1;
TIM_HandleTypeDef htim6;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_DAC_Init(void);
static void MX_TIM6_Init(void);
uint32_t MAX_SAMPLES =1000;
uint32_t sine_val[1000];
void get_sineval()
{
for (int i =0; i< MAX_SAMPLES; i++)
{
sine_val[i] = ((sin(i*2*pi/MAX_SAMPLES)+1))*4096/2;
}
}
/* USER CODE END 0 */
- Once this is done, we can start the DAC by saving the sampled values of the sinewave in the buffer (* pdata) as shown below:
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_DAC_Init();
MX_TIM6_Init();
/* USER CODE BEGIN 2 */
get_sineval();
HAL_TIM_Base_Start(&htim6);
HAL_DAC_Start_DMA(&hdac, DAC_CHANNEL_1, sine_val, MAX_SAMPLES, DAC_ALIGN_12B_R);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
Now we just have to show the acquisition that the oscilloscope:
If we change the number of MAX_SAMPLE to 100 the sinewave will be a frequency of 100 Hz, but as can be seen from the acquisition, the number of samples, in this case, is a bit low.
We can optimize the waveform by acting on timer 6 in order to increase the number of samples. For example by modifying htim6.Init.Period = 400
So, that was all for today. I hope you have enjoyed today's lecture. Let me know if you have any questions. Thanks for reading. Take care !!! :)
How the Use of IoT Has Made Life a Lot Easier for Medical Professionals
IoT – the Internet of Things – has revolutionized the way we use and perceive technology over the last couple of decades. From introducing the world to smart homes and cars to envisioning a more efficient office and work environment, IoT has done it all.
We have integrated IoT in our industrial, tech, and agricultural sectors, as well as our personal lives. However, one of the most fascinating ways IoT has influenced our current society is through its contribution to the health and medical sector.
The healthcare sector managed to get the most out of the Internet of Things technology. Utilizing modern sensors to keep a close eye on their patients’ conditions, these IoT systems are making life easier for medical professionals. And while IoT systems cannot run entire healthcare facilities by themselves, they make life easier for doctors in other ways and provide benefits to patients too. Here is how.
Urgent Care and Walk-In Clinic Services
IoT sensors, especially those that can measure temperature, pulse and heartbeat, breathing rate, etc. are being deployed in medical facilities all over the world right now. Due to COVID-19, urgent care and walk-in clinic services have gained a lot of popularity.
However, for their safety, healthcare professions maintain a considerable distance from patients at times. So whenever possible, the tests are carried out from a distance, and IoT can help in this regard.
Take the MLX90614 IR temperature sensor used in temperature guns. It can take the reading, then send the doctor the results via an IoT network within the healthcare facility. The doctor can then carry out more tests in an unmanned manner (wherever possible), and then write the prescription. All they have to do is note down the readings, explain the situation, and hit their custom signature stamp on the paper.
Thus, during such times of crisis, a doctor only needs to carry a self-inking signature stamp to work. Hitting their custom signature stamps on the prescriptions, mostly containing their qualifications and name, are all that they have to do manually right now. This is, by no means, is demeaning to their work or responsibility. It just goes to show how IoT is making their life a lot easier, and safer.
Remote Health Monitoring And Long Distance Check-Up
In a lot of cases, doctors need not be present at the clinic or hospital to write their patients a prescription or update them about their medical condition. They can do so within the comfort of their homes as well.
Take the AMD-DS-AS0028-1 fingertip sensor as an example here. Pulse oximeters, which are being used all over the world right now to check for dropping oxygen levels in the human body, use these sensors to measure SpO2 levels.
Normally, the measurements are then displayed on a screen on the device or a separate monitor. However, with a proper network connection, this system can be IoT-enabled. That will allow the doctor to receive the pulse oximeter reading at his home, from where they can then advise the patient on what to do next.
A similar case can be carried out for long-distance check-ups. Once the medical devices, like the oximeter or blood pressure machine, get the readings, they can then deliver those numbers to the doctor, who might be living a few hundred miles away. Based on the findings of these devices, the doctor will prescribe a course of action for the patient.
For this system to go fully remote, a high-definition camera is also preferred, because the way a patient looks is also crucial in treatment these days. Thus, a quick look at them can reveal a lot of vital information about their health.
Machine Learning and AI-Driven Treatment Suggestions
Walk-in and remote health services are just two of the areas that IoT contributes to in the healthcare sector. One of the more vital roles it plays is that it can navigate medical professions in the right direction during a difficult treatment procedure. Of course, IoT does not do this by itself. It utilizes machine learning and artificial intelligence for better results.
Take the latest COVID trends as examples. New strains are popping up every once in a while, and it is getting difficult to keep track of them all. So virologists are gathering samples via unmanned drones or bots and then testing them at labs. The results are then run through various ML algorithms to determine the strain’s origin.
A similar approach is being used to predict the next coronavirus. The AI used here can classify the animals based on their chances of forming a new coronavirus.
And as we continue to explore more aspects of IoT, we will keep coming up with newer innovations that can benefit the healthcare sector, as well as other fields.
ESP32 Low Power Modes
Hello readers, hope you all are doing great. In this tutorial, we will discuss low power modes in ESP32, their purpose and their implementation to increase the battery life by reducing power consumption.
| Where To Buy? |
|---|
| No. | Components | Distributor | Link To Buy |
| 1 | ESP32 | Amazon | Buy Now |
Purpose of Low Power Modes
Fig.1
Along with multiple wireless and processing features, ESP32 also provides us with a power-saving feature by offering sleep modes. When you are powering the ESP32 module from the live supply using an adaptor or a USB cable, there is nothing to worry about power consumption. But when you are using a battery, as a power source to ESP32, you need to manage the power consumption for longer battery life.
Low Power Modes in ESP32
When ESP32 is in sleep mode, a small amount of power is required to maintain the state of ESP32 in RAM (random access memory) and retain necessary data. Meanwhile, the power supply won’t be consumed by any unnecessary peripheral or inbuilt modules like Wi-Fi and Bluetooth.
ESP32 offers 5 power modes. Each mode is configurable and offers different power-saving capabilities:
- Active Mode
- Modem Sleep Mode
- Light Sleep Mode
- Deep Sleep Mode
- Hibernation Mode
Fig. 2
Active Mode:
- In active mode, all the modules and features of ESP32, like processing cores, Wi-Fi, Bluetooth, radio etc. remain active all the time.
- Most of the power consumption occurs in this power mode which can vary between 160 -240mA and sometimes the maximum consumption could reach up to 790mA (when both Wi-Fi and Bluetooth are enabled or active at the same time).
Modem Sleep Mode:
- In this mode, radio, Wi-Fi, Bluetooth will be disabled and everything else will remain active. Power consumption in this mode varies from 3 to 20mA.
- Sleep modes can switch between modem and active modes as per the predefined intervals, by following the associated sleep pattern.
Light Sleep Mode:
- During this mode, the central processing unit is paused by turning/powering off its clock.
- ULP- coprocessor and RTC (real-time clock) remain active during light sleep mode and power consumption is 0.8mA.
Deep Sleep mode:
- In this mode, the Ultra Low Power (ULP) coprocessor remains active while the ESP32 core and other digital peripherals remain inactive.
- The ULP coprocessor wakes up the core processor when required.
- The amount of power consumed in this mode is 10uA.
Fig 3
Hibernation Mode:
-
- In this mode, the ULP coprocessor and internal oscillator both are disabled.
- Only a real-time clock (RTC) remains active to wake up the processor and other required modules from hibernation mode and the power consumption in this mode is extremely low that is approximately 2.5uA.
For a better understanding of low power modes in ESP32, we are going to implement deep sleep mode in esp32 and will also discuss how to wake up the device from deep sleep mode.
Deep Sleep mode and Wakeup Using Capacitive Touch-sensitive pins
To implement deep sleep modes we are going to use another ESP32 feature that is Capacitive Touch Sensing pins. These pins can sense the presence of a body that holds an electric charge.
So we are going to use these touch-sensitive pins for waking up ESP32 from deep sleep mode using the Arduino IDE compiler.
In Arduino IDE examples are given for deep sleep mode with various wake-up methods.
- Follow the image attached below to open the example code:
Fig. 4 Example code.
#define Threshold 40 /* Greater the value, more the sensitivity */
RTC_DATA_ATTR int bootCount = 0;
touch_pad_t touchPin;
/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}
/*
Method to print the touchpad by which ESP32
has been awaken from sleep
*/
void print_wakeup_touchpad(){
touchPin = esp_sleep_get_touchpad_wakeup_status();
switch(touchPin)
{
case 0 : Serial.println("Touch detected on GPIO 4"); break;
case 1 : Serial.println("Touch detected on GPIO 0"); break;
case 2 : Serial.println("Touch detected on GPIO 2"); break;
case 3 : Serial.println("Touch detected on GPIO 15"); break;
case 4 : Serial.println("Touch detected on GPIO 13"); break;
case 5 : Serial.println("Touch detected on GPIO 12"); break;
case 6 : Serial.println("Touch detected on GPIO 14"); break;
case 7 : Serial.println("Touch detected on GPIO 27"); break;
case 8 : Serial.println("Touch detected on GPIO 33"); break;
case 9 : Serial.println("Touch detected on GPIO 32"); break;
default : Serial.println("Wakeup not by touchpad"); break;
}
}
void callback(){
//placeholder callback function
}
void setup(){
Serial.begin(115200);
delay(1000); //Take some time to open up the Serial Monitor
//Increment boot number and print it every reboot
++bootCount;
Serial.println("Boot number: " + String(bootCount));
//Print the wakeup reason for ESP32 and touchpad too
print_wakeup_reason();
print_wakeup_touchpad();
//Setup interrupt on Touch Pad 3 (GPIO15)
touchAttachInterrupt(T3, callback, Threshold);
//Configure Touchpad as wakeup source
esp_sleep_enable_touchpad_wakeup();
//Go to sleep now
Serial.println("Going to sleep now");
esp_deep_sleep_start();
Serial.println("This will never be printed");
}
void loop(){
//This will never be reached
}
Code Description
- The first step is to set the threshold value for touch-sensitive pins.
- When a body, containing an electric charge touches a touch-sensitive pin, the threshold value decreases below 40, that decrease in the threshold value will make ESP32 wake up from deep sleep mode. In the example code threshold value is 40.
- The next task is to store the data into RTC memory (using RTC_DATA_ATTR ) because in deep sleep mode only RTC remains active and all other peripherals, processors, wireless modules will be disabled.
- ESP32 offers 8kB SRAM on RTC to store the data.
- But when you press EN/reset button the data stored in RTC memory will also be erased.
- bootCount an integer type variable is used to count the number of times ESP32 has woken up during sleep mode. The value of bootCount variable is stored in RTC memory.
- The print_wakeup_reason() function is used to print the reason for ESP32 wakeup from deep sleep whether it is due to an external interrupt, timer, or touch-sensitive pins.
- The ESP32 has multiple capacitive touch-sensitive GPIO pins which can be used to wake up esp32 from deep sleep mode.
- Print_wakeup_touchpad() function is used to print the GPIO pin which made ESP32 wake up from sleep mode.
- When you hold a capacitive sensitive pin for a longer duration the threshold value (initialized globally) decreases from its predefines value i.e., 40 which will cause ESP32 to wake up, at that time the callback() function comes into action.
- This function will be used as an argument inside the touchAttachInterrupt() function.
Setup()
- Inside the setup() function the first task is to start the serial monitor with a baud rate of 115200.
- Next, if there is any increment in boot count due to wake up calls, then print that count on the serial monitor.
Call the respective functions to print the wake-up reason:
- Print_wakeup_reason() is used to print whether the ESP32 wake-up is caused by an external interrupt, timer or a capacitive sensitive pin.
- If the wake up is due to a capacitive sensitive pin then the print_wakeup_touchpad() function will print the GPIO pin number which caused the wake-up.
- The next task is to attach the interrupt using touchAttachInterrupt() function, to capacitive sensitive GPIO pin which you will use to wake up ESP32.
- In this example we are using GPIO 15 capacitive sensitive pin as a wakeup interrupt pin.
- esp_sleep_enable_touchpad_wakeup() is used to enable touch sensor feature.
- esp_deep_sleep_start() function is used to make ESP32 enter to deep sleep mode.
- Once ESP32 enters the sleep mode no other operation or data communication is possible until it receives a wakeup call.
Fig 12
Loop()
- In this example code, there is nothing, written inside the loop function. But you can change the code as per your requirements.
Code Testing
- To test the code, use a connecting wire (male to female) and connect one side to ESP32’s touch-sensitive pin (which you have mentioned in the code as an interrupt).
- When you touch that pin an interrupt will be generated to wake ESP32 from sleep.
- You can see the results on a serial monitor or can check the current consumption or can run other functions once it is awake like blinking LED.
- In this code, we are using GPIO_15 touch-sensitive pin.
Fig. 13 waking up esp32 using capacitive sensitive GPIO pin
We have attached a screenshot from the serial monitor for reference.
Fig. 14
Deep Sleep mode and Wakeup Using Interrupt method
Arduino IDE Code
#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 5 /* Time ESP32 will go to sleep (in seconds) */
RTC_DATA_ATTR int bootCount = 0;
/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}
void setup(){
Serial.begin(115200);
delay(1000); //Take some time to open up the Serial Monitor
//Increment boot number and print it every reboot
++bootCount;
Serial.println("Boot number: " + String(bootCount));
//Print the wakeup reason for ESP32
print_wakeup_reason();
/*
First we configure the wake up source
We set our ESP32 to wake up every 5 seconds
*/
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) +
" Seconds");
/*
Next we decide what all peripherals to shut down/keep on
By default, ESP32 will automatically power down the peripherals
not needed by the wakeup source, but if you want to be a poweruser
this is for you. Read in detail at the API docs
http://esp-idf.readthedocs.io/en/latest/api-reference/system/deep_sleep.html
Left the line commented as an example of how to configure peripherals.
The line below turns off all RTC peripherals in deep sleep.
*/
//esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF);
//Serial.println("Configured all RTC Peripherals to be powered down in sleep");
/*
Now that we have setup a wake cause and if needed setup the
peripherals state in deep sleep, we can now start going to
deep sleep.
In the case that no wake up sources were provided but deep
sleep was started, it will sleep forever unless hardware
reset occurs.
*/
Serial.println("Going to sleep now");
Serial.flush();
esp_deep_sleep_start();
Serial.println("This will never be printed");
}
void loop(){
//This is not going to be called
}
Code Description
- The first task is, to define the timer period for which ESP32 will be in deep sleep mode.
- As we know that ESP32 operates at the MHz frequency range so the timer will be in microseconds. So, it is required to convert the time into seconds.
- To add a timer of 5sec we need to multiply 5*1000000.
- bootCount an integer type variable is used to count the number of times ESP32 has woken up during sleep mode. The value of bootCount variable is stored in RTC memory.
Fig 15
- The print_wakeup_reason() function is used to print the reason for ESP32 wakeup from deep sleep whether it is due to an external interrupt, timer or touch-sensitive pins.
Fig. 16
Setup()
- As discussed earlier, inside the setup function first we need to initialize the serial monitor at 115200 baud rate and then print the value of bootCount variable which is incrementing every time a wakeup interrupt occurs.
Fig. 17
- The esp_sleep_enable_wakeup() function is used to enable the timer to generate a timer interrupt by passing time in microsecond as an argument.
- In the beginning of code we have defined some global variable to add 5 sec timer (or 5000000us) and after every 5 sec ESP32 should wake up from deep sleep till 5 sec.
Fig. 18
- esp_deep_sleep_start() function is used to make ESP32 enter the deep sleep mode.
Fig. 19
Testing
- You can see the results of above code on serial monitor as shown is the image attached below.
Fig 20
This concludes the tutorial. I hope you found this useful, and I hope to see you soon for the new ESP32 tutorial.
ESP32 PWM(Pulse Width Modulation) in Arduino IDE
Hello readers, I hope you all are doing great. Welcome to the 3rd Lecture of Section 2 in the ESP32 Programming Series. In this tutorial, we are going to discuss another important feature of ESP32 i.e. PWM(Pulse Width Modulation).
Pulse Width Modulation is a technique to reduce the voltage by pulsating it. In today's lecture, we will first understand the basic concept of PWM, and after that will design two projects to fully grasp it. In the first project, we will control the brightness of an LED, while in the second one, we will control the speed of a DC Motor.
- Here's the video demonstration of PWM Control in ESP32:
Before going forward, let's first have a look at the PWM working:
| Where To Buy? |
|---|
| No. | Components | Distributor | Link To Buy |
| 1 | ESP32 | Amazon | Buy Now |
What is Pulse Width Modulation?
PWM is used to control the power delivered to the load by pulsating the ON-Time of the voltage pulse, without causing any power loss. Let's understand the PWM concept with the help of below image:
- As you can see in the above image, Figure A shows a simple 5V DC signal.
- Figure D shows a simple circuit with a manual switch, now if we turn the switch ON & OFF manually, the Load will also behave in the same way. Its waveform is shown in Figure B, when the switch is ON, we are getting +5V and when it's OFF, output is 0V.
- Instead of manual switching, if we place a fast automatic switching circuit (FETs, MOSFETs etc.), the output pulse won't show fluctuations, instead, it will get steady but its overall power will be reduced.
- Let's understand the working of PWM with an example:
Suppose a DC Motor runs at 200RPM over 5V. Now, if we want to reduce its speed to 100 RPM, we need to reduce its input voltage to 2.5V(approx). So, either we can replace the 5V battery with a 2.5V Battery or use a PWM circuit to reduce the voltage level from 5V to 2.5V. In this specific case, the PWM pulse will be ON for 50% of the time and get OFF for the remaining 50% of the time.
The behavior of the PWM signal is determined by the following factors:
- Frequency
- Duty Cycle
- Resolution
PWM Frequency:
- The Frequency of a signal is defined as the number of cycles per second, denoted by "f" and the measuring unit is hertz(Hz).
- The Frequency (f) of a signal is inversely proportional to its time period(t).
- Let's understand the signal Frequency with the help of below image:
As you can see in the below figure, we have taken two signals for a duration of 1 second. The first signal completes 10 Cycles in 1 second, so we can say it has a frequency of 10Hz, while the second one has a frequency of 5Hz as it completes 5 cycles in 1 second. So, I hope now it's clear that the number of cycles per second is the frequency of a signal.
- The frequency of a PWM signal depends on the provided clock source.
- In the case of microcontrollers, the clock source is provided by the crystal oscillator. So, a 40MHz Crystal Oscillator can produce high-frequency PWM signals as compared to a 20MHz oscillator.
PWM Duty Cycle:
Duty Cycle is the ratio of ON time(when the signal is high) to the total time taken to complete the cycle. The duty cycle is represented in the form of a percentage (%) or ratio. Let's understand the PWM Duty Cycle with the help of below image:
- The 1st graph shows no signal, so we can say it has a 0% Duty Cycle because there's no ON-Time.
- The 2nd graph shows 5 cycles of a signal and in each cycle, the signal is ON only for 25% of the total time. So, its Duty Cycle is 25%.
- In the 3rd graph, the signal has a duty cycle of 50% because it's HIGH for 50% of the cycle.
- You can calculate the 4th graph, its duty cycle is 75% as it is HIGH for 75% of the total duration.
- The last graph shows a pure DC Signal of 5V, and as it is HIGH for the whole cycle, its duty cycle will be 100%.
Resolution:
The resolution of a PWM signal defines the number of steps it can have from zero power to full power. The resolution of the PWM signal is configurable for example, the ESP32 module has a 1-16 bit resolution, which means we can configure maximum a of 65536 (2^16) steps from zero to full power.
Implementing PWM using ESP32
In the ESP WROOM-32 module, there are 16 PWM channels. All the channels are divided into two groups containing 8 channels in each group. The resolution can be programmed between 1 to 16 bits and frequency also depends upon the programmed resolution of the PWM signal.
Now
For the demonstration of PWM in ESP32 we are going to explain two examples:
- Controlling LED brightness using PWM
- Controlling DC motor speed using PWM
ESP32 Code for Controlling LED brightness using PWM
We are using Arduino IDE to compile and upload the code into the ESP WROOM-32 board.
- If you are new to Arduino IDE and ESP32 then follow our previous tutorial, Introduction to ESP32 programming series for detailed information.
- ESP32’s inbuilt LED is used in this code. You can also connect an external LED as per your requirements.
Arduino IDE Code:
// Global variable declaration to set PWM properties
const int ledChannel = 0; // select channel 0
const int resolution = 8; //8-bit resolutin i.e., 0-255
const int frequency = 5000; // set frequency in Hz
int dutyCycle = 0;
void setup()
{
Serial.begin(115200);
ledcSetup(ledChannel, frequency, resolution); // configure LED PWM functionalities
ledcAttachPin(LED_BUILTIN, ledChannel); // attach the channel to the GPIO to be controlled
}
void loop()
{
while(dutyCycle <200)
{
ledcWrite(ledChannel, dutyCycle++); // changing the LED brightness with PWM
Serial.print(" duty Cycle ++ :");
Serial.println(dutyCycle); // display the duty cycle on serial monitor
delay(5);
}
while(dutyCycle>0)
{
ledcWrite(ledChannel, dutyCycle--); // changing the LED brightness with PWM
Serial.print(" duty Cycle -- :");
Serial.println(dutyCycle); // display the duty cycle on serial monitor
delay(5);
}
}
Code Description
Global Variable declaration:
- The first step is to declare variables for setting PWM properties.
- As we have already mentioned that ESP WROOM-32 has 16 PWM channels (0 to 15). So, the first step will be to select a PWM channel between 0-15. In the Arduino IDE code, we are using PWM channel_0 to generate a PWM signal.
- The next step will be to choose the resolution. The maximum resolution for ESP32 is 16-bit. You can choose any value between 1-16. PWM resolution is the factor that decides the maximum duty cycle.
- For example, if we choose 10-bit resolution then the maximum duty cycle of the output signal will be 2^10 that is 1024 (0-1023) and similarly, for 8-bit resolution the duty cycle will be 2^8=256 (0- 255).
- 5KHz or 5000Hz is the PWM signal frequency.
- We also need to initialize a variable to store the duty cycle value.
// Global variable declaration to set PWM properties
const int ledChannel = 0; // select channel 0
const int resolution = 8; //8-bit resolutin i.e., 0-255
const int frequency = 5000; // set frequency in Hz
int dutyCycle = 0;
Arduino Setup() Function
- Inside setup() function we are going to start serial monitor at 115200 baud rate.
Serial.begin(115200);
- To configure PWM properties we are calling the ledcSetup() function which uses PWM properties (like PWM channel, frequency and PWM resolution) as arguments.
ledcSetup(ledChannel, frequency, resolution); // configure LED PWM functionalities
- ledcAttachPin() function is used to assign the LED_BUILTIN pin to the PWM channel.
ledcAttachPin(LED_BUILTIN, ledChannel); // attach the channel to the GPIO to be controlled
Arduino Loop() Function
- Inside the loop function, we going to run a conditional control loop (while loop) to change the LED brightness along with the change in duty cycle.
- At first, the value of the duty cycle is going to increase continuously until it reaches max 8-bit resolution ( that is 255).
- The serial monitor will print the duty cycle value with some delay.
while(dutyCycle <200)
{
ledcWrite(ledChannel, dutyCycle++); // changing the LED brightness with PWM
Serial.print(" duty Cycle ++ :");
Serial.println(dutyCycle); // display the duty cycle on serial monitor
delay(5);
}
- After increasing the duty cycle to maximum resolution another while loop is used to decrease the duty cycle to value 0 from 255 and proportionally the LED brightness and the PWM output will be printed on the serial monitor.
while(dutyCycle>0)
{
ledcWrite(ledChannel, dutyCycle--); // changing the LED brightness with PWM
Serial.print(" duty Cycle -- :");
Serial.println(dutyCycle); // display the duty cycle on serial monitor
delay(5);
}
Code Testing
- You can see the change in the value of the duty cycle on the serial monitor. We have attached a screenshot below from the Arduino IDE serial monitor for reference.
- For a better understanding of PWM output you can use an oscilloscope (either CRO or DSO) by connecting the PWM output pint and GND pint to the oscilloscope probe, if available.
- You can also use a serial plotter to see the PWM output if you do not have an oscilloscope.
- To access the serial plotter, use sort-cut key shift+ctrl+L or follow the image attached below:
Fig. 8 Arduino IDE Serial Plotter
- We have attached a screenshot of the PWM output waveform from the serial plotter for better understanding.
- You can vary the value of duty cycle anywhere between 0-8 bit resolution.
- For example in the image attached below the duty cycle is 200.
Fig. 9 Serial plotter PWM output
ESP32 Code for Controlling DC motor speed using PWM
Fig. 10
In this example, we are going to implement PWM using ESP WROOM-32 to control the speed of a DC motor.
The speed of the DC motor depends upon the input power supply. So, by varying the power input we can also vary (increase or decrease) the speed of DC motor.
Hardware components required:
- ESP WROOM-32 board
- DC motor
- L298N motor driver
- Connecting wires
- Data cable
L298N motor driver: A motor driver is used between the ESP32 board and DC motor to resolve the power compatibility issues.
Both the ESP32 board and DC motor operate at different power ratings due to which you can not connect the two devices directly. So a motor driver is used to receive a low power input from the ESP32 board and drive/run DC motor at slightly high power.
L298N can drive a DC motor that operated between 5 to 35 voltage range and maximum current of 2A.
There are various DC motor drivers available in the market for example L293D, DRV8833, MAX14870 single brushed motor driver etc. You can choose the driver of your choice depending upon the application and power ratings.
Fig. 11
FIG. 12 IC L298N pin-out
- You can also change the direction of rotation by connecting the input as per the table drawn below:
| IN_1 |
IN_2 |
Rotation |
| HIGH |
LOW |
DC motor rotates in a clockwise direction |
| LOW |
HIGH |
The motor rotates in an anti-clockwise direction |
| LOW |
LOW |
Motor STOP |
| HIGH |
HIGH |
Motor STOP |
Table 1
Arduino Code
//configure GPIO pins to connect motor driver
int enable1Pin = 14;
int M_Pin1 = 26;
int M_Pin2 = 27;
// Setting PWM properties
const int freq = 10000;
const int pwmChannel = 0;
const int resolution = 8;
int dutyCycle = 150;
void setup()
{
Serial.begin(115200);
// sets the pins as outputs:
pinMode(M_Pin1, OUTPUT);
pinMode(M_Pin2, OUTPUT);
pinMode(enable1Pin, OUTPUT);
//Configure LED PWM functionalities
ledcSetup(pwmChannel, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(enable1Pin, pwmChannel);
Serial.print("Testing DC Motor...");
}
void loop()
{
// Move the DC motor in anti-clockwise direction at maximum speed
Serial.println("Moving reverse");
digitalWrite(M_Pin1, LOW);
digitalWrite(M_Pin2, HIGH);
delay(500);
// Move DC motor forward with increasing speed
Serial.println("Moving Forward");
digitalWrite(M_Pin1, HIGH);
digitalWrite(M_Pin2, LOW);
//----while loop----
while (dutyCycle <= 255)
{
ledcWrite(pwmChannel, dutyCycle);
Serial.print("Speed increasing with duty cycle: ");
Serial.println(dutyCycle);
dutyCycle = dutyCycle +5;
delay(100);
}
while (dutyCycle >150)
{
ledcWrite(pwmChannel, dutyCycle);
Serial.print("Speed decreasing with duty cycle: ");
Serial.println(dutyCycle);
dutyCycle = dutyCycle -5;
delay(100);
}
// _____Stop the DC motor
Serial.println("STOP DC motor");
digitalWrite(M_Pin1, LOW);
digitalWrite(M_Pin2, LOW);
delay(500);
}
Code Description
- The first step is to configure GPIOs which are to be connected with the DC motor driver (L298N).
- Here we are using three GPIOs, the first one is connected with the Enable_A pin and the rest of the two are connected with motor inputs.
- You can also control 2 motors with the same driver using Enable_2 and its respective input pins.
//configure GPIO pins to connect motor driver
int enable1Pin = 14;
int M_Pin1 = 26;
int M_Pin2 = 27;
- The next step is to define variables to store PWM properties as discussed in the previous example.
- You can vary the frequency and duty cycle of the PWM signal as per your requirements but, within the desired range.
- Here we are assigning 10000Hz or 10KHz frequency with 8-bit resolution (0-255 duty cycle) and the initial duty cycle value is 150 for PWM channel 0.
// Setting PWM properties
const int freq = 10000;
const int pwmChannel = 0;
const int resolution = 8;
int dutyCycle = 150;
Arduino Setup() Function
- Inside the setup function, the first task is to initialize the serial monitor with a 115200 baud rate.
Serial.begin(115200);
- Set the operating mode of three GPIO pins (which are to be connected with motor driver board) as output.
// sets the pins as outputs:
pinMode(M_Pin1, OUTPUT);
pinMode(M_Pin2, OUTPUT);
pinMode(enable1Pin, OUTPUT);
- Call the function ledcSetup() to configure PWM properties by passing PWM properties as arguments.
//Configure LED PWM functionalities
ledcSetup(pwmChannel, freq, resolution);
- Next, you need to select the GPIO pin which will provide the PWM output from ESP32 to the motor driver using ledcAttachPin() function which uses the PWM output pin and PWM channel as two arguments.
// attach the channel to the GPIO to be controlled
ledcAttachPin(enable1Pin, pwmChannel);
Arduino Loop() Function
- Start rotating the motor in the anti-clockwise direction. Follow Table 1 for more details regarding the direction of rotation.
- Add the delay of 0.5 sec or as per your requirements.
Fig. 19
- Rotate the DC motor in a clockwise direction by setting M_PIN1 as high ND m_Pin2 as low.
Fig. 20
- As we have initialized the duty cycle variable with a value of 150. Now, increase the motor speed by increasing the value of the Duty cycle from 150 by increasing 5 steps continuously until it reaches the maximum value that is 255.
Fig. 21 Increasing speed
- After reaching the maximum speed at 255 duty cycle, now let's decrease the speed of DC motor till 150 duty cycle with the decrease of 5 steps every time.
Fig. 22 Reducing speed
- Stop duty cycle by either writing both the motor pins(M_Pin1, M_Pin2) to LOW or HIGH (like XOR gate).
Fig. 23 STOP DC motor
Code Testing
- For a better understanding, open the serial monitor using shortcut keys ctrl+shift+M.
- On the serial monitor, you can see the increase and decrease in duty cycle and can compare it with DC motor speed.
Fig. 24 PWM output on serial monitor
- You can also check the PWM output on the Serial plotter by pressing the ctrl+shift+L keys.
- It is visible through the waveform that the duty cycle is varying from 150 to 255 and reverse and proportionally the seed of the DC motor.
Fig. 25 PWM output on Serial Plotter
This concludes the tutorial. I hope you found this useful, and I hope to see you soon for the new ESP32 tutorial.
The Complete Guide to Nearshoring
The nearshoring phenomenon is a global economic trend that has been going on for decades. The phenomenon is defined as moving a company’s operations to a country that is in close proximity to the company’s home base.
Nearshoring offers many benefits in terms of cost savings, but it also has many drawbacks. It can have a negative effect on wages for local workers, and it can also have an impact on the environment if the process involves bringing in outsourced goods from overseas.
To conclude, nearshoring often benefits both companies and consumers who are looking for affordable goods at low prices. However, it can have a negative effect on wages and local jobs in the long run.
It's a great way for companies with smaller budgets to have more resources for other aspects of their business. However, it isn't without its challenges. For starters, a company will need someone on-shore to manage the team abroad and provide direction on how things should be done. In addition, there are cultural differences that may need to be addressed - such as different time zones or mores that may not line up with American values.
Why Nearshoring is Becoming so Popular
Nearshoring is becoming more popular because of the benefits it offers for both the outsourcing company and the nearshore company.
Nearshore outsourcing provides cost savings to companies that are looking to outsource their work. It offers lower overall risk than offshore outsourcing through the protection of intellectual property and by having better communications with the workforce.
While offshoring has been around for decades, nearshoring started gaining popularity in recent years due to its relative proximity to home markets, enabling companies to make quick decisions about products, services, marketing approaches, etc., which can be challenging when you are thousands of miles away. Nearshoring is appealing because it provides cost savings and lower risk than offshoring.
Why Is Nearshoring Useful?
Nearshoring is a strategic sourcing technique that can be used to lower the cost of labor. It is also helpful in reducing the production lead time by enabling production capacity to be shared among different regions while centralizing key functions.
Nearshoring allows companies to take advantage of low-cost labor without having to relocate their manufacturing facilities. Through nearshoring, companies are able to maintain control over design and marketing while lowering production costs through outsourcing manufacturing processes abroad for example in China or India.
What Countries Offer a Nearshore Workforce?
There are many countries in the world that offer a nearshore workforce and they differ in terms of their cost and quality. Some countries like India and China, with low labor costs and large populations, are popular outsourcing destinations. Other countries such as Indonesia and Malaysia, offer higher quality work based on their educational system. Nearshoring in Europe is also becoming more and more popular because of the low costs and good quality of the work.
There are many factors to take into account when outsourcing business processes or operations to a country. The type of work you need to be done will determine the country you choose for your operations, but there is one key factor that is often overlooked: the availability of human capital. Countries vary in terms of how educated their population is and what languages they speak, which can give an edge when it comes to choosing a country for your overseas operations.
What are the Disadvantages of Nearshoring?
- Language barriers can lead to communication breakdowns.
- The more time zones that are involved, the more likely it is that the business will be interrupted by time zone differences.
- Cultural differences may lead to some employees feeling uncomfortable with their working environment and may even cause some employees to quit because they do not want to work in an environment where they do not feel welcome or appreciated.
- High turnover rates among offshore workers will mean that more effort has to be spent on training new employees.
The most prominent disadvantage is that organizations will lose vital skills and know-how when they outsource their projects. They may also lack the flexibility in decision-making for both short and long-term goals due to limitations on management decisions brought about by working with a third-party company. Organizations will also have a difficult time transferring any of their employees to different locations if they decide they want them closer to home in order for them to take care of family issues or have more opportunities for growth.
5 Ways to Prevent Your Car from Being Stolen
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at the 5 Ways to Prevent Your Car from Being Stolen. Every year over 720,000 motor vehicles are stolen, according to the official site of the United States government. Thieves have gotten savvy, using technology and new methods to make stealing cars easier than ever. It is crucial to take steps to protect your vehicle from being stolen. Here are five ways to do just that:
Install a Security System
A good security system includes an alarm, immobilizer, and battery backup if you lose power to your car for any reason. It should have a remote lock/unlock capability which can be helpful if someone finds or steals your keys. You can even get systems these days that notify you on your phone if someone is trying to start your car.
The system should also have a GPS vehicle tracking device if your car is stolen. The police can track the car down and return it to you. The GPS device should enable you to monitor your car and what routes they have taken. Some of these devices will even allow you to set up alerts if the vehicle has been moved at any time during its idle state, which is excellent for catching thieves in action and alerting authorities immediately.
An added benefit of using a GPS tracking service is protecting your car from being towed. If thieves tow your vehicle, you can log into the service and search to see where it has been taken so that you know who stole it and call authorities immediately.
An excellent security system needs to be fitted with an alarm that will go off when someone unauthorized tries to open the car. The louder and more intrusive the alarm, the better. This way, the car's owner will be notified of a possible theft attempt and take precautions. You need to choose an alarm that alerts you when the car is being tampered with and one that can be activated remotely.
Steering Locks and Wheel Clamps
One way to prevent your car from being stolen is to install a steering lock. This will make it difficult for thieves to drive off with the car. There are a few different types of steering locks available on the market. A popular type is the club lock, which wraps around the steering wheel and prevents it from being turned.
Another option is to install a car alarm with a steering lock feature. This will sound an alarm if someone tries to move the car. Some cars come with a built-in steering lock that is activated when turned off.
If your car doesn't have a built-in steering lock, you can buy an aftermarket one to use. Whichever option you choose, make sure to properly secure the steering lock so that it cannot be easily removed. Another option is to use a wheel clamp. This will immobilize the car and make it difficult for thieves to steal.
Both of these solutions are a great deterrent against car theft and will help to protect your vehicle. Be sure to use them if you are concerned about your car being stolen.
Lock Your Car
This may seem like a no-brainer, but many people forget to do this essential step. Make it a habit to always lock your car doors and windows when you're not in it. This will make it more difficult for thieves to access your vehicle. If you're not in a hurry, you can also roll up your windows all the way and shut the doors.
If someone stops next to your car asking for help or directions, don't get out. Stay in your car and keep the doors locked. This allows criminals to unlock it from outside of the vehicle. Many times they will open already unlocked cars with this tactic.
The simplest thing you can do to keep your car from being stolen is always to lock your doors after getting out or entering the vehicle. This is especially important if you habit leaving your car running when you run into the store.
Park in a Well-Lit Area
If you park your car in a well-lit area, it will be less likely to be targeted by thieves. Try to avoid parking in isolated or dark areas whenever possible. If you have a garage, use it.
If you have to park on the street, try finding a well-lit spot near other cars. This will make your vehicle less of a target for thieves. In a public parking lot, always park in an area close to the entrance and visible.
If you park under a tree, try to avoid parking near an overhanging branch that thieves could use as leverage for opening your car door or climbing inside. If possible, choose brightly lit areas with surveillance cameras nearby so the footage can be used to identify thieves in case they steal your vehicle.
When looking at potential spots to park, always be aware of your surroundings and look for any suspicious activity. If you see anything that makes you uncomfortable, find another spot to park in.
Don't Leave Valuables in Your Car
One of the best ways to prevent your car from being stolen is to not leave any valuables in it. If you have expensive items in your car, it will be more likely for thieves to target your vehicle. So, always make sure to take your belongings with you when you exit your car.
If you have to leave something in your car, try to keep it out of sight. You can put it in the trunk or under the seats. If you need to put things in the trunk or in the backseat, make sure to lock them up so that thieves can't get to them. You should also do this before you reach the parking lot so that thieves can't see what you're doing.
Remember, the best way to prevent your car from being stolen is by taking precautions and being vigilant about your surroundings. You can make it much more difficult for thieves to get their hands on your vehicle by following these tips.
Manufacturing Process of Multilayer PCB
Hello! Readers, I hope you are pretty good. I am here with a new article to enhance your knowledge about advanced technologies. Today, we will have a detailed overview of the Manufacturing Process of Multilayer PCB. First, we will have a look at its basic definition, why there Is a need for this new type of PCB in presence of single layer and double layer PCBs. What are the merits and demerits of multilayer PCBs and pedagogy behind the construction process of these PCBs? Let’s start to take in all information about these PCBs. I try my best to deliver all of my research capacity for doing this job.
Introduction to Multi-layer PCBs
As to the name, it's clear that multi-layer PCBs are those which have several conductive layers over substantial material which is knowns as substrate. Unlike single layer and double layer PCBs which consist of one and two copper foil layers respectively, multilayer PCBs contain more than three lays on a single board.
Before discussing the multi-layer PCBs let put a throwback to What’s PCB. How are they classified and what are they used?
Printed circuit board (PCB)
The word PCB comes from a printed circuit board that consists of sleeky copper chips on it which are conductive. These tracks are linked with each other electrically.
How to Manufacture Multilayer PCB?
In order to manufacture a PCB board, you need to take the help of a PCB Fabrication company. There are many online PCB companies available. where you can place your PCB order on their official website. While placing your order, you need to select all your specifications/requirements and they will give you the cost and time to complete it. Let's place an order of Multilayer PCBs on PCBWay Fabrication House. PCBWay is a well-renowned PCB Fabrication house, provides excellent prices and discounts on first orders. Moreover, they have an excellent support team, ready to help you, 24/7. So, let's place our PCB order:
- First of all, open the official site of PCBWay(PCB Manufacturing House).
- Now, at the top, you will find an instant quote screen, click on the button to open the PCB Calculator page, as shown in the below figure:
- As you can see in the above figure, I have placed an order for a multilayer PCB having 4 layers.
- I have added a size of 100x100mm and have placed an order for 10 pcs of PCB.
- PCBWay has given me a cost of $139 for standard manufacturing and with shipping in America, the total cost is $166.
That's how easy, you can place a manufacturing order for PCB.
Criteria for classification of multi-layer PCBs
There are many ways by which we can categorize different types of PCB. Most commonly they are classified on basis of their layers , types of substructure material , conductive layers and rigidness of the boards, etc. Now put a little thought into describing these methods.
- Number of layers
- Type of base substantial
- Thickness of conductive layer
- Rigidness
Number of layers
This methodology divides PCBs into single-layer PCB , double-layer PCB, and multi-layer PCB . if PCB has a computerized structure on one side then it terms a single layer PCB. if they have a circuit on both sides of the board then it is termed as double-layer PCB but with the invention of technology and with the enhancement of our need we require complex electronic structures which take less space but do more than one task on a single device. Due to which we mounted more than two layers over a single board to form a multi-layer PCB. It has more layers and flexibility than two earlier PCBs which are single layer PCB and double layer PCB. Under the present rank of technology, we can form PCB having almost 32 layers.
Type of base substantial
The material which is mostly used in the preparation of PCBs is fiberglass, cyanate ester, polyamide, and polyester reinforcement. The substantially material should be
- Dimensionally stable under heating process
- Have good strength of attachment with another conductive layer
- Beneficial in electrical impedance
- Highly elastic
The thickness of the conductive layer
This method sort out the PCBs on the basics of consistency of copper foil and the breadth of conductor route onboard. The board ness of a copper layer may alter from 0.0014 to 0.0042. These factor combined determines the cross-sectional area of the board. Which in return decides how much current can a conductor carry.
Rigidness
For offering the reinforcement to the circuit which must have an electrical connection between them we require a rigid PCB. To furnish the rigidity, the thickness of the board must be almost 1.6mm. variety of substantial materials are used for this purpose.
Kinds of PCB
There are three kinds of PCB as given below
- Single layer PCB
- Double-layer PCB
- Multilayer PCB
Overview to multi-layer PCB
- If you are focus on the name of this PCB which is Multilayer it clear that it is a type of PCB which have more than two layers. In simple Words multilayer PCB have several conductive layers on a single board.
- They are favored in many elegant industrial tasks and motherboards etc.
- Most importantly where we need to save space we can use these PCBs for example in a digital camera, android mobiles even on compact disk.
- Multi-layer PCBs which are available now a day in markets have 4 to 8 layers.
Construction of multi-layer PCB
- Multi-layer PCBs area unit designed by connecting all the quantity of lays and material at heat and pressure therefore on take away any at bay air between layers.
- Organic compounds and staff are employed to stay the parts and different lays along.
- You have a choice in choosing a variety of materials like exotic ceramic, epoxy glass, Teflon, etc. to fabricate the PCB.
- The various prepreg and core layers area units combined and bear the lamination methodology happening at heat and pressure that helps to moderate the layer along. Later on, the PCB is cooled then it becomes rigid and solid board.
- The internal layers of multi-layer PCBs consist of special material which is known as prepreg.
What is prepreg?
- The lays of the healed panel in multi-layer PCB are freestanding by a sheet of B stage organic compound, which is termed prepreg. This layer aims to adhere to the rigid layer with each other and fixing the board between layers.
Problems faced by experts in manufacturing multi-layer PCBs
One biggest issue faced by manufactures while dealing with fabrication of multi-layer PCBs is drilling hole technology.
Technique for interconnecting layers on MLBS
We can make an electrical connection between components which present on several layers of multilayer PCB by using different methodologies which we are given below ;
- Through-hole via
- Through buried via
- Through blind via
What is via?
As we discuss in the previous article VIA is a vertical hole on board that is then filled with metal foil for interconnecting the component. Different modes of via to tackle this situation are elaborated below ;
Through-hole via
By using this technique we can join components of the upper side of multilayer PCBs
Through buried via
By using this pedagogy we can link the internal lays of multi-layer PCBs.
Through blind via
A blind via can link the topmost layer with internal layers of multilayer PCB.
Lamination method of multi-layer PCBs
- Internal layer gist, coating of B stage resins, and coating of atomic number 29 foil are used in the lamination process of multi-layer PCBs.
- Drilling of holes in the coating of substrate and core is utilized to line up them as they are stack aboard.
- For a four-layer PCB, we require a sheet of foil and a suitable range of woven glass cloth with epoxy resin.
- The stack of the panel is fabricated on a meaningful conductive plate and once it’s completed the plate becomes a valuable board.
- Now we heat this board under necessary conditions.
- The application of pressure, heat, and vacuum on board forced the organic compound to become flexible and consistent across core and foil surfaces.
Why do we need multi-layer PCB?
Here we discuss under which situation we preferred multilayer PCB over the other two.
- To tackle problems related to weight and volume which are commonly seen by experts during their works multi-layer PCB Is their solution.
- For a composite electrical circuit, multilayer PCBs are less pricy than a single layer and double layer PCB.
- Multilayer PCBs are help full in reducing the resistance problems in an electrical circuit and increase the chances of supply of current which in return increase the flexibility and demand of products.
- It increases the reliability of electrical circuits
- For a circuit that requires several numbers of interconnection multilayer PCBs are ideal. They allow high-speed performance.
Common mistakes in the manufacturing process of multi-layer PCBs
- Irregularities of electrical connections onboard are the biggest problem by which ones have to tackle.
- Delay between layers during bonding causes poor care in bonding. Other puzzling circumstances are discussed below.
- High resistance causes a big issue due to poor plating in holes.
- Inadequate tooling techniques.
- Due to high stuff of components into small available space causes an uninventive structure.
Key points to overcome these problems
To get better-fabricated multi-layer PCBs one should follow these steps
- The developer must be highly experienced and he must concentrate their attention on quality.
- He must have the strength to control the process.
- The board must be stocked in a bit of time and dried for almost 120 minutes at 120°C.
Advantages of multi-layer PCBs
There are many merits of multi-layer PCBs. Let’s start to grasp the knowledge about advanced technology rewards.
- We can tackle many problems at a time by using multi-layer PCBs.
- It offers less resistance and enhances power distribution between electric components on board.
- Multi-layer PCBs are less weight and have a small size which has adorable uses in advanced technology which becomes handy with time.
With the aid of multi-layer PCBs, we can have boards which although are small in size but are more compatible to tackle problems.
- Multi-layer PCBs are favored for the high-speed circuitry process.
- Multi-layer PCBs decreased the chance of EMI expelling which comes due to small loop area and high distributed capacitance.
- Multi-layer PCBs are highly persistent as they are configured at a High level.
- With the increments of layers in a single structure trim the size and become compatible to link more electronic components in the available space.
- Multi-layer PCBs are designed by high standardized fellowship therefore multi-layer PCBs are prefabricated.
Disadvantages of Multi-layer PCBs
As we know that there is some raw fact about everything. Multi-layer PCBs also have a demerit. The weakened point of multi-layer PCBs are discussed below;
- Multilayer PCBs require High expenditure. The manufacturing process of Multi-layer PCBs requires a heavy budget.
- Although multi-layer PCBs are very worthy due to their small size in advanced technology at the same time, It is not an easy task to tackle with an intensive circuit on a single board. A very careful mental focus is required while working with multi-layer PCBs.
- It is difficult to mend and retread the interconnection of multi-layer PCBs.
Applications of Multi-layer PCBs
Multi-layer PCBs have outstanding features. This worthy characteristic makes it popular for usage. Multi-layer PCBs have applications in household appliances, industrial works, wireless computing, ballistic capsule, and many other instrumentations. Multi-layer PCBs have distinguishing characteristics in the development of vast practical applications. Some applications of Multi-layer PCBs are illustrating below;
- Because of their small size, multi-layer PCBs are utilized in handy technologies like android mobiles, cameras, motherboards.
- Multilayer PCBs are used in signal transmission which requires more accuracy in processing.
- Multilayer PCBs are used in navigational computing.
- Multi-layer PCBs are used in holding the data safely.
- Multilayer PCBs are used in communicating technologies. The use of multilayer PCBs trims the size of new inventions.
- Multi-layers PCBs are used in challenging situations for the trial process of different instrumentations.
- For forecasting atmospheric conditions multi-layer PCBs are used.
- Multi-layers PCBs are used in the instrument which is utilized for observing the cardiac conditions.
- Multi-layers PCBs are Second hand in warning devices.
- Multi-layer PCBs play an important role in the fabrication of robotic space Vehicles designed to voyage the earth's orbit.
- Multi-layer PCBs are used in computed axial tomography scanners helpful to an analyzed brain tumor.
- Multilayer PCBs are used in roentgen ray instrumentations. These instruments tackle medical problems.
- Multi-layer PCBs are used in industrial systems for controlling purposes.
- Multi-layer PCBs are specifically worthy in technology associated with satellites, missiles, aircraft, and spacecraft.
- Even we can say that the building block of innovative conception is multi-layer PCBs. It becomes the need of fast, durable, flexible and valuable designs.
Conclusion
In the end, we conclude that there are more number layers in multi-layer PCBs than single and double-layer PCBs. Multi-layer PCBs have Unmatched properties, valuable applications but in the end, nothing is perfect each technology has some drawbacks like this multi-layer PCBs also have some drawbacks.
In modern computing, the demand for multi-layer PCBs is more than the other two PCBs.
- You always need to opt for which kind of PCB you would like.
That’s all for today’s article. I hope you've got enjoyed the article and build a grip on the understanding points. However, if you continue to face any skepticism concerning multi-layer PCB then please be at liberty to depart your queries within the comment section. I'll give a solution to those inquiries to the simplest of my data and researching skills. Also, give North American country along with your innovative feedbacks and suggestions you improve the standard of our work and supply you content in keeping with your wants and expectations. keep tuned! thanks for reading this text.
ESP32 Web Socket Server
Hello readers, hope you all are doing great. In this tutorial, we will discuss another ESP32 protocol that is Web Socket and we will also explain how to create a web server using web socket protocol with ESP32. So, we will have a look at What is a web socket server, How web socket protocol is different from HTTP protocol, What is handshaking in networking, Three-way handshaking, Web socket application, Creating web socket server using ESP32 module etc. Let's get started:
| Where To Buy? |
|---|
| No. | Components | Distributor | Link To Buy |
| 1 | ESP32 | Amazon | Buy Now |
What is a web socket protocol?
Fig 1 Web-socket server
A Web Socket is a full-duplex (both the server and the client can send and receive data at the same time) computer communication protocol. Web socket protocol, like HTTP (hypertext transfer protocol), also works in server and client communication format. A web socket uses a process known as handshaking to establish communication between the server and client. This protocol is also known as the stateful protocol. When a client device requests communication with the server, a connection is established between the server and the client, and the connection remains in place until either the server or the client terminates it.
How web socket protocol is different from HTTP protocol?
- Both, web socket and HTTP protocols are computer communication protocols and both the protocols work on the 4th layer of TCP (transmission control protocol). But still, there are multiple specifications that make them stand apart from each other.
- Unlike web socket protocol, HTTP is a half-duplex protocol (half-duplex protocol means that the client and server can either transmit or receive data at a time). It is a connection-oriented protocol.
Fig. 2 HTTP protocol
- When we need to update a web page over HTTP, we have to update the complete web page before updating any data. To overcome this drawback, the most efficient solution is using a web socket protocol to receive updated data in real time. Along with that web socket protocol also saves a significant number of clock cycles for resource-intensive applications.
Fig. 3 web socket protocol
- Whenever a client sends an HTTP request to a server, a TCP connection will be open between the server and client and when the server responds to that request the TCP connection between server and client will be terminated immediately.
- HTTP protocol uses three-way handshaking which guarantees the transmission of the data packet and re-transmit the lost data packet.
- Web socket starts with ws:// (web socket) or wss:// (web socket secure) whereas, HTTP starts with http://.
What is Handshaking in networking?
- It is the process of establishing a connection between server and client. Handshaking determines the protocol, error correction scheme and speed etc. to be used for communication.
Fig. 4 Handshaking
- Handshaking is necessary at the start of each communication session to ensure successful server and client communication despite some hardware or software configuration differences.
Three-way handshaking
In TCP/IP (transmission control protocol/ internet protocol) network, three-way handshaking is used to create a communication channel between server and client.
Three-way handshaking steps are:
- Establishing a connection between server and client.
- Server receives an SYN (synchronize sequence packet) packet from the client device.
- Client device receives the ACK (acknowledgment sequence number) signal from the server and responds with an ACK packet.
Fig. 5 Three-way handshaking
Web socket Application
Web socket is used in real-time applications where a client is required to respond quickly to a change or update. The various web socket applications are:
- Chat application
- Online education
- Sports update
- Location-based applications
- Financial Tickers
Creating Web Socket Server Using ESP32 Module
To create a web socket server using ESP32 we are using Arduino IDE as a compiler. Arduino IDE will compile the code and will also upload the compiled code into the ESP32 hardware module.
If you are not familiar with using the Arduino IDE compiler for ESP32 programming then follow our #1 tutorial that is about Introduction to ESP32 programming series.
Code
Code description
- Download the required libraries (AsyncTCP and ESP32 WebServer) from the given link:
https://github.com/me-no-dev/AsyncTCP
https://github.com/me-no-dev/ESPAsyncWebServer
Follow our tutorial Introduction to ESP32 programming series to learn about adding a library in Arduino IDE.
- Import the required libraries.
- We are using three libraries to create a web socket server:
- WiFi.h: This library is used to connect ESP32’s wifi module with the internet. It makes a wi-fi device to serve either as a client or a server.
- AsyncTCP.h: This library is an asynchronous TCP library, used to enable a multi-connection, trouble-free network environment.
- ESPAsyncWebServer.h: This library is used to create an asynchronous web server.
Fig. 6 Libraries
- Initialize a variable “LED_Status” to store the status of inbuilt LED (internally connected to GPIO 2.
- Enter the SSID and password as per your network credentials.
- To create a web server we need to assign a port and port 80 is used for a local server.
- Here we are creating an AsyncWebserver object with port 80 and another object AsynchWebsocket to handle connection at /ws path.
- After assigning the port and path for the webserver and web socket respectively, the next step will be to create and design a web page.
- We are using HTML (hypertext markup language) to create a web page to display LED status and change the state of the LED.
- The complete HTML code is stored inside a variable “index_html”, which is used to display and style web page content.
- Inside the index_html variable, the Style tag consists of all the instructions regarding styling the web page like the text color, font size, background color, font face etc. You can those instructions as per your requirements.
Fig. 10 <style> tag
Fig: 11 Styling the button
- Inside the body tag, all the instructions required to display the content like text, heading etc is defined.
Fig. 12 <body> tag
- <h1>ESP32 Web-Socket Server</h1> is the heading to be displayed on the top of the webpage.
- <h2>LED1</h2> is the second heading for LED.
- A button with text written to change the status of LED from LOW to HIGH and vice- versa.
- Java-Script: When the webserver interface is fully loaded in the browser, it is used to set up a web socket connection with the server and handle data exchange via web socket. It is written inside <script> tag.
Fig. 13 script tag
- window.addEventListener('load', onLoad) Here the onload() function calls the initWebSocket() function and initButton() function to initialize the websocket connection with the server and add event listener to the button respectively.
- Gateway is the entry point for the web socket which gets the IP address.
- initWebSocket() initialize the web socket connection at the obtained IP address.
- When a connection is established between the server and client, the client will send a message to the ESP32 server to ensure the connection.
- initWebSocket() will be called again after 2 sec if somehow the connection is closed.
Fig 14 initWebSocket()
- The next step will be to update the status of LED on the web page.
- When the server receives the changes in the state of LED which are requested/made by the client, the ESP32 will update the status of the LED on hardware and then acknowledge to the client.
Fig. 15 Update LED status on the web page
- The function notifyClients() is used to update the current status of LED to the client device.
Fig. 16 Notify clients
- handlWebSocketMessage() is a callback function that will run when the server receives a new message from the client through a web Socket.
Fig. 17 handles web (client) socket message
- To configure the web socket server a function onEvent() is defined, to handle different asynchronous steps for the web socket.
- The function initWebSocket() is used to initialize web socket protocol.
Fig. 18 Initialize web socket
- The processor() is used to search for a placeholder on the web page.
- The %STATE% placeholder will be replaced with the current LED state i.e. HIGHT for ‘1’ and LOW for ‘0’.
Fig. 19 Placeholder
Setup()
- Inside the setup(), first of all we will initialize the serial monitor with 115200 baud rate.
- Then, set the LED as output and write the LOW or ‘0’ state for LED.
Fig. 20
- Call the WiFI.begin() function, which is having arguments ssid and password.
- Continuously check the Wi-Fi status and print on the serial monitor once connected.
Fig. 21 Wifi status
- If the ESP32 is connected with wi-fi then fetch the IP address and print it on serial monitor.
- Iinitialize the web socket by calling initWebSocket() function.
Fig. 22
- Pass the index_html variable as an argument to serve the text stored, when you receive a request on the URL.
- Pass the processor() as an argument to replace the placeholder.
Fig. 23
Fig. 24
Loop()
- The cleanupClients() function is called continuously in the loop function to close the previous client connection when the maximum client-connection limit is reached. Sometimes evening after calling the close function, the browser does not properly terminate the connection which can crash the server.
- To avoid the server crash, cleanupClients() function is used.
- Keep updating the status of the LED to LED_Status variable.
- Print the LED status on the serial monitor using serial.println(“ ”).
Testing/Results
- For testing purposes, we are using the inbuilt LED which is connected to GPIO 2.
- You can see the updated status of the LED on the web page with an IP address of (192.168.43.233 in our project).
- In this code, ESP32 is acting as a server both the ESP32 module and laptop/ mobile phone should be connected to the same wi-fi network.
- Compile and upload the code into ESP32 using Arduino IDE.
- Open the serial monitor and copy the IP address.
- Enter the IP address in the browser.
- A web page will be displayed on the screen.
- Now you can change the status of ESP32’s inbuilt LED by clicking on the “change LED status” button.
- Screenshots of the Serial monitor and web page are attached below for better understanding.
- In the first image, you can see the IP address and status of the LED is printed on the serial monitor.
Fig 26 Arduino IDE Serial monitor
Fig. 27 Web page displaying LED status HIGH
Fig 28 Web page displaying LED status LOW
Fig. 29 ESP32 LED HIGH
This concludes the tutorial. I hope you find it helpful. In our next tutorial, we will discuss PWM (pulse width modulation) using ESP32.