The first law of thermodynamics is also known as the Conservation of energy Principle. I will explain what is energy principle is and the following are some important points of the Energy Principle:
The energy principle can be described as the following equation:
Ein-Eout=∆E
I will exemplify the energy equation through a simple example. For instance, the rock fell from the cliff and while falling from the cliff the rock gained speed and the speed doubled while coming down. The potential energy is converted into kinetic energy as the rock is falling from height. Here the air resistance is negligible here. All these factors confirm the conservation of energy principle.
One of the simple examples of the Conservation of Energy Principle in our daily life is the man who has a lot of energy i.e. the input. If he eats junk and gains weight and the energy will be stored in the form of fat also he exercises less and that is the output. But on the other, a man who eats less has less input and ultimately loses weight. So his input is small as compared to the output.
The conservation of energy principle states that
The change in energy content of a system is equal to the difference between the energy input and output.
If the mass, energy or other quantity enters the system from outside to the system and exists in the system. But if the quantity moves within the system then it is not considered to be a transferred quantity. So it is important to understand the boundaries of the system.
In a closed system, the energy can change to heat transfer and work transfer. In this case, the conservation of energy of the close system equation will be expressed as follows:
Qnet in+Wnet in=dEsysdt
The value of the net heat transfer rate is as follows:
Qnet in=Qin-Qout
The value of net power output is as follows:
Wnet in=W in-Wout
Here dEsysdt is the rate of change of the total energy content of the system.
In the case of a compressible system, the equation of total energy consists f internal kinetic and potential energies and the equation is as follows:
e=u+K.E+P.E
e=u+V22+gz
The energy transfer by heat is one of the important topics of the energy equation. The following are some of the important key points related to the energy transfer by heat:
The heat is in the form of a latent form of internal energy.
Heat transfer is defined as the movement of thermal energy by means of nature and the temperature is decreased in this case. So the transfer of thermal energy from one system to another due to temperature variations is known as the transfer of heat.
In the case of heat transfer, the heat is always transferred from a body of higher temperature to a body of lower temperature. When both temperatures maintain equal temperature then the process of transfer stops. In the case of bodies having equal temperature, there is no transferring of heat.
Adiabatic process is the one in which there is no transfer of heat. The system is said to be in adiabatic if the system is insulted and if the system and the surroundings are at the same temperature.
The adiabatic process is confused with the isothermal process. But there is no transfer of heat but in the adiabatic process, the temperature can be changed by the work transfer.
The energy transfer by work is also an important part of the energy equation. The following are some of the important key points related to energy transfer by work:
The energy interacts and results in the work.
The time rate of doing work is called the power and the power is denoted by the W.
The energy is increased when the work-consuming devices transfer energy to the fluid. A simple example of transferring energy is an electric fan. This moves the electric energy is converted into mechanical energy and this mechanical energy operates the motor of the fan and that motor starts the blades and the fan starts. But here we can say that energy is transferred and this energy transfer has no relation to the temperature.
The system has various kinds of transferring of work and the total work equation is as follows:
Wtotal=Wshaft+Wpressure+Wviscous+Wother
The shaft work is also one of the important part of energy equation. So following are some of the important key points related to the shaft work:
Machines such as turbines, pump, fans or compressors all have shaft and the work protrudes through the control surface by the shaft is known as shaft work.
The equation of the shaft work is as follows:
Wshaft=ωTshaft
Wshaft=2πnTshaft
Here omega is the angular speed of the shaft and n is the number of revolutions of the shaft per unit time.
The work done by the pressure forces is also one of the important topic that comes under the energy equation. So following are some important key points related to the work done by pressure forces:
In the case of work done by pressure forces, let us consider a gas that is compressed in a piston cylinder.
The diagram of gas compression in a piston cylinder is as follows:
The piston is moved at some distance and that differential distance is ds. The differential distance is under the effect of pressure forces PA where A is the cross sectional area of the piston whereas P is the pressure forces. Here the work is being done.
The equation for work done on the system is as follows:
Wpressure= δWboundry=PAVpiston
Here the value of Vpistonis as follows:
Vpiston=dsdt
We will start the derivation with a little theoretical background.
Let us consider a system that has arbitrary shape and the diagram is as follows:
The system moves with the effect of pressure. The pressure here acts in an inward direction and normal the surface. The equation for the time rate at which work is done by pressure on the differential part of the system is as follows:
Wpressure=-PdAVn
Wpressure=-PdA(V.n)
The equation for the normal component is as follows:
Vn=Vcos
Vn=V.n
So now I will show you the equation for the total rate of work done by the pressure forces:
Wpressure net in=-∫A P (V.n)=-∫APρ(V.n)dA
Now there is an equation that shows the general form of energy equation that is applied to the fixed, moving and deforming control volumes as follows:
Qnet in+Wshaft, net in+Wpressure, net in=ddt∫cvedV+∫cse(Vr.n)dA
So is the energy equation for the fixed, moving and deformed control volumes.
The statement of Bernoulli’s Equation is as follows:
In fluid dynamics, Bernoulli’s Equation states about an increase in speed of fluid that occur simultaneously with the decrease in static pressure or decrease in fluid’s potential energy.
After reading the statement, you might have little idea what Bernoulli’s equation is about. Don’t worry. Here I am to explain that to you extensively.
Some of the important critical points related to Bernoulli’s equation are as follows:
Bernoulli’s equation is the relation between the pressure, velocity and potential energy.
This equation is only applicable for steady, incompressible flows. In this equation, all the frictional effects are neglected.
We will derive Bernoulli’s equation with the help of the Conservation of Linear Momentum Principle.
There are certain restrictions in the application of Bernoulli’s Equation. For instance, we cannot apply the equation to every fluid. Obviously, there should be a certain amount of viscosity in the fluid (some fluid has less value of viscosity) and the equation cannot be implemented in every flow.
So we conclude our statement by saying that Bernoulli’s equation is only applicable to inviscid regions of the flow.
So following is the diagram that shows the regions where Bernoulli’s Equation is applicable and where it is not.
The Bernoulli’s Equation id helpful in regions outside the boundary layers where the fluid motion is governed by the combined effect of gravitational and pressure forces.
The path and motion of the particle are described by the velocity vector. In the case of steady flow, the particle passes through streamlines.
The acceleration of the fluid particle is one of the most important topics while describing Bernoulli’s equation. So following are some important key points related to the acceleration of fluid particles:
While describing the motion and path of fluid particles, it is important to describe the distance along the streamline with the radius of curvature of the streamline.
Obviously when we are explaining the distance of a fluid particle then velocity can also be related to it. But here is a condition the velocity may vary along the streamline.
In the case of defining the acceleration of fluid particles of two-dimensional flow, the acceleration is divided into two parts. One is the normal acceleration an and one is the streamwise acceleration as respectively.
The normal acceleration is due to the change in direction whereas the streamwise acceleration is due to the change in speed.
There is a condition that when the particles are moving in a straight path the normal acceleration is zero since there is no change in direction and the particle is moving in a straight line so the radius of curvature is infinity.
Bernoulli’s Equation is the result of force balance along the streamline.
We might wonder that in steady flow the acceleration is zero. But here is an interesting fact the acceleration is not zero. We define acceleration as the rate of change of velocity in time but there is no change in time. In order to exemplify this point garden hose is one of the perfect examples to describe. There is a steady flow in the garden hose and steady means no change with time but the quantity may change. When the water accelerates along the nozzle then there is a change in velocity at the inlet and outlet but at a specific point it remains constant.
So mathematically representation of velocity is as follows:
dV= ∂V∂sds+∂V∂tdt and dVdt=∂V∂sdsdt+∂V∂t
In the case of steady flow,
∂V∂t=0
And
V=V(s)
The equation of acceleration will be as follows:
as=dVdt
as=∂V∂sdsdt
as=∂V∂sV
as=VdVds
Before starting the derivation of Bernoulli’s Equation let us overview the statement of Bernoulli’s Equation and that is as follows:
The sum of kinetic, potential and flow energies of a fluid particle is constant along the streamline during the steady flow neglecting the frictional and compressibility effects.
Let us start the derivation of Bernoulli’s Equation with the theoretical part:
First of all, consider the fluid particle in a flow field with steady flow. The fluid particle is shown in the diagram as follows:
According to Newton’s Law states as
The conservation of linear momentum relation in fluid mechanics.
The fluid particle moving in the s direction along the streamlines gives the following force according to Newton’s Law:
∑Fs=mas
Here all the frictional forces and effects are neglected. The forces that are acting in the s directions are pressure forces and they are acting from both sides along with the weight of the particle.
The equations will now become:
PdA-P+dPdA-Wsin =mVdVds (1)
Here is the angle between the normal of streamline and the vertical z-axis. The value of mass is m=ρV and it will become:
m=ρdAds
The value of the weight of the fluid particle will be W=mg and it will become:
W=ρ g dA ds
The value of theta will become:
sin =dzds
We will substitute all the values in equation 1 and we will get:
-dPdA-ρg dA ds dzds= ρ dA ds VdVds
Now the next step is to cancel out the dA and we will get the following equation:
-dP-ρg dz=ρV dV
In the next step we will substitute the value of V as
VdV=12dV2
We will substitute the value in the above equation and then divide each term by density and will get the following result:
dP+12d(V2)+gdz=0
After the integration the equation for the steady flow along the streamline will be as follows:
∫dP+V22+gz=constant
In the case of incompressible and steady flow the equation will be as follows:
P+V22+gz=constant
The above equation is used in inviscid flow regions. So now Bernoulli’s equation will be as follows:
P1+V122+gz1=P2+V222+gz2
This is the final equation of Bernoulli and that is derived by the conservation of momentum that is moving along the streamline.
Bernoulli’s Equation is also viewed as the Conservation of Mechanical Energy Principle.
This principle also states that no mechanical and thermal energy is converted but they are conserved separately.
Bernoulli’s equation is implemented to an incompressible, steady flow as we have discussed earlier.
As we have also discussed that whenever the force is applied to a system the energy is transferred so we can relate that with Bernoulli’s equation which statements will; be as follows:
The work done by the pressure and the gravitational forces that are increased is equal to the increase in the kinetic energy of fluid particles.
In steady and incompressible flows, the force balance in the direction of n across the streamline is as follows:
P+∫V2Rdn +gz= constant
We have a huge discussion on the incompressible and steady flows and their derivation equation now Bernoulli’s equations in terms of compressible and unsteady flows are as follows:
∫dP+∫∂V∂tds+V22+gz=constant
Some of the important key points related to the topics are as follows:
The statement of Bernoulli’s equations says that the sum of the fluid particle,s' kinetic, potential and flow energy is constant. So the kinetic and the potential energy during the flow is easily converted to the flow energy , which changes the pressure. So density is multiplied with Bernoulli’s equation and we got the following answer.
P+ρV22+ρgz=constant
this equation has some essential terms, and one by one, I will explain each term to you.
Static Pressure
At the start of the equation, there is pressure P, and that pressure is called Static Pressure. This static pressure does not incorporate dynamic effects. Static pressure is the accurate presentation of thermodynamics pressure, and while solving the equation, we use thermodynamics tables for using the values.
Dynamics Pressure
The second term, i.e. V22, is called the dynamics pressure, and when the fluid is in motion, and there is an increase in pressure, this pressure stops isentropically.
Hydrostatic Pressure
The third term of the equation is called hydrostatic pressure, and basically, this is not the pressure because of its dependence on elevation effects. This means that this pressure accounts for the weight of fluids.
so the sum of all these pressures is called total pressure, whereas the sum of static and dynamic pressure is known as stagnation pressure, and its equation is as follows:
Pstag=P+ρV22
There are certain limitations applied while dealing with Bernoulli’s Equation. The list of constraints is as follows:
The first and foremost important limitation is that as we have derived the whole derivation of Bernoulli’s equation, you might have noticed the word steady and incompressible. So yes, Bernoulli’s equation is applicable in stable flows only. I have also mentioned the equation for unsteady flows also but there Bernoulli is not applicable.
You might have noticed one of the important factors that during the steady and incompressible flows, all the frictional and compressible effects are neglected. So yes, that is the second limitation of Bernoulli’s equation. Frictional effects in the case of short flows and large cross-sectional areas. And if the velocity is low, then that is a plus point. A slight disruption in the streamlined flow can make Bernoulli’s equation inapplicable to that flow. So much concentration and care are required for a steady and incompressible flow.
We have derived Bernoulli’s Equation from a particle moving along a streamline, so any flow in machines such as turbine fan or impeller without streamlined flow does not apply Bernoulli’s equations in flow sections. So energy equations are widely used for calculating the shaft input or output of these machines. But Bernoulli’s equation can still apply to flow sections before or past a machine.
The following restriction of Bernoulli’s equation is that Bernoulli’s equation states that density is constant, which means that the flow is incompressible. The incompressibility is applied in the case of liquids as well as gases. The Mach number should be less than 0.3 in that case. The compressibility and the density variations in the case of gases are negligible because of the low relative velocity.
Another limitation says that the increase in temperature decreases the density and vice versa. So Bernoulli’s equation is not applicable in the case where the flow section has a lot of changes in temperature (cooling and heating).
The last limitation of Bernoulli’s equation is that it is applicable in the flow streams only. As discussed above in the derivation, the final equation is applicable in the steady incompressible and flow streamline. So when the flow is disrupted or is irrotational there is no voracity in the flow field, the value of constant is the same for all the streamlines and here Bernoulli’s equation becomes applicable. The main thing is whether the flow is irrotational we don’t need to worry about the application of Bernoulli’s equation.
Bernoulli’s equations are one of the most important fields and have numerous numbers of uses in our daily life. Here I will share some of the important applications of Bernoulli’s Equation. So let us start.
One of the important applications of the Bernoulli’s Equation is a spray gun and another name is atomizer. The procedure is that we press the piston and the air is rushed from a tube that is in horizontal direction. The following diagram shows the atomizer.
So at point B, the air rushes out and the pressure is decreased from p2 to p1. Because of the pressure decrease, the liquid is raised in vertical tube A. So the high air pressure collides with the liquid rise tube and results in fine sprays. This fine spray is used in many different sprays, Bunsen burners, perfumes and many more sprays.
Who does not like travelling on aeroplanes? But do you know how aeroplanes take off and land? let me explain to you the theory of rising aeroplanes. Actually, the aeroplane rise as a result of the lift force that is acting on the wings. The lift is a result of an object placed asymmetrically and that is moving through the fluid. Bernoulli’s equation says that the increase or decrease in the velocity affects the pressure and causes variations in it. So pressure variations create an upwards force and that upward force is shown in the following diagram.
This is also one of the well-known examples of Bernoulli’s equation. A Venturimeter is used for the measurement of flow speeds in the pipe that is not uniform. As we know that Bernoulli’s equation is applied in narrow shallow and wide pipes where the height is the same and the area at the inlet is greater than the outlet and the velocity at the outlet is greater than the inlet velocity and at last, the pressure at the outlet is greater than the pressure at the inlet. so there is a collectively force applied when the fluid enters the throat and the force slows down on leaving. The following diagram shows the working.
Now we will move towards our last topic of this article that is about the Energy Equation. This topic is also one of the fundamental topics of fluid dynamics. So without wasting any time let us start the topic and see the equations of it.
In this article, I will cover one of the essential topics of fluid mechanics as the title shows three crucial topics—the first concerns the conservation of mass and how it plays a critical role in our daily life. The next one involves the conservation of kinetic and potential energy and is all about the flow energy of a fluid stream. The Bernoulli equation is all about considering the energies, handling them of fluid, and neglecting the viscous forces. The last topic is energy equations, which is about the conservation of energy principle. As we know that while dealing with energy in fluid mechanics, the mechanical energy can be separated from the thermal energy and end, considering it an energy loss.
So without wasting time, let us start the article with the mass.
I will start with the laws of conservation. As you have heard about many laws, while discussing things related to mass, it is essential to examine the conservation laws. So let us discuss conservation laws one by one.
The definition of the law of conservation of mass is as follows:
In any close or isolated system, matter cannot be created nor destroyed but can be changed and conserved.
Some of the essential key points related to the law of conservation of mass are as follows:
In the system, the mass remains constant throughout, and the according to the equation it says:
msys=constant
dmsysdt = 0
Here, dmsysdt is the mass change r within the system boundaries.
so, in the case of the control volume, the conservation of mass in terms of rate form is presented as follows:
min-mout=dmcvdt
here, the min is the total rate of control volume;l volume, and similarly, mout is the mass flow rate out of control volume
Also, dmcvdt is the mass change rate within the control volume.
You might have heard that the conservation of mass is interrelated with the continuity equation. So the conservation of mass defined in terms of the differential control volume is called Continuity Equation.
The definition of the law of conservation of momentum is as follows:
The Law of Conservation of Momentum states that the momentum of an isolated system is constant.
Some of the essential key points related to the law of conservation of momentum are as follows:
In fluid dynamics, the conservation of momentum is interrelated to Newton’s Law of motion. In solid mechanics, Newton’s Laws of motion are implemented.
As we know, that momentum formula is about the product of mass and velocity.
Newton’s second law of motion says:
The rate of change of momentum of the body is equal to net forces acting on it.
The statement of conservation of energy is as follows:
The net energy transfers to or from the system during a process be equal to the change in energy content of the system.
Some of the essential key points related to the conservation of energy are as follows:
As we know that energy cannot be created nor destroyed, but it can be transformed from one state to another. So the statement of Conservation of energy is similar as it says that the energy transferred to the system is equal to the change in the system's content. So it means that no energy is destroyed it is transformed into another form.
The energy balance equation of conservation of energy will be:
Ein-Eout=dEcvdt
Here, Ein and Eout are the total energy in and out of the control volume.
dEcvdt is the rate of change energy within the control volume.
It is the first part of the article, and while discussing this topic, we should know that it is one of the most fundamental principles in nature. At the start of the article, I have given you a brief introduction about the conservation of mass, the statement, and the energy balance equation.
Now I will discuss those key points not discussed before in detail. So their explanation is as follows:
The mass has a much similar property as the energy. One of the significant statements is that it cannot be created or destroyed. But mass can be converted to energy and vice versa with the help of the following statement and i.e.
E=mc2
Yes, you guessed it right. This is Einstein Equation. Where c is the speed of light, and the value is c=2.9979108m/s.
The equation helps us detect the change in mass whenever there is a change in energy.
As the statement of the conservation of mass shows that the system’s mass remains constant but in the case of a closed system. While discussing the control volumes, there might be some changes. The significant change will be that mass can cross boundaries.
These two words are well known in fluid mechanics, so readers should know these two when discussing the conservation of mass. So the definition of mass flow rate is as follows:
The mass flow through any cross-section per unit time is called mass flow rate.
Some of the essential key points related to the mass flow rate are as follows:
The fluid passing through any cross-sectional area has a flow rate. Let us suppose it passes through some small area; then, the differential mass flow rate will be:dAc.
Then, the equation will be like this:
m=ρVndAc
Here, is used for quantities such as heat, work, and mass transfer, whereas d ( differential quantity) is used for the properties.
Let us have the flow of fluid passing through some annulus with inner radius as r1 and outer radius r2 as then the equation will be:
12dAc=Ac2-Ac1=π(r22-r12)
Also, we know that the total mass flow rate is as follows:
12m=mtotal
After the integration, the mass flow rate equation will be as follows:
m=∫Ac δm = ∫Ac ρVndAc
The equation is very informative but is not used in daily life because of the integration. So the flow rates are values taken as average. The importance of density and velocity varies accordingly to the size of the pipe. Due to non-slip conditions, the value of velocity varies
So the equation of average velocity is as follows
Vavg=1Ac∫AcVndAc
In the case of compressible and incompressible flows when the density is uniform throughout the cross-sectional area, then the equation will be:
m=ρVavgAc
The definition of volume flow rate is as follows:
The volume of fluid flowing through any cross-section per unit of time is known as the volume flow rate.
Some of the important critical points related to the volume flow rate are as follows:
The equation of volume flow rate is as follows:
V=∫AcVndAc
V=VavgAc
V=VAc
One of the essential points that should be kept while dealing with the volume flow rate is that it should not be confused with the symbol Q as it also presents the flow rate.
There is a relation between the mass and volume flow rate, and that relation is explained by the equation.
m=ρV=Vv
The statement of conservation of mass principle is as follows:
The newt mass transfer to or from a control volume during the interval of time is equal to the net change in total mass within the boundaries of the control volume.
The theoretical equation is as follows:
(Total mass entering the CV during ∆t) – (Total mass leaving CV during ∆t)
=
(Net change in mass within the Control Volume during ∆t)
The mathematical equation will be as follows:
min-mout=∆mcv
This equation can also be expressed in terms of rate form:
min-mout=dmcvdt
Here one of the essential vita points that must be kept in mind is that the conservation of mass principle is performed within the control volume boundaries.
The theory and the mathematical equations about the conservation of mass principle are as follows:
First of all, we will consider the control volume of irregular shape as shown in the diagram below:
So the mass of differential volume that is in the control volume will be:
dm=ρdV
The equation of total mass within the control volume will be:
mcv=∫cvdV
Now I will show you the equation of the rate of change of mass within the boundary of a control volume:
dmcvdt=ddt∫cvρdV
The conservation of mass principle has a special case in which no mass can cross the boundary. We can conclude that control volume restrictions are much similar to the closed system. The equation of conservation of mass principle, in this case, will be as follows:
dmcvdt=0
Now we will further assume that the mass is flowing from the differential area of the control volume. Here the unit vector will be n of differential area (dA). V will be the flow velocity and this whole theory is presented in the diagram that is mentioned above.
There is an angle at a point where the velocity can intersect the differential area.
The mass flow rate here is proportional to the normal component of velocity as:
Vn=Vcos
here there are some values of theta that are applied to the above-mentioned equation. Such as =0 when the outflow is maximum and the flow is normal to the differential area. The value of =90° when the flow is tangent to the differential area and the outflow is minimal to zero. The value of =180 when inflow is maximum and the flow and differential area is opposite to each other also the flow is normal to the differential area.
So the equation of the normal component of velocity will be as follows:
Vn=Vcos =V.n
As this is the important principle of fluid mechanics, it comprises equation many. Now there is the equation of differential mass flow rate in which the mass flow rate passing through the differential area is directly proportional to the fluid density and it is normal to the flow area:
m=ρVndA=ρVcos dA=ρV.ndA
Now there is an equation of net mass flow rate and it is an overall equation of control volume in which the flow rate moves in and out through the control surface. So the equation is as follows:
mnet=∫csm=∫csVndA=∫csρ(V.n)dA
Here are some important values of theta as we know that V.n = Vcos so the value will be <90° in the case of outflow and it will be >90° in the case of inflow. So whenever the value of the net mass flow rate is positive, it shows that it is an outflow; whenever the value is negative, it shows that the net flow is inflow.
Now there was an equation at the start which was min-mout=dmcvdt
We will rearrange it and will present it as an equation of general conservation of mass equation and it is as follows:
ddt∫cvρdV+∫csρ(V.n)dA=0
For your convenience I will explain the above equation to you. The above equation says that the rate of change of mass within the boundary of control volume along with the net mass flow rate through the control surface is said to be equal to zero.
We can also derive the equation with the help of Reynold’s Transport Theorem.
Now I will show you our second last equation and this is associated with the above equation. What we will do is we will spill the above equation into two main parts.
One part comprises the outgoing flow streams and the value will be positive. The second part comprises the incoming streams and the value will be negative. So the equation will be as follows:
ddt∫cvρdV+t∫AVndA-in∫AVndA = 0
Here A is the area of outlet and inlet and the summation value shows all the collective values of inlet and outlet.
Now moving toward, the last equation will be the end of this topic. In the last equation I will show you how mass flow rate can be shown in some different equations:
ddt∫cvρdV=inm -outm
or
dmcvdt=inm -outm
This topic also comes under the conservation of mass of principle. So the essential key points are as follows:
Whenever there is a steady flow, the total mass within the boundary of the control volume remains constant.
But when we have studied the conservation of mass principle it says that the mass that is entering the control volume should be equal to the mass leaving it.
Toto explain further I will unquote an example that says that while watering our flowers with the help of a garden hose. The water passing through the nozzle of the garden hose is moving in a steady motion. So the water entering the nozzle per unit time equals the water leaving per unit time.
While dealing with the steady flow, the amount of mass is not considered rather the mass flow per unit time is always considered. And that amount of mass flowing per unit time is the mass flow rate.
In the case of steady flows, the flow's inlet and outlet are always considered equal. Such as shown in the diagram.
inm =outm
There are numerous mechanical devices in which a single stream with one outlet and inlet are used. Examples are turbines, diffusers and pumps. So to have an equation for them to calculate the steady flow the equation will be as follows:
m1=m2 1V1A1=2V2A2
Here 1present the inlet of flow and 2 presents the outlet of flow.
Now here comes the last topic of conservation of mass principle in this topic we observe a special case study. So without wasting any time let’s have a look at the important key points:
In the case of liquids, when the fluid is compressible the conservation of mass has a defined line.
The equation for the steady and the incompressible flow will be as follows:
in =out
Here the density is cancelled from the side. So in the case of single stream, steady and incompressible flow, the equation will be as follows:
1=2=V1A1=V2A2
We have a detailed explanation of the conservation of mass but after this equation, you might have questions in your mind about the conservation of volume. So for your information, there is no such thing exists as the conservation of volume.
In the case of steady flow, the volume flow rate at the inlet and the outlets are different and may vary from device to device.
To clarify this point let us take an example of an air compressor. The volume flow rate at the outlet is less as compared to the inlet. As the mass flow rate at the inlet and outlet is constant. The reason for this is that there is a high density of air at the exit of the compressor.
In the case of steady flow, the mass flow rate along with the volume flow rate is the same or constant throughout the whole process.
so that is a whole detailed discussion about the first part of this article which covers almost every domain. So now I will start the second part of the article, which is about the Bernoulli Equation. Without wasting any time let us start.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Raspberry Pi 4 | Amazon | Buy Now |
Welcome to the following tutorial in our raspberry pi four programming tutorial. In the previous tutorial, we learned how to build a raspberry pi four website monitoring tool. We say how beautiful soap is applied in browser automation tasks such as tracking website activities. But in this guide will discover how to utilize our Raspberry Pi 4 as a wifi repeater. If you want a lag-free wireless network, a wifi Wireless Adapter is exactly what you need. You may want to set up a wifi repeater if your signal is weak in certain rooms of your home or if you have entirely lost service in one or more rooms that are too small to accommodate your current network setup. If you want to increase the range of the wifi connection without breaking the bank or wasting a lot of energy, consider getting a Raspberry Wifi Extender. Compared to a wireless access point, a wifi extender has significant differences.
The critical distinction is that instead of using an Ethernet cable, it uses a WiFi adapter to connect to the internet. Two WiFi adapters are required to finish this tutorial, and one of them must be able to function as an access point. You might expect a significant slowdown in your network speed when using the WiFi repeater. That's because devices can't join your network until your initial WiFi communication has gone through and been rebroadcast from your Pi 4.
Our Virtual private network Access Point tutorial, which explains how to set up a VPN connection, complements this one nicely and can be found immediately. It will demonstrate how to install an OpenVPN client and route all network traffic through that app. You'll need two Wireless dongles to finish this guide, at least one of which should be able to function as an AP. Those components are listed below.
Raspberry Pi
Power Supply
WiFi x 2
A standard wireless range extender may pick up the signal from your existing wireless router, boost its signal strength using several channels, and broadcast it over a larger region in your house or workplace. Say, for instance, you have your WiFi router put on the ground floor of your building, and you are studying on the 2nd floor of your room. You're trying to link up your computer or mobile device, but obstacles keep popping up. A WiFi Extender, which, once activated, enables wireless connectivity to the router, is an ideal solution for resolving this issue.
Because it doubles as a Domain Name System (DNS) and a Dynamic Host Configuration Protocol server, the dnsmasq package is essential to setting up our RPi Wireless Extender and doing the bulk of the legwork for this guide. Another program we'll need to use is hosted, enabling us to use one of your wifi gadgets as an AP. Don't forget that you'll need access to a working wireless router and an Ethernet device to bridge your wireless connection; follow this guide. For starters, we'll update the rPi by typing the two commands below into the terminal.
sudo apt update
sudo apt upgrade
Installing dnsmasq and hostapd, two necessary packages, is now a simple matter of running the appropriate commands.
sudo apt install dnsmasq
sudo apt install hostapd
It's important to prepare the wlan0 network connection before moving forward. It is possible to skip to Step 5 if you have previously established a wireless network connection. Alternatively, you can access the WPA-supplicant.conf script by issuing the command below on your RPi:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Incorporate the following into this file, switching out "ssid" for the network's id and "psk" for the passcode.
network={
ssid="networkname"
psk="networkpassword"
}
Save the script by clicking Control + X, followed by Y, then finally, ENTER key once you have provided your network username and password. Assuming you successfully installed all the packages and connected to the wifi network, the next step would be to configure dhcpcd to provide our RPi with a permanent IP address. This can be accomplished by adding the command below to the dhcpcd.conf script:
sudo nano /etc/dhcpcd.conf
The lines below, added to the file's end, will configure the wlan1 connection as desired. Please insert the lines below.
interface wlan1
static ip_address=192.168.220.1/24
static routers=192.168.220.0
Clicking Control + X, followed by Y, and then Return will save the file and allow us to exit the program. After making changes to the DHCP configuration, it is necessary to restart the service.
sudo service dhcpcd restart
Next, we'll change the configuration file for hostapd by entering the following command into the terminal of your RPi.
sudo nano /etc/hostapd/hostapd.conf
The following lines, which must be written into this file, establish the framework for our communication with the WLAN hardware. The only two lines in this file that warrant serious consideration are the ssid= and WPA passphrase= entries. Some wifi devices have particular driver needs; thus, you may need to modify the driver= line to point to the most significant driver for your device. A quick Google search will do the trick if you need help figuring out which driver to use.
interface=wlan1
driver=nl80211
hw_mode=g
channel=6
ieee80211n=1
wmm_enabled=1
ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]
macaddr_acl=0
ignore_broadcast_ssid=0
auth_algs=1
wpa=2
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
ssid=Pi3-Extender
wpa_passphrase=raspberry
To restrict access to your wifi booster from prying users, you need to modify your WPA passphrase to a strong password of your choosing. We can save the file and exit the program using Ctrl + X, Y, and Enter. Once that is complete, we can make changes to the hostapd configuration script in /etc/default/ and /etc/init.d/. It must first read these files for hosting to use the newly produced configuration file. The command below will open the initial of these two script for editing.
sudo nano /etc/default/hostapd
The following line needs to be updated in this document.
Find:
Instead, substitute
DAEMON_CONF="/etc/hostapd/hostapd.conf"
Clicking Control + X, followed by Y, and ENTER will save the file and allow us to exit the program. We'll modify the next script we need to set up now, which can be located in the init.d folder. The command prompt will allow us to make changes to the file:
sudo nano /etc/init.d/hostapd
The lines below need to be updated in this document.
Find:
Change to:
Tapping Control + X, followed by Y, and afterwards, ENTER will save the file and allow us to exit the program. Now that hostapd is ready to go, we can move on to configuring disease, but first, we need to relocate the default config file. Let's use the command below to accomplish this:
sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.Orig
After relocating the old configuration script, you can start working on your new file. The command below will be used to make the new file and make any necessary changes:
sudo nano /etc/dnsmasq.conf
Including the lines below this file is recommended, instructing the dnsmasq service about handling incoming connections.
interface=wlan1 # Use interface wlan1
listen-address=192.168.220.1 # Specify the address to listen on
bind-interfaces # Bind to the interface
server=8.8.8.8 # Use Google DNS
domain-needed # Don't forward short names
bogus-private # Drop the non-routed address spaces.
DHCP-range=192.168.220.50,192.168.220.150,12h # IP range and lease time
Pressing CTRL + X, followed by Y, and afterwards ENTER will save the file and allow us to exit the program. Now we must set up our Raspberry Pi to relay all wlan1 traffic over to wlan0. To begin, modify the sysctl.conf config file using the command below to activate it:
sudo nano /etc/sysctl.conf
locate the line below in this file and delete the hash symbol (#).
Locate:
substitute with
net.ipv4.ip_forward=1
Pressing Control + X, followed by Y, and then ENTER will save the file and allow us to exit the program.
In any case, if you don't want to wait for it to activate on the next boot, you can use the command below to make it happen instantly:
sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
Now that IPv4 Forwarding is working, we can set up NAT across our wlan0 and wlan1 networks. Essentially, this will redirect all wireless network traffic from our AP to our ethernet link. To implement our new iptable rules, we must execute the following commands:
sudo iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
sudo iptables -A FORWARD -i wlan0 -o wlan1 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan1 -o wlan0 -j ACCEPT
If you have any problems after typing the above lines, try doing a sudo reboot on the Pi. The new rules we create will need to be saved somewhere so that they can be reloaded into iptables after each reboot of the Raspberry Pi. Use this command to store our modified set of rules permanently:
sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"
Now that we have our new rules written down, we need to ensure they have loaded back in every time the system restarts. Changing the RC.local file is the simplest solution. To begin making changes to the file, type in the following command:
sudo nano /etc/rc.local
Since we're already here, we might add this line that follows the file. See that this line is visible from Exit 0 and higher. This line extracts our iptables configuration settings. Iptables takes the rules from the ipv4.nat file and applies them.
Locate:
Add this:
iptables-restore < /etc/iptables.ipv4.nat
We can now save the file and exit the program. We may conclude by using systemctl to enable the two services we just started. Put these two commands to work:
sudo service hostapd start
sudo service dnsmasq start
If everything went smoothly up to this point, you should now have a fully functional Pi Wireless AP, which you can test by linking any of your wifi devices to it with the Id and WPA Passcode you established earlier the tutorial. A restart may be all that's needed to get things back up and running when an error has been detected. This will guarantee that the Raspberry Pi's re-enabled features work correctly after restarting. To force a reboot of the Raspberry Pi, type the following command:
sudo reboot
Any device, regardless of whether it has VPN software installed, can be routed through a secure connection by connecting to a VPN Access Point since all traffic from that device will immediately begin passing through a VPN tunnel after being connected to your Pi 4 wireless access point. This article expands upon our earlier guide on setting up a wifi access point by making one significant adjustment: redirecting all data traffic through a virtual private network. Using either VyprVPN or NordVPN, we'll demonstrate how to set up this secure tunnelling protocol. For this guide, we tested several different VPN services, which proved to be among the most dependable in terms of speed and privacy policies.
This guide will explain how to use your VPN provider's software to establish an encrypted tunnel between your local network and the wider internet. This guide will discuss using VyprVPN and NordVPN as Virtual Private Networks. Both of these met our requirements for dependability, speed, and sound privacy protections, so we settled on them. OpenVPN will be used for the VPN connection; as both services, we'll discuss offering complete support for OpenVPN standard and supply us with the necessary.open files to get it up and running. Now that everything has been up to date, we can set up OpenVPN, the program we'll be using. Using the terminal, we may accomplish this by inputting the command below:
sudo apt install OpenVPN -y
Let's now move into the OpenVPN directory, where we'll keep all the files and configuration settings for our Raspberry Pi VPN server. Let's use the change folder command to go directly to that folder.
cd /etc/openvpn
We need to generate an authorized file now that we are in the OpenVPN directory. The auth.txt file we will make is where your VPN login information will be stored.
Create the file initially by issuing the below nano instruction.
sudo nano /etc/openvpn/auth.txt
Copy and paste the example login and password below into the file. We will configure OpenVPN to use this file as its login credentials whenever you connect to your VPN.
When you're finished making changes, save the script, and we'll go on.
First, execute this command to verify that you are still in that OpenVPN folder before proceeding with downloading the VyprVPN installation files. Of course, you'll need a VyprVPN account before using these files.
cd /etc/openvpn
Once the VyprVPN OVPN files have been downloaded, you can access the configuration directory. We will be loading these components to connect to Vypr's server network. Download the archive from VyprVPN's servers using the wget command.
sudo wget -O vyprvpn.zip \
https://support.goldenfrog.com/hc/article_attachments/360008728172/GF_OpenVPN_10142016.zip
After transferring the zipped file to the RPi, we must extract it to use its contents. The unzip command below can be executed in the terminal to extract the file.
sudo unzip vyprvpn.zip
Now that the.ovpn files have been generated, you can explore them in the corresponding directory. Make a note of the target server's location, as you'll need to supply it in a later operation.
cd OpenVPN256
Execute the command below to display a list of all.ovpn files are currently stored here. Remember the filename of the desired location; for example, "USA - San Francisco.ovpn" would be remembered if a connection to San Francisco, California, in the U.s was desired.
ls
The required ovpn file should be transferred from the OpenVPN256 folder to the OpenVPN folder. Since we'll be making modifications to the file, having it under the OpenVPN directory will make autostarting the daemon much less hassle. Our sample file may be relocated to the correct folder with a command like this. You must be in the VyprVPN folder to run this command. You'll need to rename the extension if you want OpenVPN to recognize and use the file.ovpn to.conf. We will modify the file after moving it to make it more user-friendly.
sudo mv "USA - San Francisco.ovpn" "../USASanFran.conf"
After that, you can proceed to "Setting up the Virtual private network access point," where you'll find detailed instructions on modifying the.ovpn file and setting the VPN to launch when the system boots automatically.
After finishing the auth.txt file, head to NordVPN and download the necessary.ovpn configuration files. Please note that you will need a NordVPN subscription to use these files. However, before we proceed, let's double-check that we're already in the correct directory by entering the following command into the terminal.
cd /etc/openvpn
Now, navigate to the ovpn area of the NordVPN webpage to get the OpenVPN configuration files. Locate the server you want to use on this site, right-click on "Download UDP," and select "Copy Address" to copy the link. Simply replace the URL in the following command with the copied URL. We'll be using the au514 server in this example.
sudo wget https://downloads.nordcdn.com/configs/files/ovpn_legacy/servers/au514.nordvpn.com.udp1194.ovpn
The downloadable file should now be renamed. You can save some time in the tutorial by giving the file a new name before using it. Additionally, you must convert the file extension from.ovpn to.conf. This modification is required for OpenVPN to recognize the file and incorporate it into its startup process when autostart is enabled. See how easy it is to rename a file with the mv command by looking at our working example. To make the au514.nordvpn.com.udp1194.ovpn filename more manageable while still providing sufficient information about which server it is for, we reduced it to just au514.conf.
sudo mv au514.nordvpn.com.udp1194.ovpn au514.conf
The section "Setting up the Virtual private network access point" can be accessed once the file has been renamed. In this part, you will learn how to connect to an OpenVPN server and redirect traffic through it.
Since we have a working.ovpn file, we need to tweak it so that our RPi Virtual private network access point can connect to the internet. Start by executing the following command, changing the filename to the one you want to use.
sudo nano au514.conf
The following line in this file has to be edited, so go ahead and do a search. To quickly locate this passage, press CTRL + W. This modification will cause the Vpn client to load the auth.txt file whenever it is opened automatically.
Find
Switch to
After making changes, use CTRL + X, Y, and enter to save the script.
After that is complete, we can verify that OpenVPN is connecting to our VPN service, NordVPN. When we run the command below, it will overwrite the existing one.conf (.ovpn) script with the one we edited in the previous section. We'll use the "au514.conf" configuration file as an illustration.
sudo openvpn --config "/etc/openvpn/au514.conf"
While this operation establishes the connection, it will generate a large amount of text; the most important is the format we've demonstrated below. If you get similar results, you are successfully connected to your OpenVPN provider's servers.
After a successful trial run of the OpenVPN client, we may terminate it and move on to making it launch automatically at system boot and adjusting firewall routing to force all traffic to go through the Virtual private network tunnel. Hit Control + C to cancel the action you're now performing. Now that we have a functional VPN, we can use iptables to redirect the wlan0 traffic through the VPN instead of directly to an Ethernet-like we did in the previous wireless AP tutorial. But before we do so, we need to clear away our existing iptables, which we can accomplish by using the three lines below on the RPi.
sudo iptables -F
sudo iptables -t nat -F
sudo iptables -X
Finally, we can install the updated iptables by issuing the command below, which will direct all wlan0 traffic through the tunnels.
sudo iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
At this point, we may save our iptables and remove the rules we previously set up for our Wireless AP guide. To accomplish this, enter the command below into the RPi terminal.
sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"
Since the firewall is operational, the Vpn client's config file will need to be modified. To start modifying the file, type in the following line.
sudo nano /etc/default/openvpn
The following line should be uncommented, and "all" should be substituted with a file name you edited in the previous Steps when you return to this file. Please see the example we've provided below.
Locate
Instead, substitute
autostart="au514"
After making the necessary edits, press Control + X, followed by Y, and finally, return the key to save and quit the Vpn config file. Rebooting your RPi should now allow you to test out your Setup. At boot-up, it must connect to the VPN, create the tunnel, and route all wireless signals.
sudo reboot
When using a VPN, the best way to ensure it is functioning correctly is to compare your Internet address to that of a device that is not linked through a Private network. On the other hand, both NordVPN and VyprVPN, two of our examples, clearly indicate whether you are "Protected" or not at the very top of their websites. If you want the same results as those shown above, you'll need to make one tiny adjustment and use the below commands. Most noticeably, we will now use our wlan1 connections to tunnel traffic rather than wlan0.
sudo iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
sudo iptables -A FORWARD -i tun0 -o wlan1 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan1 -o tun0 -j ACCEPT
Now your raspberry pi should be set up as a wifi extender
Depending on several factors, you can take advantage of a Wireless extender in various settings. These wifi Extender Benefits analyze why you need one and the amount of money you may save using one.
Increased Protection in Open Space
When your home has a lot of electronic devices, a wifi Booster or repeater is a robust solution for covering wireless communication coverage. Connecting a wifi extender to your home's network can increase the signal's reach, which is one of the device's primary benefits. It will boost your router's password by acting as a repeater.
The Wireless Extender is Simple to Install
Plug-and-play capabilities and automated configuration are standard on modern wifi range extenders. It's user-friendly enough that you won't need to study a technical manual before putting it to work. You can take a product straight from the box, put it into an electrical outlet, and start using it. The Setup and maintenance of a wifi range extender are free of charge.
The existing Router Will Be Reused.
Since the Wireless repeater and the original router share the same Id, you can continue to use the original router with the repeater. Range extenders can be used to convert an existing router into a repeater, saving you the trouble of having to dispose of the device. You can reuse the signal in different rooms without running additional cables by setting up a wifi range extender. You can get the most out of your outdated network gear.
Budget-Friendly
Adding a wifi repeater to your network will increase its coverage without requiring additional hardware. One of the benefits of wireless extenders is the money they can save you. Moreover, a Wireless extender setup requires no extra wires or labour, making it the simplest to set up. These gadgets are completely pre-configured, so there is no need to spend money on laborious Setup or special cables.
Connectivity for a large number of users
A key drawback of having a shared wifi network is the loss of connection speed every time a new user joins your wireless network. Imagine you're attempting to load Wikipedia while someone else is streaming in high volume. It's common to run into this issue when the number of users on the network rises, and the available bandwidth decreases. A wifi range extender is helpful for these people because it allows them to connect to the network from anywhere in the house by using various channels and frequencies.
While a wifi repeater is a fast, innovative, and cheap solution to wifi coverage concerns, it is essential to note that it is not a magic bullet. You may encounter these drawbacks of wifi Extender, which may cause you to reevaluate your position.
Bad Reception
If your wifi adapter is emitting a weak signal, a Wireless extender can help. If your router is older or unsecure, you may run into any of these primary issues as a consequence of utilizing a Wireless Booster at home. Repeaters typically reduce network bandwidth for connected PCs by two, so upgrading your modem and wifi extender is not a good idea. A signal is received, processed, and then repeated on many channels by a repeater. Both the PC and the router take part in this procedure. Because of this cause, the signal intensity is weakened.
Low Speeds
There may likely be a decrease in Wireless internet speed because of the signal's passage through the repeater due to signal weakness. As the wifi range extender strives to boost the movement within your residence, the quality of your network will inevitably decline.
Issues of Incompatibility
However, setting up a repeater from a different manufacturer to work with the router can become a chore. There could be compatibility or operability concerns as a result of this. Generally, it's best to use parts and software made by the router's original manufacturer.
In most cases, the repeater will have a unique password and SSID from the router. Launching a new brand name comes with its share of challenges.
Adherence to emerging wifi standards
It is wise to verify how often a wifi range extender's software is updated before purchasing. You should think about this if you want to use it for a long time. Wireless range extenders can become unusable if their firmware is out of the current. Don't buy anything if the fixes aren't readily available as patches.
This tutorial taught us how to build a raspberry pi four wifi extender to increase the wifi range of our home wifi network connection. We also looked at how we can configure a VPN for the same pi four wifi extender to offer security to our home network. Now we can try out more advanced ideas like how to boost the signal strength of the wifi extender without interfering with the internet service provider. Using a Raspberry Pi and a SIM800L in the following tutorial, we'll set up an IVR system that can dial numbers and send text messages automatically.
Hi Friends! Hope you’re well today. Happy to see you around. In this post, I’ll walk you through How to Install PCBWay Plugin for KiCAD PCB Software.
Before we move further, let’s get a brief overview of KiCAD PCB Software.
KiCAD is a free and open-source electronic design application mainly developed to draw schematics and PCB layouts. It is open-source which means anyone can use it to develop and modify electronic designs. The tool can effortlessly run on Windows, macOS and Linux. The main window of the application comes with 8 different software tools used to make PCB layouts and schematics.
Hope you’ve got a sneak peek at the software. Now we’ll get to know how to install the PCBWay Plugin for KiCAD.
When you install PCBWay Plugin for the KiCAD, you can instantly send the PCB layout to the PCBWay for the production of your required boards.
To install PCBWay Plugin, go to the KiCAD website. The following page will appear when you visit the website.
Click the “Download” button encircled in red. When you click it, the following image will turn up.
Here you will see the list of operating systems you can pick from. Click the required system. For instance, if you click the windows operating system, the following image will come up.
Based on your system requirement, you can choose between the 64-bit and 32-bit. When you click anyone of them, the following image will come up.
Here you’ll see the different downloading links based on your location. The recommended option is the “Worldwide” with the link from GitHub.
When you click this option, the software will start downloading.
Once downloaded, right-click the software and click “open”.
When you click it, the window will open up. Then click the “next” and then “install” when you click it, your installation will start as follows.
Once installation is completed, click the “Finish” as follows.
Then start the software. Once you start it, the following options will appear. You can either import the settings from the previous version or you can start with default settings to start it from scratch as follows.
When you start with the default settings, the following window will appear. Go to the “Tools” section and select “Plugin and Content Manager”.
The list of plugins will open up. Scroll it down and find the “PCBWay Plug-in for KiCAD” as follows.
Click “install” and then click “Apply Changes” and the PCBWay plug-in for KiCAD will be installed through which you can send your PCB layout to the PCBWay with just one click.
When you click PCBWay Plug-in button on Kicad, the following files will be exported to your project:
1. Gerber files used for production
2. IPC-Netlist file
3. Bom-file that comes with the information of components
4. Pick and Place-file in assembly
When you click "Save to Cart" to immediately placing an order after you upload the files, the PCBWay team of professionals will cross check the files before starting the final production.
Choosing the right manufacturer is tricky, especially when everyone claims to be the best in the market. In this read, we’re covering the most renowned PCB manufacturing company that has been serving the electronic industry for over a decade now.
PCBWay is a china-based PCB fabrication house. It is a one stop shop for both PCB and PCBA (printed circuit board assembly). From single layer, double layer and multiple layers to flex, rigid and rigid-flex boards, they have you covered. They come with 50 engineers on board that make sure the manufactured board run through a stringent inspection processes. They ensure the customers’ demands are properly met so they keep coming back for what the company has to offer.
They strive to meet the customers’ expectations by standing on their words. A few customers have seen the slight change in price of the final product. But that’s not their fault. It’s on the customer side since they didn’t pay special heed to matching the parameters of the production files. So, keep in mind… before you submit an order, make sure the parameters of Gerber and production files exactly match with the ones you put online during the submission of order in an instant quote. If they don’t match, you may see the slight change in price for the production of the final product.
When your order process is complete, they will send you three emails: First email will tell you about the order status, whether it’s been approved or rejected. Second email is about the successful payment and production management and the third one is for the products being shipped. This way, you remain thoroughly updated about the processes your product will go through. Know that, you can ask for the change in parameters of the product before the production process is scheduled. However, if your product already goes through the initial stages and has reached the certain stage of product, you cannot ask for the change and the parameters will remain the same you initially put during the order submission.
They value your time and money. They know how it’s important to deliver products on time so folks working on their electronic projects can develop and execute their projects in a timely manner. PCBWay takes pride in achieving a 99% delivery rate. They work 24/7 from Monday to Friday to make sure the final products are delivered as promised.
The best thing about PCBWay is that when you become their regular customer and buy more PCBs, you become a part of their V5 members. These members can enjoy 5% off on upcoming orders. Additionally, you get Beans when we put your order online. Beans are rewards points that come in handy to buy electronics products from their online shop.
That’s all for today. Hope you find this article helpful. If you have any questions regarding the installation of the PCBWay Plugin, you can ask in the section below. We’d love to help you in the best way possible. Thank you for reading the article.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Raspberry Pi 4 | Amazon | Buy Now |
Welcome to the next tutorial in our raspberry pi programming. In the previous tutorial, we learned how we could run Xbox cloud on our pi 4. We found that we can run any game easily without lag or having raspberry pi shut down, proving that pi 4 is quite a powerful minicomputer. However, this tutorial will demonstrate how to use Python on raspberry to monitor websites. This Python program will execute on Pi 4 and watch over a website, alerting you whenever it changes or goes down. This is accomplished by keeping a straightforward webpage duplicate locally and monitoring for updates. This webpage monitor is straightforward, so it should work well on pi Zero. Throughout this tutorial, we will demonstrate how to develop your custom code to monitor a webpage. With this information, you ought to be able to modify the script to meet your unique requirements. However, for email updates to function, a few settings must be made in the core code.
The lack of an interface makes this project ideal for a headless Pi. Even though this tutorial concentrates on Pi 4, the core code can be used on any device that supports Python 3. That implies that, if you'd want, you could even execute this program on a Windows computer.
Raspberry Pi
Micro SD Card
Power Supply
Ethernet Cable or Wi-Fi
Ensure you have all the components you need to execute your website monitoring program before you begin. These actions include installing Python 3 and the necessary Python libraries. Updates to the package registry and any current packages come first. To make these upgrades, we must execute the following lines in the console on our Pi 4.
sudo apt update
sudo apt upgrade -y
We must make sure that Py 3 and its application manager, "pip," are both installed on the mini-computer. To guarantee that the two packages are loaded, use the below command.
sudo apt install python3 python3-pip
Installing the necessary Python libraries is the last step before writing the program to monitor our web pages. Download the packages for queries, beautiful soup4, and lxml with this line.
pip3 install requests beautifulsoup4 lxml
Having completed the installation of the necessary packages, we can begin drafting our elementary website monitoring code. So that you can understand how everything functions, we'll break this down into its parts. Though the nano editor will work, a more capable integrated development environment (IDE) like Visual Studio Code is recommended. Get started on the Python code to keep an eye on a website with your Raspberry Pi. Websitemonitor.py is the name of the script we'll be working with throughout this guide. Launch nano and enter the following command to begin writing the script.
nano websitemonitor.py
Before we get too far into coding a complex website monitoring program for our RPi, let's start with the simplest possible solution. We shall craft a basic script to retrieve a web page, check its contents against a known master copy, and output an appropriate message if any changes have been made. At the beginning of any script, we must import the packages we'll be working with. These scripts' launch requires the "os," "sys," and "requests" packages.
Os: To communicate with the os, you will need to install the package known as os. For our purposes, we'll be using this to store a copy of our most recent website request in a cache. To detect any modifications, we will check this cache.
Sys – For any arguments supplied to the program, we utilize the sys library to retrieve them. We'll allow the user to provide the URL of the website and the name of the cache in this case.
Requests – Python can only send requests thanks to the requests package.
This allows us to take a certain website's content and save them.
import os
import sys
import requests
Most of our logic will be handled by a function we'll write next. Two parameters must be set for this function: "has the website changed." The first input, the website URL, contains the website's address. We will make we obtain a request from this point forward. The website name, the second parameter, contains the website's name. This is a condensed form of the name used for the cached file. This method will have 3 potential return values: -1 if the webpage is "not ok," 0 if the webpage hasn't changed, and One of the webpages is altered.
def has_website_changed(website_url, website_name):
Keep in mind that indentation is crucial when using Python. Please make careful to keep the indentation when you complete this function.
Now that our function is specified, we can move on to implementing it. To initiate a website request, we must first define the headers sent by the request module. We are doing two things with these headers. For starters, there's the "User-Agent" header. Set it to whatever works best for you. For the most part, we are trying to keep things straightforward here.
Second, we instruct the client and the destination server not to store this request in their cache by setting the "Cache-Control" header to "no-cache." There is no guarantee that the requested web server will comply.
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
The queries package is secure enough to retrieve the passed-in URL with the requested headers. This is a vital part of our RPi's website monitoring software, as it returns the site's current status. This is an example of the get function included in the "requests" package. The "headers" and "website URL" variables are passed in. The result of this query will be saved in the "response" parameter.
response = requests.get(website_url, headers=headers)
Once we've retrieved the website's response, we need to double-check that it was an "OK" response. Simply put, we need to ensure the error code is not below 200 or above 299, inclusive.
If the value is outside our allowed range, we will return "-1" to indicate an error on our end.
if (response.status_code < 200 or response.status_code > 299):
return -1
Let's set up two more variables after verifying the response to ensure we get a proper status code. For now, we'll keep the text of the response we received in a variable called "response text." This variable will allow us to tailor the response wording before saving it. Our RPi website monitor will continue to work with the present form of the answer text for the time being.
As a second step, we set up a variable named "cache filename" to hold the location of our cache's data file. This name will be fabricated using the "website name" argument and the suffix "_cache.txt." If our website's name were to be entered as "theengineeringproject," the resulting filename would be "theengineeringproject cache.txt."
response_text = response.text
cache_filename = website_name + "_cache.txt"
It's possible that the current website's URL won't have a cache file when you initially run the program. We use the "path.exists()" function from the "os" package to see if the cache script already exists. If the cache file doesn't already exist, we make one by opening it with the "w" switch. We then append the text of the current response to the file, allowing our Raspberry Pi to check for updates to the website. Given that this is a brand-new request, we will respond with a value of 0 to indicate that the reply has not changed.
If not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
If the program reaches this stage, the "previous response text" variable will need to be updated with the contents of the cache file. Now we'll utilize "r+" with the open function. The following command informs open that we want to be able to read and write to our cache file. After Python finishes reading a file, the stream position is reset to the beginning; thus, we need to use the "seek()" function to return to the beginning. If this is a fresh reply, it will be simpler to truncate the file.
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
We may now check for a match between the answer text and the original one.
If the responses are identical in content, we exit the process by closing the file handle and returning 0. Recall that a value of 0 indicates nothing has changed in the responses. This, together with the else statement, completes our RPi's "has website changed" monitoring function.
if response_text == previous_response_text:
file_handle.close()
return 0
If the responses don't match, our RPi has picked up on a change while keeping tabs on the webpage. If the race were being run right now, it would be in position 0. We then append the updated reply to the file once it has been truncated. The file handle can be closed as soon as the writing is done because it is no longer required. Since the answer has shifted, we send back a 1 to show that it has been updated.
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
To continue our RPi-based website monitor, we must now create its main method. This method will be invoked anytime the script is executed. In this script section, we'll mostly be concerned with invoking the function we just made, so it should be rather simple. First, we'll identify the primary role. This is where the real magic happens for our RPi-based webpage monitoring.
def main():
At this point, we can access the "has website changed()" method we've created. This method's initial and next parameters will be passed in via the "sys" package. The web address (Uniform resource locator) will be the first argument. As for the second, it will become the cache file's title. The function's output is saved in the "website status" variable we created.
website_status = has_website_changed(sys.argv[1], sys.argv[2])
Our variables now contain the current online status, so we can use that to inform our output. Our basic website monitoring software for the Raspberry Pi is now complete. We can expand upon this feature to make it possible to communicate via email or text message. This is a basic if, Elif clause that prints out various text based on the input.
if website_status == -1:
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
print("Website has changed")
Last, we can wrap up our script by including the call that activates the script's main method. Using an if clause, we can be sure that the program was actually called and not just loaded as a Python package.
if __name__ == "__main__":
main()
The program can be saved and tested at this stage. What we have provided here is how the completed core code should appear. To save your work in the nano editor, use control + X, followed by Y, and finally, the Return key.
import os
import sys
import requests
def has_website_changed(website_url, website_name):
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
response = requests.get(website_url, headers=headers)
if (response.status_code < 200 or response.status_code > 299):
return -1
response_text = response.text
cache_filename = website_name + "_cache.txt"
If not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
if response_text == previous_response_text:
file_handle.close()
return 0
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
def main():
website_status = has_website_changed(sys.argv[1], sys.argv[2])
if website_status == -1:
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
print("Website has changed")
if __name__ == "__main__":
main()
Seeing that our web monitoring software is complete, it can be deployed on the Raspberry Pi. The following procedures will help us test and verify that the script is functioning properly. Our web monitoring script requires elevated permissions before proceeding. By executing the following line on the RPi, we may grant this access to the website monitoring program.
chmod +x websitemonitor.py
Now that the script has the correct permissions, we can run it. When running this script, you will need to know the URL you want to monitor and the name you want to use for its cache. For our example, we will use "https://www.theengineeringprojects.com/” as our URL to monitor and “project” as our cache name.
python3 websitemonitor.py https://www.theengineeringprojects.com/ project
You may check if the website monitor produced the cache file with the ls command in the console. A text document with the extension "_cache.txt" should be present. Take the "theengineeringprojects cache.txt" file as an illustration. If you execute this script, you may find an issue right away. Metadata can be dynamically set on some websites, meaning that even if the content remains unchanged, each request to the site could result in a slightly different response. If you use our website, you'll see that our script will flag the page as modified whenever we update the core code. In the next part, we'll demonstrate how to use Python's lovely soup to tidy up the outcome and remove anything that could falsely flag the webpage as modified.
Here we'll use beautiful soup to enhance Raspberry Pi's web server monitoring. The beautifulsoup Python module is a potent tool for modifying HTML documents. We may eliminate clutter like style and script tags, for instance. You'll need to adjust the script we built in the last step for this one. A new import is added to the script's initialization. This will bring in the bs4 library and its BeautifulSoup module.
from bs4 import BeautifulSoup
Our new mission must now begin. Any HTML obtained from the queries package will be cleaned up using this method. As a result, our RPi's behavior during web monitoring will become more standardized. Including the following code in the file will define the new method. The HTML material to be processed will be supplied as the sole input to this function.
def cleanup_html(HTML):
A fresh instance of BeautifulSoup is instantiated now. The first argument is the HTML string to be cleaned up. We specify the HTML parser we need to utilize in the second argument. XML is used since it is quick and has all the required features. A faster and more efficient program is always welcome in a resource-constrained environment like our RPi, in which we are executing a web monitor.
soup = BeautifulSoup(HTML, features="lxml")
With BeautifulSoup, we can parse HTML and get rid of unwanted tags. We strip off the "script," "style," and "meta" tags with for loops as well as BeautfulSoup's "select" method. You'll see that the ".extract()" method is called on each loop iteration. When an element matching the given criteria is located, this function deletes it.
for s in soup.select('script'):
s.extract()
for s in soup.select('style'):
s.extract()
for s in soup.select('meta'):
s.extract()
After BeautifulSoup has processed the HTML retrieved by our website monitoring software, we can return it. It's not enough to return your soup object to its current state. Alternatively, the "str()" function must be used to transform it into a regular string.
return str(soup)
Our "cleanup html()" function is complete; now, we only need to update some other code to use it. Locate the piece of code below and change it. Instead of storing the reply text without thinking, we first pass it through the new method. The "has website changed()" method is where you'll want to put it.
Substitute the following for the sentence.
response_text = cleanup_html(response.text)
Once you've finished editing the script, the program should resemble what we've displayed below. To save your work when using nano, use control + X, followed by Y, and finally, the Return key.
import os
import sys
import requests
from bs4 import BeautifulSoup
def cleanup_html(HTML):
soup = BeautifulSoup(HTML, features="lxml")
for s in soup.select('script'):
s.extract()
for s in soup.select('style'):
s.extract()
for s in soup.select('meta'):
s.extract()
return str(soup)
def has_website_changed(website_url, website_name):
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
response = requests.get(website_url, headers=headers)
if (response.status_code < 200 or response.status_code > 299):
return -1
response_text = cleanup_html(response.text)
cache_filename = website_name + "_cache.txt"
If not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
if response_text == previous_response_text:
file_handle.close()
return 0
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
def main():
website_status = has_website_changed(sys.argv[1], sys.argv[2])
if website_status == -1:
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
print("Website has changed")
if __name__ == "__main__":
main()
The script is ready for further testing. More stable outcomes are expected this time around. We can decrease the likelihood of a false detection by eliminating the "script," "style," and "meta" tags. For instance, every query on our website must not be recorded as "modified" if you follow this pattern.
Our Raspberry Pi monitoring system is somewhat useless without a way to be alerted when a website has been updated. We'll add to our functionality here by notifying you through email anytime the script notices a shift. Remember that this will necessitate you to have the SMTP information for your email provider at hand. Here, we'll use the SMTP settings for Gmail as an example.
We must import a separate package to make SMTP connections from within Python. Thankfully, Python already has this module built in. Include the following line in your script's imports. This line will make it possible to establish SMTP connections quickly by importing the necessary "smtplib" package.
import smtplib
At the outset of the Python code, we must define certain constants. Below the existing "import" command, add the lines below. The fact that Python doesn't truly support constants doesn't stop us from naming these parameters with all capital letters, though. You shouldn't modify these values while the program is running.
Identity for your outgoing mail server (Simple mail transfer protocol) connection, as defined by this constant. This is the account you'll use to access Gmail.
We refer to the value saved in this constant for the simple mail transfer protocol connection.
SMTP_USER='example@gmail.com'
The SMTP user's password must be set inside this constant. This is the password for your Gmail account. Second-factor authentication (which you should enable) requires a separate app passcode.
SMTP_PASSWORD='PASSWORD'
The address or URL to which the SMTP connection should be established is saved in the "SMTP HOST" constant. Here, we'll use the SMTP server information for Gmail as an example.
SMTP_HOST='smtp.gmail.com'
Using this setting, we tell our RPi web monitor which port to use when it detects a change and needs to notify us through email. Using Gmail's port for implicit SSL, as shown below: (port 465).
SMTP_PORT=465
These days, most email providers offer a secure connection (SSL or TLS). Our software will only be able to utilize HTTPS protocol. Ensure the constant is set to True to activate this support. By setting this to False, SSL will be turned off.
SMTP_SSL=True
At long last, we have the option to designate the sender's email address for this message. It must be an account you have created to use this email. If you're using an Email account, this should be a verified email address. You need to set up that email account and domain in your transaction email provider, such as Mailgun.
SMTP_FROM_EMAIL='example@gmail.com'
The final required setting is the destination email address for the script to use to send the email. Enter the email address at which you would like to be notified of updates to the website.
SMTP_TO_EMAIL='sendto@gmail.com'
Our "email notification()" method can be written when we have declared all necessary constants. This function will take care of the process of connecting to an SMTP server and sending an email. Let's begin by identifying our new role. There will be two inputs for it.
def email_notification(subject, message):
Initiating an SMTP session is the first step of this method. Since we need to accommodate both SSL and non-encrypted connections, we'll have to make two distinct calls separated by an if clause. An SMTP session is established and saved in the "SMTP server" parameter if the "SMTP SSL" flag is set to True. When SSL is not enabled, we also take this action. We include the SMTP HOST and SMTP PORT environment variables when establishing the link.
if (SMTP_SSL):
smtp_server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT)
else:
smtp_server = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
After establishing contact with the SMTP mail server, we can start composing and sending the email. We'll first fire off an "eh" to the server. We won't delve too deeply into what this information conveys to the server. The next step is to send an authentication message to the server. The credentials saved in the variables "SMTP USER" and "SMTP PASSWORD" will be sent along with this login request.
smtp_server.help()
smtp_server.login(SMTP_USER, SMTP_PASSWORD)
The next thing we need to do is compose the message sent via the SMTP connection. This is crucial since it allows our Raspberry Pi to send you an alert if it detects a change to the website you've instructed it to monitor. This structure is adaptable to your needs. To avoid any confusion, please use the "FROM," "Too," and "Subject" lines as shown here. On different lines, please. In addition, one blank line should precede the main body of your email.
email_text = \
"""From: %s
To: %s
Subject: %s
%s
""" % (SMTP_FROM_EMAIL, SMTP_TO_EMAIL, subject, message)
As the final step of this procedure, we transmit the email over our SMTP session. The previously generated email, along with the email address from "SMTP FROM EMAIL" and the destination email address from "SMTP TO EMAIL," are passed into this function call. After the message has been transmitted, we terminate the SMTP session.
smtp_server.sendmail(SMTP_FROM_EMAIL, SMTP_TO_EMAIL, email_text)
smtp_server.close()
Since the necessary method has been written, it must be called from within the program. Here, we'll modify the "main()" procedure. You need to locate the line below in your Python code.
print("Non 2XX response while fetching")
Follow that with the line below. The script will automatically send you an email to notify you every time the RPi web monitor encounters an error connecting to the webpage.
Moreover, we should have a line that alerts us whenever the webpage updates. Check your script for the following line. Ideally, it would be located below the previously discovered line. Try to find the following:
The following line should be added above it. Every time this line is reached, an email will notify you that the web has been updated.
After making the necessary modifications, your script's core code should resemble what we have provided as an example. Before moving forward, make sure to save your code. Your website monitoring service should now send you email alerts if functioning properly. It will send a notification email whenever it is launched and detects a change to the website. This website will, however, notify you by email if it becomes unavailable or produces a status code other than 2XX.
import os
import sys
import requests
from bs4 import BeautifulSoup
import smtplib
SMTP_USER='example@gmail.com'
SMTP_PASSWORD='password'
SMTP_HOST='smtp.gmail.com'
SMTP_PORT='465'
SMTP_SSL=True
SMTP_FROM_EMAIL='example@gmail.com'
SMTP_TO_EMAIL='sendto@gmail.com'
def email_notification(subject, message):
"Send an email notification.
Message - The message to send as the body of the email.
"""
if (SMTP_SSL):
smtp_server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT)
else:
smtp_server = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
smtp_server.ehlo()
smtp_server.login(SMTP_USER, SMTP_PASSWORD)
email_text = \
"""From: %s
To: %s
Subject: %s
%s
""" % (SMTP_FROM_EMAIL, SMTP_TO_EMAIL, subject, message)
smtp_server.sendmail(SMTP_FROM_EMAIL, SMTP_TO_EMAIL, email_text)
smtp_server.close()
def cleanup_html(html):
"""Cleanup the HTML content.
html - A string containg HTML.
"""
soup = BeautifulSoup(html, features="lxml")
for s in soup.select('script'):
s.extract()
for s in soup.select('style'):
s.extract()
for s in soup.select('meta'):
s.extract()
return str(soup)
def has_website_changed(website_url, website_name):
"""Check if a website has changed since the last request.
website_url - URL that you want to monitor for changes.
website_name - Name used for the cache file.
"""
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; PIWEBMON)',
'Cache-Control': 'no-cache'
}
response = requests.get(website_url, headers=headers)
if (response.status_code < 200 or response.status_code > 299):
return -1
response_text = cleanup_html(response.text)
cache_filename = website_name + "_cache.txt"
if not os.path.exists(cache_filename):
file_handle = open(cache_filename, "w")
file_handle.write(response_text)
file_handle.close()
return 0
file_handle = open(cache_filename, "r+")
previous_response_text = file_handle.read()
file_handle.seek(0)
if response_text == previous_response_text:
file_handle.close()
return 0
else:
file_handle.truncate()
file_handle.write(response_text)
file_handle.close()
return 1
def main():
"""Check if the passed in website has changed."""
website_status = has_website_changed(sys.argv[1], sys.argv[2])
if website_status == -1:
email_notification("An Error has Occurred", "Error While Fetching " + sys.argv[1])
print("Non 2XX response while fetching")
elif website_status == 0:
print("Website is the same")
elif website_status == 1:
email_notification("A Change has Occurred", sys.argv[1] + " has changed.")
print("Website has changed")
if __name__ == "__main__":
main()
If you've taken the time to write a Python script to keep tabs on many websites, you'll want to set it to run regularly. You may implement an infinite loop to make the script run indefinitely; however, a cronjob will suffice. Our Python program must be installed on the RPi before you continue. You can grab the core code from the Git repo if you'd rather skip the intro. Be careful to complete the SMTP connection information. This instruction section assumes the script is located in the "pi" user's home directory (/home/pi/). After making the necessary changes to the crontab, our program will be run automatically every minute.
Start modifying the active user's crontab with this command.
crontab -e
When requested to choose a text editor, we suggest "nano." Please insert the following line at the end of the document. If you wish to track a certain URL, you'll need to make a small change to the command. In addition, a cache name must be specified. The cache name is optional and can be any string that helps you distinguish this request from others. Insert at the end.
CTRL + X, Y, and ENTER will save your changes to crontab. A new minutely check of the specified website will now be performed by your RPi. The software will notify you if it identifies a modification to a page's content.
Encourages problem-free operation of systems
To maintain optimal performance and satisfy clients, monitoring the website is essential. Customers are in a buying mood and don't want to wait for webpages to open or for controls that don't work. If you own an online store, you should examine key performance indicators such as daily bounce rates and page load time. However, regular usability testing will ensure consistent functionality and keep visitors returning.
Keeps a site running smoothly and efficiently
A growing top line is a sign of a healthy website. However, you will not be able to spot warning signs unless you understand your typical exchange rates and annual peaks. Monitoring your statistics can provide a clear picture of your website's performance.
Detailed user insights are revealed.
One of the essential benefits of web tracking is the ability to uncover hidden user and product possibilities. This may be achieved by setting up quarterly or monthly usability tracking based on your staff's population and your website's structure. One of the most effective strategies to enhance your site and raise customer satisfaction is demonstrating empathy for your customers by performing routine monitoring activities like analyzing comments.
E-commerce transactions can be optimized using customer feedback, for example, by removing an extra photo or description step between the product selection and the shopping basket. There's a chance that another user will vent their annoyance over not being able to access subscriber-only deals. If you take the time to listen to and empathize with your users' complaints, follow up with them to let them know they must sign in to obtain the offer and assure them that the site will be improved soon.
assures usability and boosts return on investment
Users may not be able to access and engage with your website in the event of downtime or page breaks. Prolonged outages can lead to being de-indexed, dropped in search engine rankings, and a dent in your reputation. No one will wait for a down website. Customers are not easily won back, and doing so requires an investment of both time and resources. If your site goes down in Perth but remains accessible in Sydney, you won't realize the difference unless you watch it constantly. In an emergency, tracking can assist you alert consumers and fixing any accessibility problems before they affect users.
In addition to preventing disruptions in the future, automatic downtime monitoring can provide real-time alerts by studying past incidents. Whether you need to check if your SSL certificate has expired or if there is an API problem affecting site speed, automation and control can help.
Facilitates easy interaction
When servers go down, your website becomes inaccessible, and so does all of your correspondence. Because of the prevalence of remote work and international teams, port failures have become increasingly expensive. Unfortunately, there is no viable or efficient way to communicate by text message on a mobile device.
Servers and port monitoring are often included in downtime monitoring software. Systems and tools make it easy to resolve communication issues between teams, offices, and nations. Customers will appreciate the timely alerts, and your employees will appreciate the mental stimulation.
There are, of course, a few drawbacks to keeping an eye on your website. To decide if tracking is the best option for you and the team, consider these drawbacks. Some sites and portals may have a foundation of cybersecurity or automatic monitors; depending on your firm's specifics, you may just need a few more tools and processes. There is a silver lining to every cloud in the website monitoring storm. This article will provide some advice and solutions to help you deal with the drawbacks.
Costly
The cost of a good website monitoring technology might be a significant drain on a company's resources. Though many products provide free tiers of service, these tiers are sometimes not as feature-rich as paid tiers, leaving you vulnerable to security holes or unsupported APIs. Spending on paid monitoring software, if any, might range from $15 per month to $500 per month, depending on the features you require and the size of your firm.
Consumes a lot of time
Time is a necessary component of the organization, approach, and resource for successful web monitoring. How long would it take, for instance, to become an expert in website monitoring if you taught your current team how to do it? Because of the potential lack of workforce in other areas as a result of a single employee's pivot, training may not always be an option. Assume for a moment that your group possesses the necessary expertise to perform monitoring in-house. You should consider how much effort it will take and whether outsourcing is an option.
Blocklists
Checking in on your website regularly is essential. It's important to check in numerous times a day to ensure no outages. Regrettably, excessive monitoring can raise red flags with your hosting service, leading to your IP address being blocklisted. To some, blocklisting might prevent electronic communications and alert consumers that your site is a security threat, a major downside of website monitoring. However, this problem can be easily fixed by contacting your server and having your IP address allowed.
Monitoring errors
Even the most composed teams can quickly become flustered when confronted with novel tools and increased data. Mistakes in tracking can be caused by several factors, including a failure to communicate, inexperience, and hazy objectives. However, when a team is inundated with information, they may become paralyzed and unable to get the answers they need. Since the point of tracking is to swiftly handle problems within all data available instead of getting mired in data analysis, this may be particularly stressful and disheartening.
This tutorial taught you the fundamentals of setting up a web-based monitoring system on a Raspberry Pi 4. This code will retrieve the most recent version of the given URL each time it is used. Then, the cached response is checked again on the new request to determine if any changes were made. This script will notify you via an outside email server if the URL changes or becomes unavailable. In the following tutorial, we will learn how to build a raspberry pi 4 Wi-Fi extender for our home use.
Hi Guys! hope you are doing great today! We come this time with a complete project to work out together starting from the point at which we sit with the client and receive the logical narratives that represent what they want to implement. We are going to start with a simple project this time and continue increasing the scale and complexity of the requirements through the incoming tutorials. The project we are going to implement today is one of the most common tasks that we can find in every place in our real life which is the control of the garage door. That could be found in private property or commercial buildings or public garages. Too many things need to be controlled in garage doors and several scenarios could come to your mind. However, take it as a rule of thumb that we design our program based on the requirements specified by the customer not based on our thoughts.
Figure 1 images the project with details. As you can see, it is a garage door that is required to be controlled to open, and shut down flexibly and safely. Flexible operation means it needs to open and shut down at any time exchangeable showing operation indicators when it is opening and when it is closing. And safe operation means taking care of the motor and system components when the change between open and shut down commands for not make any kind of hazard to the system components.
The control logic philosophy is a common term you will be used to hear when you meet with the clients who are going to discuss with you the control logic and all scenarios which will be interpreted by you to the control narratives. The following control narratives of the project were decided and designed based on the discussion with the customer who requested the control system and it is as follows:
There will be a control panel with a front panel that has push buttons, indicator lamps, and switches that enable the end user of operating the system including all functions of the control system. that includes one push button for commanding the door to open and one other push-button for instructing the system to shut down the door. In addition, one indicator to show the door is opening, one to show the door is closing, and one to show the door is in ajar status or open slightly.
The system needs to have a safety emergency stop switch to stop the operation at any instant
The system also can switch between opening and shutting down at any time when it is allowed to do
The system needs to be safe and secure from any hazards that might occur due to wrong logic design for example requesting one operation which might cause any damage to the system components like motors
Please note that when the customer lists the requirements he or she does not know about the deep technical details like the system components that the system needs including push buttons, indicating lamps, switches, sensors, and actuators because he or she is supposed to talk at a high level while telling you the requirements and you the one who should translate his requirements into logic narratives and deciding for the whole system components.
Guys! now our work has just started by translating the above high-level requirements into detailed logic narratives and also deciding all system components and input-output lists. Figure 2 shows the garage door project with the system components that include actuators, sensors, switches, push buttons and indicator lamps.
Table 1 lists the system components which include the main motor running up and down for opening and shutting down. Limit switches for preventing the door from opening and shutting down. Also, it includes the indicators and operation status while opening and closing and ajar status as well. Also, one emergency stop is utilized to stop the process at any time. The table includes the component name, description, the related IO type, and address. For example, the main motor of the door can be run in two directions to let it open or shut down. Therefore, two coils are connected through two digital outputs at addresses O:02/0 and O:02/01 which are the third output input card and the first and second channels. Also, two limit switches have been utilized to control the limits up and down to which the door can go. They are connected to two digital inputs at addresses I:01/03 and I:01/04 which are connected to the second digital input card at the 4th and 5th channels. In addition, two push buttons to handle the open and shutdown requests of the door have been connected at addresses I:01/00 and I:01/01 which are the first and second channels of the second digital input card. And the E-stop or the emergency stop has been connected to digital input at address I:01/03 which is the 4th channel of the second digital input card. Last but not least, three lamp indicators are connected via three digital outputs which are connected to addresses O:02/02, O:02/03, and O:02/04 which are the third digital output card in the rack and the third, fourth, and fifth channels respectively.
Table 1: Input-output list of the garage door project
Component |
description |
IOs type |
Address |
Motor up |
Door motor in a clockwise direction |
Digital output |
O:02/0 |
Motor Down |
Door motor in Anticlockwise direction |
Digital output |
O:02/01 |
Limit switch |
Limit switch to stop the door from over spinning |
Digital input |
I:01/03 |
Limit switch |
Limit switch to stop door of over shutting down |
Digital input |
I:01/04 |
OPEN pushbutton |
A pushbutton to request opening the door |
Digital input |
I:01/00 |
Shut down pushbutton |
A pushbutton to request shutting the door down |
Digital input |
I:01/01 |
E-stop pushbutton |
A pushbutton to request an emergency stop |
Digital input |
I:01/02 |
Indicator lamp |
Showing ajar door status |
Digital output |
O:02/02 |
Indicator lamp |
Showing open door status |
Digital output |
O:02/03 |
Indicator lamp |
Showing shutdown door status |
Digital output |
O:02/04 |
Despite this is a simple and short project. And it is our first complete project. We are going systematically step by step to show you guys the right sequence to achieve a ladder logic project work. Again, we have to sit with the customer to get his requirements, and then we interpreted his requirements into a logical narrative and decided on the IOs list and all system components. Now we need to work professionally and create a flow chart that represents the program logic graphically as shown in figure 3. It shows when a request of opening the door has been requested, it checks for any emergency stop or a concurrent stop request is in progress, if no then it is clear and all set to energizing the coil of the contactors that drives the motor to run in Up direction for opening the door right away. Similarly, when a request to shut down the door. The emergency stop is checked and if is there an open door request in progress if the answer is no then it is all the settings to run the motor in the down direction to close the door by activating the related contactor to energize the motor in the direction to shut down the door.
Now guys after completing the design stage in which we have to design the logic and decide on the system components and the logic flow. It is time to program so let my friends open our program editor and write down the program rung by rung based on the flowchart we just have drawn in figure 3. Looking into the ladder logic program, the first rung shows the opening handling request by energizing the output coils of the motor to run in the up direction and energizing the lamp indicator in case there is no emergency stop or a shutting down request in progress. Similarly, the second rung shows the shutdown request handling by activating the coils of the motor to run in the down direction and the indicator lamp to show the process of the shutdown of the door is in progress. That is true when there is no emergency stop is hit and no opening request is in progress. Also, you can see in both rungs for opening and shutting down the door of the garage that, the limit switches are used to prevent the door from opening or over closing for protecting the motors. At last, the third rung shows the indicator of ajar status as long as the door is not completely closed or when it is slightly opened.
Now guys! it is time to open our simulator to check if we already have written the correct logic or if there is something missed or wrong. Let me tell you something before testing your program you should hold and sit back and think about the test case scenarios for not to forget any case that might cause a failure to your program. For this very program we simulate, there are two main scenarios which are testing opening the door and testing closing the door. In addition to the main test case scenarios, there are edge test case scenarios which are testing requesting opposite operations like request opening while a shutdown process is in progress or requesting shutdown while an opening the door is in progress. Or testing requesting process while the E-stop is raised to check the safety of the operation. So let’s get started and take the test cases one by one to see if we have coded our program correctly or if there is an issue to fix.
As you can see guys in Figure 5 in rung 2, the process of opening the door started by hitting the open push button, and because there is no emergency stop and there is no shutdown request in progress, the motor keeps spinning in the up direction and the opening lamp indicator keeps switched on. But up till when this operation will go on?
The process of opening the door is continued successfully until the LS1 is contacted at which the door has reached its final point for protecting the motor from overloading failure.
Also figure 7 shows the indicator of the door status on Ajar status whenever it is slightly opened or when it is not closed all the way.
Now let’s test the shutdown command by hitting the shutdown push button and notice the first rung in the program in figure 8. You can notice the door continues closing see the motor is spinning in the down direction and the indicator lamp showing closing is ON. But until when it will be stopped?
Figure 9 shows the end of the shutting down process of the door of the garage by having the limit switch LS2 reached that protects the motor from over spinning until it burned.
Figure 10 shows one of the edge test cases when the door was opening and all of a sudden operator requested to shut down the door. The test was successful and the operation can be reversed thanks at any time thanks to the good design by having the negative of each contact of the open and close in the other rung request as shown in rungs 1 and 2.
Guys! I would like to thank you all for sharing this tutorial up till this point hoping you all have enjoyed learning and practicing. And, be there with a larger project to take for the next time step by step learn, design, coding the ladder logic program, and enjoy simulating them as we are inside the factory.
Hi friends, today we are going to learn one of the most important instructions in the PLC ladder which is MOVE instruction by which we can move data between different memory storage including input, output, marker, and variables. Also, data of different data types and sizes can be transferred from source to destination and source memory locations. For example data types including char, string, integer, floating, time and date can be transferred between source and destination. Memory location like input, output, and marker memory area can be acting as source or destination. Furthermore, a mask can be utilized to customize and control the part of data to be transferred between source and destination. In that move with a mask, the instruction uses a source address, a destination address, and the mask as well. Guys, please do not worry if you are not understanding what is mentioned hundreds percent because you will get it in more detail and practice with the simulator as well. So let’s continue to learn and practice that MOVE and masked MOVE instruction.
Let’s start with the basic MOVE instruction. Figure 1 shows the typical block of a MOVE instruction in Siemens. It shows two sides for the input and output parameters of the block. Simply, the input EN input shows the contact that enables the block and triggers the movement of data between the source specified by the memory address given at input IN and the destination pointed by the memory address given at output OUT1. Also, output ENO denotes the status of the movement process to indicate the completion of the process.
As shown in the function block of the MOVE instruction shown in figure 1, there are source and destination which are an address of a memory area and can be expected to be byte, word, or double word DWORD or of any datatype like integer, character string, float, time, or date datatype. Some examples of memory size and datatype are listed in table 1 below:
Source (IN) |
Destination (OUT1) |
|
---|---|---|
With IEC check |
Without IEC check |
|
BYTE |
BYTE, WORD, DWORD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE ,TOD, CHAR |
WORD |
WORD, DWORD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD, CHAR |
DWORD |
DWORD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, REAL, TIME, DATE, TOD, CHAR |
SINT |
SINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
USINT |
USINT, UINT, UDINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
INT |
INT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
UINT |
UINT, UDINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
DINT |
DINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
UDINT |
UDINT |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME, DATE, TOD |
REAL |
REAL |
DWORD, REAL |
LREAL |
LREAL |
LREAL |
TIME |
TIME |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TIME |
DATE |
DATE |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, DATE |
TOD |
TOD |
BYTE, WORD, DWORD, SINT, USINT, INT, UINT, DINT, UDINT, TOD |
DTL |
DTL |
DTL |
CHAR |
CHAR |
BYTE, WORD, DWORD, CHAR, Character of a string1) |
WCHAR |
WCHAR |
BYTE, WORD, DWORD, CHAR, WCHAR, character of a character string1) |
Figure 2 shows one very basic ladder logic rung that demonstrates the usage of a MOVE instruction. It consists of a contact “trigger” to control activation of the move instruction, the MOVE instruction block which has source and destination memory address MW10 and MW12 respectively. The source and destination in this example represent integer data types.
Guys! Let's simulate this rung to learn together how the MOVE instruction works. Figure 3 shows the case when the MOVE instruction is not activated, in that case as shown in figure 3 the data is not transferred from source to destination.
But after activating the MOVE instruction by enabling the EN of the MOVE block using the contact M0.1, the data is moved from the sources to the destination.
It is important to let you guys know, this MOVE function block can be used to move different types of data types as listed above by providing the address of both source and destination.
Friends! Sometimes we need to move arrays of data. So do your think we are going to move one by one? The answer is yes it is possible but that is too boring to code and the program is getting very lengthy. So there is another version of MOVE instruction that enable us to move a massive amount of variables which is MOVE_BLK instruction. Figure 5 shows the function block of the massive move instruction in a very basic example ladder logic rung. As you see friends, similar to basic MOVE instruction, it has EN and ENO for enabling the instruction and returning its status showing the completion status. Also, it has an input source denoted by the address of the memory storage of the source and the address of the memory location of the destination as well. But you notice that time there is an array of variables or datatypes for source and destination. And there are other parameters called count which denotes the number of items to be moved from source to destination. Let’s simulate this MOVE_BLK instruction to see how it works and the virtues of moving many data items in one command.
Figure 6 shows the execution having the block not activated. On the right part the memory of the source and the destination show array of 5 integers for each. You can notice guys there is no data moved.
Figure 7 shows the data is moved from source to destination after activation of the MOVE_BLK instruction. But wait for a second! Why not all the data been moved? Yes, you are correct friends, because we use count parameters to control how many variables or data items are to be transferred. And it has 3. So the first three data items have been moved only.
Figure 8 shows a simple program that demonstrates the ladder logic rung that uses MOVE instruction. It shows the input contact I:3/0 triggers the move instruction block to activate it and enable data transfer from the 16bits input I:1 to the 16bits output O:2. On the left side, you can see guys the inputs are mirrored at the output by using the MOVE instruction. Now let’s see how we can control the data transfer using a mask to allow only selected bits to be transferred and prevent the others.
The idea behind the masked move instruction is that we utilize an array of bits to be used as a mask to filter the data that are being transferred. For example Figure 9 shows a very simple ladder logic rung that uses a masked MOVE instruction to customize the data transfer from source to destination. The MVM instruction has three parameters as shown in figure 9 which are: the source, destination, and mask. All of them are addresses of the memory area. For the very given example here, the source is the 16 bits input at I:1/0 and the output is the 16 bits output at O:2/0 while the mask is the 16bits input at I:3/0. Before we are going to simulate this example, you should expect that the data will be transferred from source to destination based on the status of every bit in the mask data.
In the first test case shown in figure 10, the data to be transferred is ready at the source but nothing is transferred to the destination because the activating contact I:3/0 is not enabled. So let’s switch it on and see what is happening!
Now we enabled the activation switch at I:3/0 but still, data are not transferred from source to destination! Is there a problem in coding or logic? No, that is because the mask bits are set to off that is why bits of the source are not enabled to be transferred to the destination. Now, let us enable the masked bits and see what’s going on?
Yes! Now guys you can see all bits of the source have been transferred to the destination as long as their mates at the masked bits are enabled. But those who have their mates of bits at the mask are disabled and are still prohibited from being transferred. Like this, you can see friends how we can move data without control as when we use the MOVE instruction. In addition, you see how to control that data transfer by using mask bits as a filter. Do not forget, the move instruction can be utilized to move different data types, variables, memory sizes, and data blocks. So, it is a great tool for you as an experienced ladder logic programmer to flexibly move data between your data variables and memory location through long the program you are writing.
Guys! I would like to thank you for being here with me up till this point of our tutorial hoping you are really happy with it and seeing it is useful. Now guess what? I have a gift for you which is our next tutorial. It is not like every time we come up with another aspect in ladder logic to learn and enjoy practicing simulation. Now we come to the point that we should be counted as real ladder logic programmers because we have learned a lot and practiced more topics. So, it is time to practice a complete project string from reading the logic chart, understanding the logic narrative, and interpreting it to a complete successful ladder logic program. So next time will come up with a complete process with a logic diagram and requirements and practice together step by step. You can consider it as a great workshop in which you will apply all your knowledge base and what you have learned so far to take the responsibility as a PLC ladder logic programmer to convert the logic narrative and diagrams into a real ladder logic program. The work will include deciding the required logic components including switches, relays, inputs, outputs, digital and analog. Then will do a flow chart showing the logic flow based on which the program will be written. And lastly, the coded program will be applied to the plc simulator to verify the logic and make sure it is functioning correctly according to what has been requested at the beginning from the customer. So please be ready, make some revisions, and be there when we are going to learn by practicing a real project as in the real life and industry problems.
Matrices are an essential topic in different fields of study, especially in mathematics, where you have a bulk of data and want to organize, relate, transfer, and perform different operations on data in a better manner. We have studied a lot of types and operations on the matrices and have worked on different types with the help of MATLAB. Today, we are here to present the applications of the matrices in different fields of study to clarify the importance of this topic. So, have a look at the list of topics we are going to learn. Yet, first of all, I am going to describe what a matrix is.
In the fields of physics and mathematics, there is the use of different types of numbers in groups of various types. In order to organize the data into a manageable format, matrices are used. A matrix is a rectangular array of numbers that are enclosed by a square matrix (or, in some cases, parentheses).
The information about the numbers of rows and columns is called the order of matrices, and on the basis of this information, we can recognize different types of matrices. The types, in turn, are used in different applications because of their unique behavior. By changing the order of the matrix, the properties and working of the matrices changes according to the changes. Mostly, square matrices are used in different applications.
It is interesting to know that in the early days of matrices, these were considered arrays. With the passage of time, when they were involved more and more in different research and methodologies, matrices gained popularity. Because of the ease of usage, this popularity is not going to end. So, have a look at the different types of fields where matrices are used in different ways but before going into details, you must know, these fields are not only dependent on the matrices but the normal functioning of these fields include the usage of matrices in different ways.
As we have said earlier, matrices are used to deal with massive amounts of data better. The matrices that we have learned and seen till now are of very minimum order, and these are kept simple for the better concepts in easy ways, but in practice, we have seen that there are gigantic matrices with complex data in them, and at that point, it is difficult to solve and save them manually. Have a look at the different fields of practical life where matrices are used in a routine.
Data cryptography is an important department in data communication in which the encryption of the data is an important process. It is done by using different keys and codes to secure the message and communication in a better way. A large amount of data is sent and received by different parties, and the encryption techniques also require some other space as well. Matrixes are used to make sure that all the data and its codes are stored in a better way. These matrices
save the keys of the encrypted data to decrypt them on the receiving end and in this way, matrices play a key role in cryptography.
We all know that in wireless communication, usually air is used as the medium to send and receive messages from one point to the other. In this process, matrices are used to detect, extract, and process the information about the message that is to be delivered. Here are some other uses of matrices in this department:
Signal estimation and the detection of the problem during communication are done with the help of matrices.
Sensor array signal processing involves the matrices.
In the processing and representation of a digital image, matrices have a great role.
Radar signals
Underwater surveillance
With the help of matrices, wireless communication is done efficiently, and understanding the code becomes easy. Think about the case if the data of different queries are not used in the form of a matrix, then finding the data of a simple command would never be organized.
The use of matrices in the field of mathematics is not new to us. We all know that it is a basic concept in mathematics and a great variety of concepts of matrices are used in different ways while solving mathematical problems. One of the major use in mathematics is a solution of linear equations with the help of matrices. The complex and time taking equations can be easily solved with the help of rules of matrices in different ways.
In engineering and other related fields of mathematics, matrices are the basic concepts and it is used in different ways to make the working of the system better manner. We have seen different cases in which the matrix is used as the alternative method to find the unknown value because it is a more organized way and the great number of research resulted in different theorems and laws therefore, the long calculations are minimized to their result by simply using the theorems.
One of the amazing applications of matrices is in the form of computer graphics where the pictures and the graphics comprise pixels and the array of these pixels and points are arranged in the form of matrices for easy transformation and working. Overall, you can say that in computer graphics, each digital image is treated as a matrix. Therefore, different types of operations used in the matrices are applied to the graphics with great ease. Not only in the dimensions and the sizes but also for the colors of the images, matrices are used to store and reuse the values for the images and graphics. For example, in the CNN technique, different types of matrices are used. For the greyscale image, only a 2D image is used and if one wants to get the RBG system image, there is a need for a 3D matrix.
Gaming is one of the most important filed in graphics and when we talk about three-dimensional games, matrices are important there in order to alter the 3D space in different ways. For this purpose, if we use simple words, the conversions between the 2D and 3D matrices are used by different techniques, and therefore, we get the final output. Moreover, the quality of the result depends upon the way you use the data in different ways.
During the seismic survey in geology, matrices are used in a great way. For real-time surveys of different areas of common real problems such as mortality rate, population, the number of people in different areas of the world, and other specific counting related to real-life problems involve the use of matrices because it becomes easy to deal with great data using different operations on the data.
In different Information technology organizations, matrices are used to execute and search the different queries. The IT security system needs to have a secure way to deal with all the information and once saved, data is to be retrieved in an efficient way with the help of minimum commands. If the data is not present in the form of tables, or we should say, in the form of matrices, organizing, storing, retrieving, and dealing with the data will be like a nightmare.
It is one of the procedures in mathematics in which the values of collinear points are found with the help of matrices. If it seems simple at this time then you should think of the case where gigantic collinear points are found with the help of matrics with the help of different software and these points are in return used in different ways.
As we have said, matrices make the working of daily life data and complex calculations easy. We read different types of commands about the matrices when we were learning about their functioning and therefore, we can now use them in a simple program to prepare the code in which the matrix is used for the pre-allocation of the data in a simple way by using limited lines of codes. Trus, have a look at the code given below:
p=zeros(5)
p(1,:)= [ 3 6 2 8 7]
for i=3:4
p(i,:)=p(i-1,:) +1
end
In this code, we have used a simple function of zeros and used a loop to execute the whole instruction. Let us discuss both of them in detail:
Zeros Function
It is a pre-defined function of MATLAB that is used to make a null matrix of the required dimensions by using just a simple signal command. For the null matrices, there is the condition that the square matrix should be used.
For loop in Matrix
There are certain loops used in the MATLAB and with the help of this for loop, we just have to simply follow the syntax given below:
for index = value
statement
end
Here, the index value is the starting point where we want to start the matrix formation and the statement is the condition that we want to be executed while the formation of our matrix. If it is not clear right now in your mind, just have a look at the flow of the program.
First of all, we have used the zeros function to allocate the space in the memory according to the requirement. We have used the square matrix which has the order of 5 by 5.
I wanted to pre-allocate the values in the matrix row after the row therefore, we simply changed the values of the matrix p formed before from 0 to other values defined by us. If you are not familiar with this function, have a look at the notation given below:
p(a,b)
Where,
a=number of row
b=number of column
As we did not want to alter any value in the columns so we have used a colon in its place.
By using the for loops, we have specified that the index value starts from 3 and ends and 4.
In the next step, we are using these index values and specifying to MATLAB that we want to change the values of the 3rd and 4th rows only and the program ends.
MATLAB does this task step by step and changes the null or zero values of the matrix p into the required pre-allocated values in the matrix.
For the best concepts, we have changed the values of just two rows and the other matrix remains the same.
Larger versions of these kinds of procedures are used in diverse ways to recognize, store, and use the data in a better way, and with the help of this short program, we have seen a glimpse of a real-time application in which a matrix can be used to pre-allocate the different values and people can have benefit from it.
Trus, today, we have learned a lot about matrices and their applications. We have read great information about matrices in the past lectures and it was quite interesting to know how can you use these basic pieces of information in a better way and how people are working on the matrices to make their daily tasks easy during their professional life. We have seen different departments where matrices are making the work easy and more efficient. Most of them can not work without using matrices. Moreover, one must have the idea that many times we use matrices in our daily life unintentionally. As we have said earlier, 3D games require the involvement of a matrix. So, when your child is playing the game, he or she is enjoying the application of the matrices without knowing it. In the end, the small program was helpful to understand how little programs and the working of matrices are helpful to perform different tasks automatically.
Hello learners. Welcome to The Engineering Projects. We all know that matrices have been used in the engineering field for a long time, and they have a vital role in the calculation of different data. Therefore, we are learning about some very special kinds of matrices that are usually introduced to engineers at a higher level. Till now, we have seen some general operations on matrices and also examined the special kinds of matrices. Yet, today, we are moving a step forward and learning about some complex types of matrices that require strong basic concepts. So, have a glimpse at the topics that you are going to learn, and then, we’ll start practicing.
What is a matrix?
What are the different types of matrices that are less common?
How can we implement some interesting commands in MATLAB?
What is the procedure for dealing with complex equations in MATLAB?
First of all, it is recommended to learn about the introduction of the matrix. A matrix has different elements in it with different sequences, and we define it as:
“A matrix is a rectangular array in which different types of elements in the different sequences are present, and all the elements are enclosed in a long bracket that is usually a square bracket.”
The sequence and the values of the matrices are important, and the collection of horizontal lines is called a row. On the other hand, the vertical entries are collectively called columns. To find the difference in the types of matrices, it is important to know that the basic kinds of matrices are square matrix and rectangular matrix. Most of the matrices that we are going to discuss here will be square matrices.
Depending upon different parameters in matrices, these are divided into different types and groups. In a square matrix, the numbers of rows and columns are equal to each other, and in a rectangular matrix, the numbers of rows and columns are never equal. You will observe different parameters on the basis of which these matrices are recognized, and then the behavior of each of them is examined. So have a look at these types.
We all know that boolean numbers mean two conditions only, that are, zero and one. So, the boolean matrix is the type of matrix in which only zero and one value are used, and other values are never involved. The order of the matrix may be anything, but the entries must be either zero or one.
One thing that must be kept in mind is that the matrix will surely have these values in a non-specific pattern and it never has only zero or only one. There must be one and zero of each type. We are clearing it because some other types, such as singular matrix, identity matrix, null matrix, and scalar matrix, also involve zero and one, but in a specific manner.
Boolean numbers and conditions are used in almost every field of mathematics, and therefore, this matrix is also used in different ways in such fields. With the help of a matrix, it becomes easy to deal with a large number of data points at once. The example we have shown here has a small size. Yet, when the boolean matrix is used in practical life, we use a bulk of matrices with greater sizes.
In the previous section, we learned that a transpose of the matrix is obtained when the rows and columns, along with the entries, are interchanged with each other. Keeping this concept in mind, we can define this type of matrix as
A matrix A is called an orthogonal matrix if and only if the multiplication of the matrix A with the transpose of itself provides us with the identity matrix.
If you are new to the identity matrix, then you must know that an identity matrix is one that contains only value 1 in its diagonal and all the entries other than the diagonal are zero.
As we have read about the orthogonal matrices, they remind us of the inverse of the matrix. It is interesting to know that there exists the inverse of a matrix that, when multiplied with the original matrix, delivers us the identity matrix. We hope you remember that an identity matrix is a type of matrix that always has the value 1 in the diagonal elements and zero in all the remaining elements. So, if we are taking matrix A, then for the inverse matrix, we can say:
A.AT= I
In this way, if we have the value of A and want to know the inverse of it, we use the following equation:
AT= I/A
So, in this way, we have observed that no matter if the inverse of the matrix is multiplied with the original matrix or vice versa, we get the identity matrix. This condition is somehow special because the multiplication of the matrix is a more complex operation than addition and subtraction, yet here we are using the rules of the dot product. There is another way to find the inverse of a matrix with the help of a formula that states that the inverse of a matrix A is equal to the determinant of matrix A with an adjoint of A.
There are certain conditions for the existence of a square matrix:
A matrix has the inverse only if it is a square matrix.
If the determinant of the matrix is equal to zero, then there is no need to find the adjoint of that matrix because the inverse does not exist for that matrix.
It is not always necessary that in the inverse of a matrix, the values are reciprocal of the original matrix. The values may also be changed, and by dot multiplication, we can get the identity matrix.
Here is another interesting type of matrix in which all the values show the probability values. We know that the probability values are so small that they are less than one and have fractional values or in the form of points less than one. So, the stochastic matrix has all the probability values as its elements.
You can see all the values are less than one because the probability is usually in the form of such small numbers. If any of the values is greater, then it is not a stochastic matrix.
This is a less common type of matrix in which Ak = O, that is, for every power of the matrix, we get a null matrix (the one with all the values equal to zero). There are two conditions that must be fulfilled in this type:
The matrix A must be square.
We get a null matrix every time we apply any power to matrix A, which is a natural number.
For example, when we take the square of each value of A, we get the null matrix. It is a less common type of matrix, but at a higher level of calculations, it has its applications.
It is a type of uncommon matrix that provides us with a matrix equal to itself when any power is applied to it greater than 2. That is, An = A where the value of n is always equal to or greater than 2. Usually, it has been noticed that if the square of the matrix A is equal to itself, then there is no need to check further because the result remains the same for any number greater than 2. You can take it as homework and find examples of such matrices by yourself.
It seems like you have learned a lot about the special kinds of matrices. When we talk about MATLAB, we have observed that there are different MATLAB commands that are not related directly to the matrices yet are used to make the functioning of a group of numbers and matrices easier and more effective in some cases. So, have a look at some of the commands.
sr# |
Command |
Description |
1 |
inv(A) |
This provides us with the inverse of the matrix A. |
2 |
s,t, complex(s,t) |
It is the way to introduce a complex number in MATLAB. It produces a complex equation with s as a real number and t as an imaginary number. |
3 |
real(A) |
With the help of this command, you can find the real part of the equation saved as equation A. |
4 |
imag(A) |
By using this command, you can easily encounter the real part of the equation saved as equation A. |
5 |
abs(A) |
This command will show us the absolute value of the matrix A. |
6 |
angle(A) |
To find the angle of equation A, we use this command. |
We all know about complex numbers and have also used them in the matrices when we were talking about hermitian metrics. A special kind of function in MATLAB is the “complex” function, which is used to make the complex equation. So have a look at the step-by-step procedure to perform the complex equation in MATLAB.
Hit the start button of MATLAB.
Go to the command window.
Start by writing the following command.
a=3
w=3
It will provide us with two numbers that we will use in the complex function. We are naming this equation ComplexEqaution, and the command to perform this is
ComplexEqaution=complex(a,w)
Press the enter button.
Now, using this equation, we can also find the real and imaginary parts of the equation using different commands. For real numbers, we are writing:
real(ComplexEqaution)
It will give us the real part of the equation. Similarly, write the following command for the imaginary number:
imag(ComplexEqaution)
Similarly, to obtain the absolute value of the equation we have just made, we are using the required command.
abs(ComplexEqaution)
Finally, to find the angle of the equation, we are using its command.
angle(ComplexEqaution)
Now, to perform the inverse of a matrix, we are going to introduce the matrix first. So, write the following command:
B=[1 55 2 7; 4 5 2 8; 4 99 1 6; 3 8 4 1]
The command for this purpose is:
InversofMatrix= inv(B)
If you are confused about the absolute value of the complex equation, then you must realize that complex numbers are present in the plane or the coordinates of the system, and the absolute value of the complex numbers is defined as the total distance between the origin of the complex number (where the plane is (0,0)) and the complex plane (a,b). The procedure to do so is a little bit complex if we solve it theoretically, but with the help of MATLAB, this can be done with the help of a simple command and all the control in your hand. You should practice more with all these commands by using your own values in the matrix with a different sequence. Once you have followed all the instructions given above, the output at your MATLAB command window should be like the images given next:
So, in this way, we have gotten rid of the long and error-prone calculations, and by using simple commands, we have simply applied the formula of inverse, and in this way, we have not had to find the adjoint and determinant of the matrix A.
Consequently, we had a little bit of a complex yet interesting lecture today on matrix, in which we defined it first for a solid foundation of the concept. After that, there were different types of matrices that are less common but have interesting patterns of the elements in which the values and positions are important to define the type of matrix. Moreover, we have seen some interesting commands in MATLAB to perform the operations of complex equations and also implement them all practically. In the next lecture, you are going to learn the amazing features and applications of MATLAB in different aspects of the study.