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.
ESP32 Interrupts
Hello readers, hope you all are doing great. Today, we will discuss interrupts and timers in ESP32 and how to handle internal as well as external interrupts. So, we will discuss What is interrupt, Polling, ESP32 interrupt, Software interrupts, Hardware Interrupts, IRS (Interrupt Service routine), Steps to execute an interrupt or how is an interrupt handled in the microcontroller, Code description for ESP32 interrupts with Arduino IDE, Code description for hardware interrupts, Why is it preferred to use timer to add delay instead of using delay() function. So, let's get started:
Where To Buy? |
---|
No. | Components | Distributor | Link To Buy |
1 | ESP32 | Amazon | Buy Now |
What is Interrupt?
- Interrupts are used when a micro-controller needs to continuously monitor for an event while the same micro-controller is executing a particular task.
Fig 1 Interrupt
- Each interrupts has a priority level and each interrupt is executed as per their priority level.
- You can mask or unmask a particular interrupt depending upon their properties and your requirements.
Polling
Polling is a process that performs continuous monitoring. Basically, the processor continuously monitors the state of a specific device or a peripheral, and when the status of the device satisfies the condition, the device executes the task that was required. Then it moves on to the next device to monitor until each one has been served. The processor performs no other operations and devotes all of its processing time to monitoring, and all other tasks are suspended until the current one is completed.
Fig 2 polling vs Interrupt
So, to overcome the disadvantage of the polling method, we chose the Interrupt method.
ESP32 Interrupt
ESP32 module has a dual-core processor and each core consists of 32 interrupts. Basically interrupts are of two types:
Software Interrupts:
Fig 3 ESP32 software interrupt
Software interrupts are internal which occur in response to the execution of a software instruction. For example, a timer can be used to generate a software interrupt.
Hardware Interrupts:
Fig 4 ESP32 software interrupt
Hardware interrupts are the external interrupts that are caused by an external event. For example, an external push button connected to ESP32’s GPIO or a motion sensor will generate an interrupt (event) if a motion is detected.
ISR (Interrupt Service routine)
When an interrupt occurs during normal program execution, an ISR (interrupt service routine) or an interrupt handler is called into action. The normal program execution will be halted, and the interrupt will be executed based on the priority level of the interrupt.
Fig. 5 Interrupt service routing
Every interrupt has a fixed memory location where the address of the ISR is stored.
Interrupt Vector Table refers to a memory table or memory table that is used to store the location of an interrupt service routine.
Note: IRAM_ATTR attribute should be defined for interrupt handling. As per the ESP32 datasheet interrupt service routine should run inside the RAM. Because inside the RAM it is fast to execute a code than in flash memory and when an interrupt occurs all the other tasks will be blocked or halted till the time interrupt request is served.
Steps to execute an interrupt in ESP32
When an interrupt occurs, the microcontroller will go through the following steps:
- The microcontroller will halt the current task and will store the address of the next instruction (Program Counter or PC) on the stack (lower byte first).
- The microcontroller will execute the higher priority interrupt first and will block the lower priority interrupts.
- It jumps to the interrupt vector table memory location that contains the address of the interrupt service routine (ISR).
- The microcontroller reads the interrupt vector table and jumps to the address of the ISR. It begins executing the interrupt service subroutine.
- The microcontroller returns to the location where it was interrupted after executing the RETI instruction. First, it obtains the program counter (PC) address from the stack by inserting the stack's top bytes into the PC. The execution will then begin at that address.
Fig. 6 ESP32 Interrupt Program flow
ESP32 Interrupt Code
We are using Arduino IDE to compile the code and then upload into the ESP32 board.
If you are not familiar with the procedure of getting started with Arduino IDE and hoe to compile a code in Arduino IDE then follow our previous tutorial that is Introduction to ESP32 programming series.
// Set GPIOs for LED and Push button
const int led = 2;
const int button = 0;
// Timer: Auxiliary variables
#define timeSeconds 10
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
// Checks if button input was detected, sets LED HIGH and starts a timer
void IRAM_ATTR buttonInput() {
Serial.println("input is available !!!");
digitalWrite(led, HIGH);
startTimer = true;
lastTrigger = millis();
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
pinMode(button, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(button), buttonInput, RISING);
// Set LED to LOW
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop() {
now = millis();
// Turn off the LED after the number of seconds defined in the timeSeconds variable
if(startTimer && (now - lastTrigger > (timeSeconds*500))) {
digitalWrite(led, LOW);
startTimer = false;
}
}
Code for ESP32 Interrupts with Arduino IDE
As we have already discussed that the interrupt could be software generated (internal interrupt) or due to hardware (external interrupt). This tutorial we are using hardware or external interrupt for demonstration. You can also use software interrupts or both in a single code, as per your requirements.
Code Description for Hardware interrupt
- For the demonstration of hardware interrupt we are using a push button which is connected to the interrupt pin and a LED for the show output.
- First of all, let us assign two GPIOs, one is for push button (input) and another is LED. We are using the built-in LED that is GPIO_2 and a built-in push button (named as BOOT on ESP32 board) connected to GPIO_0.
Fig. 7
In this code, we are using timer to add delay instead of using delay() function.(I will also explain that why it is preferred to use timer in order to create delay instead of using delay() function after the code demonstration).
- Next, we are defining variables which are used to set the timer for adding delay after the interrupt is being detected.
- The variable now is defining the current time
- The variable lastTrigger is defining the time when the interrupt is detected.
- The variable startTimer is used to start the time when an interrupt is detected.
IRAM_ATTR
- It is required that the interrupt service routine should have the minimum possible execution time because it halts or blocks the normal program execution.
- The attribute IRAM_ATTR is used to run the code (interrupt code) inside the internal RAM when an interrupt occurs because RAM (random access memory) is much faster than flash memory.
- After the execution of the interrupt code or ISR the normal code will be stored or executed inside the flash memory.
Arduino Setup() Function
- Inside the setup() function we are initializing the serial communication with a baud rate of 115200.
- Set the push button GPIO pin a pulled up input pin.
- attachInterrupt() function is used to set the button pin (GPIO_0) as an interrupt pin and it will button input (interrupt) during the falling edge.
- A function called detachInterrupt() can be used if you no longer want to use a GPIO pin as an interrupt.
- Change the state of the LED when an interrupt is detected for
Arduino Loop() Function
Inside the loop function which is continuously running, the buttonInput function will be called every time when an interrupt occurs , which we have defined previously inside the setup() function.
- LED will turned off after the delay of 5sec once an interrupt is detected.
- The variable “now” will be updated every time with the current time.
- We can check the interrupt details on serial monitor as shown in the image below:
Fig 14 Serial monitor
Why it is preferred to use Timer instead of delay()?
Delay() function is a complete software process and it is mostly used because it is easier to implement delay using only software. On the other hand, when we switch to hardware delay or use a timer to add delay the process is a bit complicated to implement.
But, when we think of a practical perspective we prefer hardware delay over software delay. Because a software delay keeps the processor busy in a continuous loop and the processor need to keep all other tasks on halt.
On the other hand, if we use a timer to add delay the processor can complete some other task while the timer is playing its own part.
This concludes the tutorial. Hope you find it helpful. In our next tutorial, we will discuss the ESP32 Web Socket server.
ESP32 Web Server in Access Point (AP) Mode
Hello readers, hope you all are doing great. This is our 3rd tutorial in the ESP32 programming series. In our previous tutorial, we discussed the ESP32 Web server, where we created the ESP32 web server in STA mode.
ESP32 can be operated as an access point (AP) or a Wi-Fi station (STA mode). So, in this tutorial, we will create an ESP32 web server in access point (AP) mode. Here's the video demonstration of ESP32 WebServer in Access Point Mode:
As I mentioned above, in our 2nd tutorial, we already discussed the basics of the ESP32 web server. So, in this tutorial, we will only discuss how to create the ESP32 in access point mode.
For detailed information about the basics of the ESP32 web server and how client-server communication takes place, follow our previous tutorial (i.e., Create a Web Server with ESP32).
Where To Buy? |
---|
No. | Components | Distributor | Link To Buy |
1 | ESP32 | Amazon | Buy Now |
What happens in Access Point (AP) mode?
In Access Point Mode the ESP32 creates its own wireless Wi-Fi network in this mode, similar to the one provided by your existing router. In access point mode, we don't need to connect the ESP2 to a Wi-Fi network. In the Wi-Fi network it creates, the ESP32 Wi-Fi board can connect up to 5 devices.
Fig 1 ESP32 as an Access Point
So, in access point mode, nearby Wi-Fi devices such as mobile phones, laptops, or a secondary ESP32 module acting as a station can connect directly to the AP (ESP32 module) without the need for an external Wi-Fi router.
On the other hand, in Station mode, the ESP32 wi-fi module connects to your Wi-Fi network through a router. The router acts as a conduit for communication between the web client and the ESP32. The Wi-Fi router provides the IP address. This IP address can be used by web clients to connect to the Web server on a local network.
To know about how to set up/operate Arduino IDE for ESP32 compilation, follow our first tutorial i.e., Introduction to ESP32 programming series.
ESP32 Web Server in Access Point (AP) Mode
Here we are using an inbuilt example from Arduino IDE(ESP32). You can modify the example code as per your requirements or can write your own code.
- To find the Wi-Fi Access Point example in Arduino IDE :
- Click on File from the top menu bar.
- Place the mouse cursor on the example option from the list.
- Look for the WiFi option.
- There you will find the WiFiAccessPoint option, click on that and compile the program.
A screenshot is attached below to help you find the example code in Arduino IDE.
Fig 2 Wi-Fi access point example
The first task while writing the WiFi code is to add the required wifi header files or libraries in the code.
Here we are adding three libraries.
- WiFi.h: This header file contains all the functions related to Wi-Fi activities like enabling the Wi_Fi, connecting to a wi-fi network etc.
- WiFiClient.h: This header file is used to create a client that can connect with a specific IP address.
- WiFiAP.h: This header file is used to configure and manage ESP32’s wifi module in Access Point (AP) mode.
Fig 3: Libraries
Define the LED pin or a GPIO (for peripheral interface) which we going to control through web server. Here we are using the inbuilt LED which is internally connected with GPIO2
Give a name (SSID) to the ESP32 Access Point and set the password for security purpose ( if you wish to).
While creating a web server we also need to assign a port and usually port 80 is used for local web server.
Arduino Setup() function
Inside the setup function, the LED pin is initialized as an output one and then initialized the serial monitor with a baud rate of 115200.
The next task is to configure the ESP32 Wi-Fi module in access point mode. For that, here we are calling a function called WiFi.softAP. Where we are passing two parameters, ssid and password, respectively.
After configuring the AP mode, we need to fetch the IP address of the access point by calling the WiFi.softAPIP() function and printing it on the serial monitor.
Then, after fetching the IP address, we will start the server using the server. perform.
Arduino Loop() function
After configuring the Access Point mode and initializing the server, the server will next wait for the station or client connection, which can be a mobile phone, a laptop, or another ESP32 board configured in STA mode.
Once the connection is established between the access point and the client device, the access point will wait for the data input.
A string type variable called currentLine has been defined to hold the incoming data from the client.
If there is a byte to be read from the client, then it will be stored inside the char type variable c.
HTTP header always starts with a response code e.g.: HTTP/1.1 200 ok
An HTML page will be created on the client’s browser, from where the client device can control (ON/OFF) the LED.
Different URLs will be created to turn ON and OFF the LED depending upon the HTML input received from the client device i.e., H (to turn ON the LED) and L ( to turn OFF the LED).
Client.stop() function is responsible for closing the connection between Access Point and client or station device.
Note: If you need any guidance regarding how to upload or compile a code for the ESP32 module in Arduino IDE, follow our first tutorial on the ESP32 programming series.
Testing ESP32 web server with hardware in Access Point with Arduino IDE
Here we are going to control the ESP32’s inbuilt LED through an ESP32 web server (AP mode).
We will connect our station or client device through Wi-Fi to the ESP32 module, which (ESP32) is currently acting as an access point (AP).
To establish the connection go to your mobile phone’s Wi-Fi setting.
The Access Point is advertising itself with a pre-defined SSID so that the station devices or clients can find the AP device and can communicate with each other.
If you find a wi-fi device (AP) named ESP32_AP (or as per your SSID) connect to that after entering the assigned password.
Fig. Scanning for available Wi-Fi devices in mobile phone
Fig. Connected with ESP32 AP
As we are using the inbuilt LED, no external components are required.
After connecting to the access point, you can find the IP address of the AP device printed on the Serial Monitor. As shown in the image below:
Fig.: Serial Monitor
Enter the IP address in the browser. Now you can turn the LED ON or OFF using the web page as shown in the images below.
A web page with URL 192.168.4.1/H will be displayed on the browser when LED is turned ON
Fig.: URL when LED is turned ON
LED is blue color represents the inbuilt LED which is connected to GPIO_2.
Fig.: ESP32 LED ON
Another web page with URL 192.168.4.1/L will be created when the AP will receive the input to turn OFF the inbuilt LED. As shown in the image below:
Fig.: Web page displaying the LED off state.
This concludes today’s tutorial. We hope you find it helpful.
In our next tutorial, we will discuss another ESP32 feature that is BLE (Bluetooth low energy).
ESP32 Bluetooth Classic in Arduino IDE
Hello readers, I hope you all are doing well. Welcome to the Section 2 (ESP32 Features) of the ESP32 Programming Series. ESP32 is equipped with numerous built-in features and in each chapter of this Section 2, we will explore one of these ESP32 features in detail.
In the previous Section(Section 1: ESP32 IDEs), we installed different software IDEs to program ESP32 boards. Among these IDEs, we are going to use Arduino IDE for programming ESP32. So, I hope all of your tools are configured properly and you are ready to explore the built-in features of ESP32.
Today's the 1st Chapter of Section 2, and here we will discuss How to communicate with ESP32 Bluetooth Classic from a smartphone using Arduino IDE.
Here's the video tutorial for ESP32 Bluetooth Classic:
Where To Buy? |
---|
No. | Components | Distributor | Link To Buy |
1 | ESP32 | Amazon | Buy Now |
ESP32 Wireless Features
ESP32 is equipped with 3 wireless communication protocols:
- Bluetooth Classic
- Bluetooth Low Energy(BLE)
- Wi-Fi
Before going forward, let's first have a look at the basic features of BT Classic:
What is Bluetooth Classic?
Bluetooth is a short-range communication(wireless) technology, used in electronic devices(i.e. mobile phones, computers, LED, headphones, speakers etc.) for wireless communication over a short distance, approximately 15m. Bluetooth operates at a 2.4GHz ISM band. Bluetooth uses low-energy radio waves for data communication between Bluetooth-enabled devices.
Now, let's design the code to communicate over ESP32 Classic BT:
ESP32 Bluetooth Classic
We are using Arduino IDE for code compiling and uploading to the ESP32 module. I hope you have already installed ESP32 Boards in Arduino IDE. So, let's design a simple project to understand the working of ESP32 Bluetooth Classic:
Project Description
First of all, we will install a "Serial BluetoothTerminal" App from the Google Play Store to communicate with the ESP32 Classic BT.
In this project, we will first enable the ESP32 Classic Bluetooth, so that we can connect it to our smartphone. After a successful connection, we will send data from our smartphone(Serial Bluetooth Terminal App) to the ESP32 Serial Terminal and vice versa.
So, let's first understand the ESP32 BT Code and then will install the Serial Bluetooth App from the Google Play Store:
Code for ESP32 Classic BT
- Open Arduino IDE and navigate to "File > Examples > BluetoothSerial > SerialtoSerialBT".
- This code utilizes BluetoothSerial Library, it's pre-installed with Arduino IDE but if you can't find it in the Examples, you can manually Download Bluetooth Serial Library and add it from Library Manager in Arduino IDE.
- Upload this code to your ESP32 Microcontroller Board.
Here's the complete code:
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to enable it
#endif
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("TEP_ESP32_BT"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
Let's understand the code working:
How the Code Works
- First of all, we added the Classic Bluetooth Library named "BluetoothSerial", it has all the routines/functions required to enable Bluetooth and to communicate with other devices.
#include "BluetoothSerial.h"
- Next, we placed a check to ensure that Classic Bluetooth is configured properly and is discoverable to other devices:
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to enable it
#endif
- Next, we created a Bluetooth object "SerialBT" of class BluetoothSerial to initialize the Bluetooth stack and communicate serially with ESP32 Classic Bluetooth:
BluetoothSerial SerialBT;
Setup() Function
Initial Configurations of the project are added in the Setup() function. In our code:
- First, we initialized the Serial Port at a baud rate of 115200.
- Next, we initialized the SerialBT object and assigned a unique name "TEP_ES32_BT" to our Bluetooth device, this name will appear in the Bluetooth Search List.
- Finally, printed a welcome message on the Serial Monitor.
void setup() {
Serial.begin(115200);
SerialBT.begin("TEP_ESP32_BT"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
Loop() Function
The Loop() Function is an infinite loop and is equivalent to while(1) in normal C Language. In our code, we have placed two if checks:
- The first "IF Check" is monitoring the ESP32 Serial Terminal.
If we send any data from the Serial Terminal, this data will be transmitted to the SerialBT.
- The second "IF Check" is monitoring the SerialBT.
If we receive any data via ESP32 Classic Bluetooth, we will print it on the Serial Terminal.
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
So, I hope you have understood the working of this ESP32 Classic Bluetooth code. Now, let's install the Serial Bluetooth Terminal App from the Google Play Store:
Serial Bluetooth Terminal App
- Make sure your mobile's Bluetooth is enabled.
- Open the Google Play Store on your Smartphone and make a search for "Serial Bluetooth Terminal" and install it.
If we are connecting with the ESP32 BT for the first time, we need to pair it first.
- Open the Serial Bluetooth Terminal app and click on the "Devices" tab.
It will scan the list of all the available Bluetooth devices:
[Image]
- Now, Pair with the ESP32 Classic BT device named "TEP_ESP32_BT".
- Click on Pair.
We have successfully paired the ESP32 BT with the smartphone's Bluetooth.
ESP32 BT to Smartphone - Data Testing
- Open the Bluetooth Terminal App and click on the Connect Button at the top:
[Image]
- Open the Serial Monitor in the Arduino IDE and set the baud rate to 115200:
[Image]
- As shown in the below figure, when we send data from the Serial Monitor, it communicates over Classic Bluetooth and appears in the BT Terminal App.
- Similarly, when we send data from the BT Terminal App, it appears on the Serial Monitor of Arduino IDE.
So, that's how we can communicate between ESP32 and smartphones over Classic Bluetooth. In today's lecture, we communicated simple text data to understand the working principle. In the upcoming lectures, we will send complex data(i.e. commands & sensor values) via Classic Bluetooth.
Now, let's have a look at some theoretical knowledge about Classic Bluetooth:
BLE vs Bluetooth Classic
Fig: BLE vs Classic Bluetooth
- Bandwidth: Bluetooth can send a large amount of data, while BLE sends small chunks of data.
- Compatibility: Classic Bluetooth and BLE are not compatible with each other. A Bluetooth-supported device can’t communicate with BLE supported device.
But, a device having BT V4 (Bluetooth version 4) can discover both BLE and Classic Bluetooth devices.
- Power consumption: The classic Bluetooth consumes more power than BLE.
- Pairing: In Bluetooth classic pairing is necessary before sharing data between Bluetooth devices for security purposes. On the other hand, BLE technology doesn't ask for pairing before data transmission.
- Number of active devices: In traditional Bluetooth, a maximum of 7 slave devices can be connected with the master Bluetooth at a time. Though classic Bluetooth can connect with multiple nodes/slave devices at a time but it can exchange data with only a single node at a time.
Bluetooth Evolution
- The initial Bluetooth version (V1.0) was riddled with bugs and limitations.
- Bluetooth 2.0 was created as a result of various modifications and improvements to the basic version 1.0.
- Bluetooth 2.0's most notable feature was the enhanced data rate (EDR).
- Fast modulation technology and a data rate of up to 3Mbps are used in Enhanced Data Rate mode.
- Despite improvements in the basic version, Bluetooth 2.0 lacks a security feature.
- Bluetooth 2.1 added a security feature called "Pairing" as well as a faster data rate.
- Another updated version, Bluetooth 3.0, included a Wi-Fi feature, but it was rarely used, and when it was, the features were similar to the Bluetooth 2.1 version.
- Bluetooth 4.0 was the first version to include the Bluetooth low energy feature (BLE).
- The most recent Bluetooth version is v5.2, which supports both Classic Bluetooth and BLE and consists of the following features:
- EATT (enhanced attribute protocol)
- LE (Low Energy) power control feature (LEPCF)
- LE Audio
Bluetooth Network topology
- Classic Bluetooth forms a piconet. A piconet has a single master and multiple(max 7) slaves. Each piconet has its own hopping sequence.
Fig: Classic Bluetooth Network topology
Classic Bluetooth can operate on both point-to-point and point-to-multi-point network topology. In traditional Bluetooth, a maximum of 7 slave devices can be connected with the master Bluetooth at a time. Though, classic Bluetooth can connect with multiple nodes/slave devices at a time, but it can exchange data with only a single node at a time.
Bluetooth Clock
In classic Bluetooth, the piconets are not synchronized.
The clock is one of the most important aspects of Bluetooth. In a Bluetooth connection, the master device has a clock that is used to split the time on each physical channel. Clocks on all slaves in a connection are synchronized to the master clock.
Bluetooth clock synchronization is essential because the radios must agree on when to transmit. Because Bluetooth uses precise timeslots for transmissions with devices alternating, if the clocks are not synchronized, there may be issues with devices transmitting at the incorrect time.
Classic Bluetooth transmitting power
It is defined in multiple classes:
- Class 1: +20dBm maximum.
- Class 2: Up to +4dBm.
- Class 3: Up to +0dBm.
Classic Bluetooth Data transmission modes
Generally, there are two data transmission modes:
- Basic Rate (BR): BR is the first Bluetooth protocol which is implemented in Bluetooth v1.0. It uses one of the FSK (frequency shift keying) modulation techniques known as Gaussian frequency-shift keying (GFSK) and communicates data at the 2.4 GHz ISM band.
- Enhanced Data Rate (EDR): It's a Bluetooth specification that allows for a higher data rate or speed. It is not available in all Bluetooth versions, and its availability is dependent on the Bluetooth version and profile. EDR uses pi/4-DQPSK (differential quadrature phase-shift keying) and 8DPSK (differential phase-shift keying) modulation techniques with data rates of 2Mbps and 3Mbps respectively.
Bluetooth packet format
- When two devices communicate data over Classic Bluetooth, they use SPP (Serial Port Profile)
Fig. Bluetooth packet format
Enhanced data rate packet sends the Access code and header using the basic rate and this process uses GFSK (Gaussian Frequency Shift Keying). The guard gives the time to change the modulation to EDR modulation and then the synch word (64 bits), payload, and Trailer (4 bits) bits are sent using EDR (enhanced data rate) modulation.
So, that was all for today. In the next lecture, we will communicate between ESP32 and smartphones via BLE(Bluetooth Low Energy). Till then take care. Have a good day!!!
Smart Coffee Vending Machine using Arduino
Hello geeks, Welcome to our new project. As most readers have already seen the coffee vending machine or maybe you are drinking coffee while reading this article and if you are a tinker or a geek, it must have come to your mind how to make a coffee vending machine on your own. In today's tutorial, we are going to learn how to make a Smart Coffee Vending Machine using Arduino with Proteus Simulation for the same.
We can use this project for an engineering project’s showcase for electronics, electrical engineering students, and can be used in offices as well.
Coffee is the second most popular drink in the world and it is one of the oldest beverages of the world. According to Wikipedia, more than 2 billion cups of coffee are consumed every day in the whole world. As engineers or working professionals, we all know how coffee is very important for us. Having a good coffee makes our day better and refreshes the mood. Research shows coffee drinkers tend to live longer but when keeping it in moderate consumption. And making a good coffee is one of the most skillful jobs and time-consuming processes as we want our coffee in minutes. Now here our project comes to the picture, this smart coffee vending machine can make a good coffee in a couple of minutes. There are various flavors of coffee and our smart coffee vending machine can provide us with 4 different flavors which are the most commonly loved such as Latte, Cappuccino, Espresso, and Cafe Mocha. Here's the video demonstration of this project:
Where To Buy? |
---|
No. | Components | Distributor | Link To Buy |
1 | DC Motor | Amazon | Buy Now |
2 | LCD 20x4 | Amazon | Buy Now |
3 | Arduino Uno | Amazon | Buy Now |
Software to Install:
As we are going to design this project using Proteus Simulation, instead of using real components. As in the simulation, we can figure out the issue which may occur while working on real components and that can damage our components.
Proteus is the software for simulation and designing electronics circuits. As Proteus software has a big database of electronics components but still it does not have few modules in it like Arduino boards or LCD modules etc.
So we have to install the libraries, which we are going to use in this project:
- Arduino Library for Proteus: We have to add the Arduino boards to the Proteus components list.
- LCD Library for Proteus: We have to add the LCD module to Proteus Suite.
You can download this whole project for example Proteus Simulation and Arduino Code, by tapping the below button
Smart Coffee Vending Machine using Arduino
These are required components for Smart Coffee Vending Machine, as follows:
- 20X4 LCD display: It is used to display user-related messages like the state of the vending machine.
- Arduino UNO: It is used as the brain of our project. All operations and decision-making will be done using this microcontroller.
- DC motor: It is used for dispensing the ingredients of coffee and the mixer.
- Buttons: It is used as a user interaction option.
As a suggestion, whenever we make a project, it should be like a product, as it should be user friendly and interactive, so considering that we have used an LCD module to display the messages related to available coffee flavors and their individual prices so that users can easily select them using buttons and DC motors to pour the ingredients related to coffee like water, sugar, coffee powder, and milk, and a mixer for blending the coffee.
We have connected the LCD using an I2C GPIO expander as we have limited GPIO pins to connect other peripherals with Arduino UNO. I2C Gpio expander requires only two pins as we know that I2C uses SCL(Serial Clock) and SDA(Serial Data) pins for communication.
Components Needed:
- Arduino UNO
- LCD display
- 4 Buttons
- 8 Motors
- PCF8574
Components Details
Arduino UNO:
We can use any Arduino development board but here in this project, we have used an Arduino UNO board.
- Arduino UNO is one of the programmable, open-source microcontroller boards of the Arduino family.
- It contains an Atmel’s Microchip ATMega328 or ATMega328P microcontroller which has Harvard architecture 8-bit RISC processor core and 32 KB flash memory.
- Arduino UNO comprises 14 digital I/O pins out of which 6 are PWM pins as well and 6 Analog I/O pins with 10 bits resolution(0-1024).
- Arduino UNO has only 1 hardware UART pin(but we can use other pins also for UART communication using SoftwareSerial library in Arduino), 1 I2C, and 1 SPI.
PCF8574:
We have used this IC as a GPIO expander for our project as we have restrictions on the availability of GPIO pins in Arduino UNO.
- It is an 8-bit I/O, silicon-based CMOS GPIO expander.
- It can be used to write data on the pins and also can read data on those pins.
- It uses the I2C protocol for communication with the master device.
- As we know that I2C protocol uses the slave address to send or receive data from slaves, so for that it has 3 pins A0, A1, A2 for setting the slave address.
- Slave address for PCF8574 starts from 0x20 to 0x27. That means we can add only 8 PCF8574 IC directly to a master controller.
- The following image explains the logic of the slave address of PCF8574.
- It is used for connection for the LCD module with Arduino UNO in our project.
- If you want to learn more about IC PCF8574, you can refer to the datasheet using the following URL: PCF8574 Datasheet
LCD display
The LCD display is used to show the user-related messages in this project.
- LCD is a short form of Liquid Crystal Display which is basically built using Liquid Crystal technology.
- There are different sizes of LCDs available, in this project we have used 20X4 size.
- Here 20X4 signifies that it can display 80 ASCII characters at a time.
- There are 16 pins in the LCD. We will not use every pin of LCD in this project.
- It has 8 data pins, 1 Read/ Write select pin, 1 Register mode pin, 1 Enable pin, 2 pins for backlight, and 2 pins for power supply, 1 contrast control pin.
- There are mainly two types of register in the LCD: Command Register and Data Register.
- When we set the RS(Register Select) pin to logic High then it will select the data register mode and in logic Low, it will select the command register.
- To display the data on LCD we will set the RS pin to logic High.
Proteus Simulation of Smart Coffee Vending Machine :
Now, it's time to start designing the Proteus Simulation of our Smart Coffee Vending Machine.
- Most importantly, ensure that Proteus is installed on your PC and download all the required libraries for Proteus ahead.
- For this project, we are going to need libraries of Arduino and LCD modules.
- Make sure that you have read about how to use libraries in Proteus software.
Let’s create a new project, open the new project in Proteus and import all the required components which we are going to use, and place them within the working area.
- We need the following components, so select all of them from the Proteus component library.
Circuit Diagram and Working:
- Now let’s design our circuit, first place all the selected components in the Proteus Workplace, as shown in the image below:
- We will start connecting the LCD module and PCF8574, as we are using only 4-data pin-mode of LCD.
- After that, we will start the GPIO expander PCF8574 I2C connections, connect the SDA, SCL pins of PCF8574 to Arduino UNO’s SDA, SCL pins which are A4, A5 pins of the development board.
- As we know, we have to set the slave address of PCF8574 using A0, A1, A2 pins. And in this project we are going to use the slave address 0x20, therefore for that, we have to connect all pins to the ground. (As we have already seen in the above PCF8574 addressing image)
- In the next step, we are going to connect the buttons to Arduino digital pins D2, D3, D4, D5 as "Latte", "Cappuccino", "Espresso", "Cafe Mocha" flavors respectively and another terminal of the buttons is connected to ground. As we are going to use the buttons inactive low condition which means, when we press the button it will give us a logical LOW state.
- There may be a doubt in your mind why we have not used any PULL-UP resistors with buttons because we will handle that in our code. Arduino UNO comes with an internal PULL-UP resistor of 20-50 KOhms.
- Now connect the dc motors for each container, Water, Coffee, and Sugar container’s motors are connected with Arduino’s digital pins D10, D12, D11 respectively. Connect the coffee outlet motors for each type of Latte, Cappuccino, Espresso, Cafe Mocha with digital pins D6, D7, D8, D9 respectively. And at last, connect the mixer with the D13 pin.
- As we have mostly completed the wiring part, the first thing which we must make sure of before going to start our simulation is that all components should have adequate power supply and ground. And ground must be common in the whole circuit.
Now we hope you have understood the connections and you have already done it, so it is time to move to the coding part of our project.
Arduino Code for Smart Coffee Vending Machine
If you already know about the syntax and structure of Arduino sketch, it's a good thing, but if you have not been familiarized yet, no need to worry, we will explain it to you step-by-step.
Arduino coding language mostly follow the syntax and structure of C++ programming language, so if you are familiar with C++, then it would be like a cup of cake for you to understand the code but still if you don’t have any background knowledge, you don’t have to worry again, we have your back.
Arduino Coding follows a strict structure, it has mainly two sections. we have to write our code in those two functions.
As we are going to explain the Arduino code, it would be easy to understand if you have opened the code in the Arduino IDE already.
Declaration code:
- When we start our code, we will first include all the required libraries which we are going to use in this project.
- So our first step would be to download the required libraries if they are already not pre-installed in the Arduino IDE.
- Mainly we will use only two libraries, one for LCD display and the other for I2C communication.
- And I2C related functions come in the Wire library which will be pre-installed in Arduino ID, we don't have to install it explicitly.
- For the LCD module, we will use the Liquid Crystal_I2C library that we have to install.
- We can install libraries related to Arduino from the Arduino IDE by going to ‘Sketch > Include Library > Manage Library’. Now in the library manager, we can search for our required libraries. We can install the libraries using zip files also.
- >> Now, as we have installed all the required libraries. Let’s include them in our sketch.
- After that, we will define the pins which we are going to use in our project.
- We have to define them globally so that we can use them in all functions.
- You must be having a doubt why we have not defined pins for I2C.
- Because those pins are pre-defined in the Wire library, we can not assign any other pins for I2C communication.
- Now we will define and declare all the variables which are required in our project.
- There is an array for the price of a coffee with the size of 4, as we will only provide only 4 types of coffees and a string type variable for storing the name of flavors of coffee.
Arduino Setup() Function:
In this Arduino Setup() function, we will write a section of code that will only run once.
- So mostly we will write the declarations, define the type of pins and initialize the peripherals such as the LCD module.
- We want to take user input from the buttons therefore we will declare them as INPUT type.
- We have not connected PULL UP resistors in buttons as you have read above, we will handle that in the code therefore we have declared it as INPUT_PULLUP mode.
- We have declared motor pins as OUTPUT mode because we want to control the motors.
- After that we will initialize the LCD module then we will turn on the backlight of LCD, set the cursor to 0,0 index and using ‘lcd.print()’, we will print the welcome message on the LCD module.
- In the setCursor function, the first argument is used for X-Axis and the second argument is for Y-Axis.
- It will display the welcome message for 1 sec as we have given a delay for 1000 milliseconds after we clear the display.
Arduino Loop() Function:
Arduino Loop function runs after the the
‘void setup()’ function.
- In this section, we will write the code which is required to run in a continuous loop. So we will write our main application code here.
- So when the code reaches the void loop section, first we will display the flavor and the price of the coffee on LCD display as we want to show the user what type of coffee our vending machine makes and the price of those individually.
>> Now we will write the section for reading the user input from the buttons. As we have set that the condition will be true when the button will be logic LOW state.
>> Now when the user will press the button, the state of the button’s pin state will be changed to logic LOW state and then our ‘if condition’ will be true and code and our operation will enter in the ‘if condition’ section.
>> Here we will display to the user the current process stage of the coffee making. So we will clear the LCD display and then set the cursor to 0,0 index. After that we will display the message for collecting the ingredients.
- As we have not cleared the display, it will display the same message.
- After 1 second delay, we will start the water container motor for pouring the water for 2 seconds.
- Thereafter we will set the water’s container pin to LOW and Sugar’s container motor pin to HIGH for 2 seconds, similarly for the coffee’s container pin.
- Now we will start the motor for the selected flavor of coffee for 2 seconds and then stop it.
- As now our selected coffee is getting ready so we will display the message for the same.
- To display any new message, we have to clear our display with pre-occupied text.
- Now we will start the mixer motor for 10 seconds to mix all the poured ingredients.
>> Now our selected coffee is ready. So we will clear the LCD display and set the cursor, and will print the message regarding the prepared coffee with the price of it.
Results/Working:
- Below is the Flow diagram of coffee vending machine:
- Let’s understand the code with an example, we will go with the starting step.
- Power ON the device, the machine will display the welcome message that you can change from that code as per your choice.
- That message will be shown for 1 second thereafter it will clear the display.
- Now it will display the type of coffee as "Latte", "Cappuccino", "Espresso", "Cafe Mocha" and their respective prices.
- Let’s suppose, the user wants to have a Latte today, so he/she will press the button for the same, thereafter our coffee-making process will start.
- The first LCD display will show the message “Wait a Moment Collecting Ingredients” and it waits for 1 second.
- Thereafter it will start pouring the water for 2 seconds, then it will stop that motor.
- After that, it will start to pour sugar for 2 seconds, then stop that motor.
- At last, it will start to pour the coffee for 2 seconds, then stop that motor.
- It will start the motor of the selected type of coffee to dispense the coffee to the container and then it will wait for 1 second.
- Now LCD will display the message for coffee getting ready as "Wait a Moment Your’s Rich Latte is getting ready…” as the user has selected Latte that’s why it shows “Latte is getting ready… “.
- Now we will start the mixer to mix all the ingredients for 10 seconds.
- Again we will clear the LCD display to show the message for prepared coffee as “ Your's Rich Latte is ready. Please Collect it Your's Amount - 5/-”.
- Then it waits for 5 seconds and clears the display and again shows the price and the available types of coffee.
- As Proteus requires the hex file of the code to run the simulation.
- So for that, open the Arduino IDE and please verify your code before making a hex file by clicking on the ‘Verify’ button to remedy any errors.
- To get the hex file from the Arduino IDE click on “Sketch > Export Compiled Binary”.
- Your hex file will be generated successfully now put that hex file to the Arduino UNO board in the Proteus software.
- Everything is now in place, it's time to run the simulation and get a nice virtual coffee.
I hope you have understood the whole working of our smart vending machine project and enjoyed it as well. I think we have explained pretty much everything but still if you have any doubts or improvements please let us know in the comment section.
Thanks for giving your valuable time for reading it.
Introduction to Single Layer PCB
Hello friends, I hope everything's going well. Today, I am going to share the 13th chapter in the PCB learning series, where we will discuss the single-layer PCB in detail i.e. definition, construction, advantages, manufacturing, applications etc. So let’s try to absorb everything about the single-layer PCB:
Single-layer PCB overview:
- Just a quick recall, PCB stands for a printed circuit board having different electrical components connected with the help of pads and tracks of copper foil, incorporated on an insulating material(substrate).
- Single-layer PCBs have only one conductive layer of copper.
- The PCB board itself has a total of 3 layers in single-layer PCB other than the copper layer which are substrate, solder mask, and silkscreen.
- In the past, phenolic aldehyde was used as a substrate but nowadays glass fiber epoxy resin is used because of its flexibility with temperature variations.
Single-layer Definition
- Single-layer PCB refers to a printed circuit board that has only 1 layer of conductive pattern.
- Single-layer PCBs are simple, low-cost and can be designed at home.
- Different materials like glass fiber reinforced epoxy resin with copper foil and a paper mask having phenolic resin with copper foil are used in the manufacturing of single-layer PCB.
Pricing of Single Layer PCB
Now let's have a look at the pricing of Single Layer PCB. As Single Layer PCB is the simplest form of PCB, so it's quite low cost as compared to other PCB types. Let's take the example of JLCPCB Fabrication House, a well-renowned PCB manufacturing company, that offers competitive rates for PCB designing.
- We need to open JLCPCB official site and click on its Order Now page, as shown in the below figure:
- As you can see in the above figure, I have selected 1 for Layers, so I am ordering for Single Layer PCB.
- The size of the Single Layer PCB is 100x100mm and I have placed the order for 5 pcs of PCB.
- For this order, JLCPCB has given me a price of $2.00, so you can see it's quite cheap to design Single Layer PCB.
Construction of single layer
- In 1950, the first single-layer PCB was designed.
- The base material or substrate is made up of fiberglass and is compact in its sense.
- There is a copper layer that has conducting path for various competent on the boards above subtract. Needless to mention, different boards have different copper thicknesses consistent with your needs and demands, defined in ounces per sq. ft.
- On one hand, there is a solder mask layer on the top of the copper foil. The layer mainly protects the copper foil from insulating which avoids conduction in case direct contact happens with some conducting material.
- On the opposite hand, there's a silkscreen layer on the highest of all layers, which is especially in adding characters and symbols on the board, so it’s easy to have a far better understanding of the board.
Types of singles layer PCB
There are some types of single-layer PCB. We are going to explain them below concerning its manufacturing material.
- Single-layer rigid PCB
- Single-layer flexible PCB
- Single-layer rigid-flex PCB
- Single-layer high-frequency PCB
- Single-layer aluminum-backed PCB
1 Single-layer rigid PCB
- Single-layer rigid PCB is a type that is made up of a rigid material such as fiberglass.
- These PCBs are hard and prevent the circuit from bending and breaking.
- It's used in applications i.e. calculators, power supplies etc.
A single-layer rigid is shown in the figure below.
2. Single-layer flexible PCBs
- A single-layer flexible PCB has a flexible substrate like polyimide in its manufacturing.
- Single-layer flexible has so many advantages over single-layer rigid PCBs. But the cost is too high for its fabrication. A single-layer flexible PCB is shown below.
A single-layer flexible PCB
3. Single-layer high-frequency PCBs
- Circuits emitting a frequency in Gigahertz, single-layer high-frequency PCB is used.
- Polyphenylene oxide (PPO) or Teflon Material is used in single-layer high-frequency PCBs.
- If you are selecting High-frequency single-layer PCB, you should consider many aspects such as dielectric loss, thermal expansion, water absorption, etc.
- A single-layer high-frequency PCB is shown in the below figure
A single layer of high-frequency PCBs
4. Single-layer rigid-flex PCBs
- Single-layer rigid-flex PCB is a combination of both Rigid PCB and Flexible PCB.
- Single-layer rigid-flex PCBs have so many advantages over single-layer rigid and flexible PCBs such as it reduces the size and weight of the overall PCB.
- Single-layer rigid-flex is shown below figure.
A single layer rigid flexes PCBs
5. Single-layer aluminum-backed PCBs
- Single-layer Aluminium-backed PCB has an aluminum substrate.
- Aluminum-backed PCB is used with the thermal insulating material for the heat to dissipate by Aluminium.
- Single-layer aluminum-backed PCBs are shown below in Figure.
A single layer aluminum backed PCBs
Steps for the manufacturing process of PCB
- There are a lot of processes involved in the construction of a PCB.
- Almost 12-20 machines are used in the manufacturing of a simple single-layer PCB depending upon the demand of the customer and the requirement of the product.
- For ease of understanding, single layer PCB manufacturing process can be defined as
1. Cutting & Cleaning of PCB sheet:
- The circuit pattern is drawn on PCB using the photolithography technique in which warm iron is used to draw a pattern from photo paper to PCB.
- Photo paper is removed by washing PCB having photo paper on it.
- After drawing the pattern, check connecting nodes, jumpers, and docking points for additional components.
2. Etching with ferric chloride:
- prepare a solution of ferric chloride with water in a 1:3 ratio and dip board into it.
- The processing speed in this step is affected by the temperature of the solution and the thickness of the foil. You have to moderately heat the solution to speed up the process.
- Again clean the board with alcohol.
3. Drilling holes on the single layer PCB:
- now holes are drilled according to the requirement of the product. Clean the board again.
4. Soldering holes and lubricate sides of the board:
- at this stage, first of all, holes are soldered to make them able to make connections between components and layers.
- After soldering holes lubricating the sides of the board with a cover layer is done.
5. Testing of the final board:
- at this stage, the final prepared board is tested for whether it is ready or not.
6. Packaging:
- in the end, the final packaging is done and now the single layer PCB is ready to be delivered.
Common mistakes in single layer PCB manufacturing:
Following mistakes are made by designers during the manufacturing 9f the single-layer PCB.
1. incorrect conducting paths width:
- The maximum allowable width of the conducting path should be drawn to avoid voltage loss, overheating of the conductor, and low mechanical strength.
2. improper power circuit designs:
- When the width of the track is not made maximum then problems like output ripples, output voltage loss, and interference have to be faced. To avoid these problems track width should be maximum.
3. grounding problems:
- To avoid grounding problems, a separate insulating layer is used for wiring.
4. small gaps between copper:
- Gaps between copper conductors deposited on the board should not be so small, this can lead to the violation of the integrity of the board.
5. large no of holes on one plate:
- By increasing no of holes, no of conductive paths increases, and this, in turn, increases resistance.
Application for single-layer PCB
It is no doubt that single-layer PCBs are very simple. But single layer PCBs are used still in such a lot of complex devices. Some devices are listed below.
- Single-layer PCBs are used in digital cameras circuits.
- Single-layer PCBs used in coffee-making machine circuits.
- Single-layer PCBs are used in soiled state drives which are mostly used in the power industry.
- Single-layer PCBs are utilized in switching relays which are mostly utilized in the automotive and power industry.
- Single-layer PCB used in vending machine circuits.
- Single-layer PCBs used in digital calculators which are consist of only a single PCB.
- Single-layer PCB used in photocopy and printer machine circuits.
- Single-layer PCB is used in radio and stereo equipment circuits.
- Single-layer PCB is utilized in digital microwave timer circuits to modify on or off the oven timely.
- Single-layer PCB is used in led lighting circuits for making power light circuits.
- Single-layer PCB used in digital and analog power supplies circuits.
- Single-layer PCB used in surveillance machine circuits.
- Single-layer PCBs are used in sensors products circuits.
- Single-layer PCBs are used in packing machines to achieve the high targets of fast-packing and are mostly used in packing industries.
- Single-layer PCBs are used in timing circuits to switch on or off the machine timely.
Advantages of single-layer PCB
There are some advantages given below of single-layer PCB.
- The single-layer PCs is very easy to design and has a lower probability to make incorrect design because the single-layer PCBs is very simple.
- Its price is very less especially when it is ordered in bulk quantity as compared to the other types of PCBs.
- It is easy to understand for anyone because it is a very simple circuit
- Because its components are installed on only one side there for its a required lower jumper o compensate for the circuit.
- Its drilling, soldering, de-soldering, and components inserting process is very easy because single layer PCBs only consist of a single layer.
- Its design circuit required a very short time to make a simple design.
- There is less probability of short-circuiting and producing noise because its components are installed at some distance from each other.
- For fault tracing and repairing of this single layer PCB need less time.
- When we compare the single-layer PCBs to the other types of PCBs. It is more reliable and efficient.
- The installation of single-layer PCBs is very easy.
Disadvantages of single layer PCB:
- Single-layer PCBs have many advantages regarding cost, efficiency, and ease of installation but they still can not be used for any circuit because of their limitations. The limitations or disadvantages of using single layer PCB are discussed below:
The simplistic design and small space:
- Single-layer PCB has a very simple design and this simplistic design presents as the hurdle in complex devices that require a lot of components and connections.
- To mount a large no of components, large space is required but single layer PCBs don’t have enough space to mitigate this problem.
Slow speed and low operating capacity:
- As they have a limited no of components so their speed is slow, their power is also slow.
- Due to their low speed, they have low operating capacity.
Large size and high weight:
- To add components to the single-sided PCB you need to enhance PCB into its dimensions. As it is single-sided so that’s why we can not add layers. By enhancing PCB into its dimensions, the size of PCB.
- The enhanced size and large no of components ultimately enhance the weight of single-layer PCB.
Conclusion:
- At the end of it all, we can conclude that single-layer PCBs have unique advantages, benefits, and applications but as an end-user, you always have to choose which type of PCB you need.
- In modern technology advancements, single-layer PCBs are now in an underestimated situation but are still used.
- With a low budget and volumes of specific design single-layer PCB is the right choice when compared to the other types of PCB.
That’s all for today’s article. I hope you have enjoyed the article and made grip on the understanding points. However, if you still face any skepticism regarding single-layer PCB then please feel free to leave your questions in the comment section. I will provide an answer to these questions to the best of my knowledge and research skills. Also, provide us with your innovative feedbacks and suggestions you improve the quality of our work and provide you content according to your needs and expectations. Stay tuned! Thank you for reading this article.