Hello people! Welcome to an exciting series on The Engineering Projects in which we are studying MATLAB. This series is not just organized just for technical people but for anyone with a basic knowledge of programming and mathematics. We will define each and every concept from scratch and you are not going to bore in any lesson because you will learn new and exciting things in every lecture. If you are wondering what MATLAB can do and what some of its features make it the best calculator and it performs complex calculations in just seconds. You will also see some other parts of MATLAB that make it the best. Have a look at the list of the topics that we are going to discuss with you:
What is MATLAB?
What are some basic features of MATLAB?
If I need to have some prerequisites in MATLAB?
What is an example of a simple task in this software?
How different disciplines of mathematics are getting benefits with MATLAB?
First of all, let us see the introduction of MATLAB and after that, we will move towards some different concepts.
MATLAB is a programming language specially designed for engineers and mathematicians and the company that leads the production, maintenance, and other operations of this software. It is interesting to note that MATLAB takes its name because it is a matrix laboratory and is called so by using the combination of both words. It has different parts such as Simulink which is the graphical window helping electrical and electronic engineers to solve different types of circuits in an efficient way without the need for real components. So, we can say that:
“MATLAB is a specialized programming language introduced by MathWorks for the students of engineering and mathematics and has the multi-windows for different types of operations.”
As we said, this software is a specialized laboratory of matrices and we see a hundred different operations that are specialized for the matrices but are also implemented on different related concepts. The LINPACK and EISPACK did the initial development of this language but we see that MathWorks has the main authority and is working more and more in this field.
The best thing about MATLAB is its multi-paradigm nature that attracts every type of users.
such as functional users, Object-oriented programming experts, and others. Here is the image that describes the multi-paradigm nature of MATLAB.
In this way, you can conclude that MATLAB is used in two ways:
Environment
Programming Language
But in general, we will use the word “software” throughout this course for the sake of simplicity because most of the students are unaware of different technical terms.
You must know, the operations in the MATLAB are stored in the form of matrices no matter if you are using the string, character type, or variable type, these are stored in the form of matrices in MATLAB and in this way, by using properties of matrices, MATLAB performs almost all types of operations by using these matrices.
To understand the importance and usage of MATLAB, we are discussing a brief description of the system inside MATLAB you are going to enjoy it because it has some extraordinary features that make your boring practical work easy and fluent. For the sake of simplicity and a clear concept, we can divide the MATLAB system into five parts which are shown in the image given below:
If you are not familiar with every part, do not worry because I am going to express it in very simple words. There is no need to memorize each of them, you just have to simply put these words into your mind and decide which type of feature you are going to use most of the time when you will discoverMATLAB in detail.
The first thing that must be kept in mind is the basic introduction to MATLAB. It is a development environment that helps programmers to get the desired result in a better way. It has a unique set of environment that enables the users to operate MATLAB functions and files that is usually pre-installed in MATLAB. It has the following features:
A desktop
Command window
A command history
An editor
A debugger
Different browsers
When you start MATLAB, you will be fetched by all of these without searching much. Some of these are just a click away from the main window and you can use them simultaneously.
This is a magical library for every type of engineer and for pure mathematicians. The pre-defined functions are there for you through which you can use trigonometric functions such as sin, cosine, Bessel function, fast Fourier transform, and other functions that help the users get rid of long derivation and calculations. Instead, they simply use the function library and pre-defined functions in an easy way. The main purpose of these libraries is to ignore the long calculations and focus on the working and results of these functions. Usually, people learn the long derivations in the theoretical part and get practice about the same topic in MATLAB by ignoring the long calculations all the time when they solve the problems.
MATLAB is a great programming language that gives users to use it for a great number of tasks. No matter if you have a simple and easy task to perform through the program or if you have a complex program to perform on MATLAB. All the programs are easy to perform and if a person has an understanding of this superb language, you can easily make complex programs in an easy way because MATLAB knows best what you want.
This language was developed by the owners of MATLAB and it is closely related to the language that we use in our daily life. In this way, we get a more user-friendly language that is easily understandable by non-technical people as well if they pay to heed the basic concepts.
When I started to learn MATLAB, I wanted to perform the signals in this fantastic development environment and I was amazed to see the versatility of the programming languaging and the options and facilities it provides to highlight the results in the best way.
For the best data visualization of data, MATLAB has a three-dimensional and two-dimensional high-level structure that provides the best and most impressive representation of data in the best manner.
MATLAB is not just limited to the specific language but it gives you the independence to use multi-languages on ti such as FORTRAN and C. If you are not familiar with these two, do not worry because MATLAB is not just limited to these two but you can do many useful tasks with this versatile software.
As we are discussing from the beginning, this environment is for technical people such as engineers, and therefore, we assume that if you are starting to learn this fantastic software you must have the following concepts in your mind:
Little knowledge of programming. At least you must know what is programming and why we are doing this.
What is a statement?
How can you declare the variables and constants and what is the purpose to do so?
Plotting of graphs and other visual pieces of information like this.
Do not worry if you do not have all these concepts or if you are new to the programming procedures because we are going to discuss all the things in an easy and brief way so that the new users understand all the concepts and the technical people may revise their concepts. Sometimes, you do not have to have all of these concepts in mind when you have the task of simple or basic level but I think it becomes fun when you start using MATLAB and after that, you try to have more and more practice to get the amazing results on this user-friendly software.
Are you excited about using MATLAB? If yes then let’s talk about a simple and easy command on MATLAB to show you a glance at the working and the screen of MATLAB. I am not going to explain each and every part of this command because you will learn a lot about it in the upcoming lectures. For this, if you have the basic concept of matrices, you will get an idea of what is going on on the screen MATLAB. So, let’s have a look at the simple addition of two matrices.
In the simplest command that we have used above, we have simply declared two matrices with the names A and B. It is important to store the values of matrices in the variables to use them later. You are going to use these values for the addition with the help of easy command. You must know, you can use any name of the variable instead of A and B but usually, we utilize these variables because they are simple to understand.
There is no need to explain why MATLAB is important in the engineering field because it is specialized for engineers and all the features of this marvelous software are designed with keeping engineers in mind especially when we talk about electrical and electronic engineers. Usually, MATLAB is easy to use for technical people because, during their educational period, they use different types of software and languages and know how to deal with such environments for the sake of complex tasks and calculations in engineering.
Many students of engineers are providing the best ideas about their fresh ideas in engineering concepts through MATLAB without spending a large amount on experimentation, they can easily propose their ideas with the help of simulations in MATLAB.
Usually, the instruments have errors in the calculation and do not provide 100 % accurate results but when we perform the simulation with software such as MATLAB, we get the ideal results all the time without any issues with accuracy.
When talking about the applications of MATLAB in the field other than engineering, you will find economics one of the most important because of its built-in capabilities to work with time series data, computation techniques, presentation of the result with the help of visualizations, and some other features that are up to mark and makes the study and teaching of economic’s in a better way.
The graphical representation of results in different ways makes this environment more user-friendly to even those who are less aware of the technical stuff and software. So, it becomes easy to understand the concepts with the help of this amazing environment.
When we are dealing with statistics, we can use MATLAB for different types of tasks such as descriptive or inferential and people related to this field find it useful to use MATLAB instead of using the typical manual methods or other software because these all are time taking and have some limitations.
Trus, MATLAB is a powerful programming language that is used in the programming environment developed by different companies and maintained by Mathworks for engineers. But, other disciplines such as economics and statistics also have applications in MATLAB because all of them are related to mathematics. MATLAB is developed with the help of concepts of matrices and therefore, it also involves the user-friendly functions and commands of matrices that are extremely useful in a great number of departments. It was the introductory lecture on MATLAB and you will learn more about it in the next session where you will be directed to install MATLAB in the best way with all the required information. This course is equally useful for the beginners and the persons with intermediate concepts about the programming language because the revision and tips will be there for you at every steps and you are not going to bore throughout this series.
A low-literate audience can nevertheless have their voices heard and their questions answered by using an IVR system, as has been proven time and time again. However, achieving such aims in a development setting calls for a cheap system that welcomes input from various parties. RASP-IVR is an inexpensive IVR system that operates on a PI 4 and a local Global System for Mobile Communications modem. RASP-IVR was designed as an open-source, community-driven solution. It's unusual to find a customer-focused company that still uses human operators rather than an interactive voice response system. Credit card companies typically have IVR systems that can be used to make payments or file fraud reports. Airlines use elaborate IVR systems to schedule flights and check their current status. To facilitate medication refills, pharmacies implement interactive voice response systems. Furthermore, IVRs are widely used for forwarding calls to other extensions and providing directory assistance.
Enterprises of all sizes have adopted IVR technology due to its cost savings over using actual, flesh-and-blood staff. The number of callers who desire to speak with a human indicates an IVR system's success. As the percentage drops, the system becomes more efficient. Of course, some IVRs will never let you bypass the system and talk to a human being. However, that's frowned upon even by IVR advocates. As most people know, Raspberry Pi is a development board that packs a fair amount of processing power into a little package (about the size of a palm). When coupled with python's adaptability, this might lead to the creation of a wide variety of useful but diminutive devices. I recently had to construct an interactive voice response system using a Raspberry Pi, which essentially entails dialing phone numbers, sending messages, and receiving DTMF inputs from the recipient when they pick up the phone.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Jumper Wires | Amazon | Buy Now | |
2 | Raspberry Pi 4 | Amazon | Buy Now |
Pi 4
SIM800L GSM Module
2G SIM Card (Airtel)
Aux Cable
LM2596 Buck Converter Module
USB to TTL Converter
12V 2A Adapter
Perf Board
Berg Sticks
Connecting wires
Soldering Kit
Computer and phone systems can be integrated into various ways, and IVR systems are one such way (CTI). Key tones are the most common way a phone can exchange data with a computer. Dual-tone multi-frequency frequency is what you get. A telephone's number pad emits a low and high-frequency tone. A "1" can be generated in a 697-Hz tone or a 1209-Hz tone, both of which are recognized by the PSTN as the numeral 1. For a computer to interpret the DTMF frequency produced by a phone, specialized hardware known as a telephony circuit or telephony board is required. Using a telephony board to connect a computer to a phone line and some low-cost IVR software, it is possible to create a rudimentary IVR system. The IVR program lets you record messages and menu items that callers can navigate using their phone keypads.
Speech-recognition software is a part of more sophisticated IVR systems, enabling callers to interact with computers via voice commands. The technology behind speech recognition is now advanced enough to comprehend things like full names and long series of digits. Text-to-speech software can be used on the receiving end to fully automate a firm's outgoing telephone calls. To better serve customers, computers may now generate personalized text to answer their inquiries, such as financial statements or flight times, and have an automatic voice read to them. Voice extendable mark-up language is a popular foundation for many cutting-edge interactive voice response systems today.
The "RASP-IVR" moniker comes from the fact that it was created on the inexpensive Linux-based single-board computer known as a raspberry pi. The operating system is built on RASPBX, with several additions and modifications to improve compatibility for interactive voice response (IVR) use. Model 4 Raspberry Pi and GSM mobile phone modem make up the system. An Asterisk server is connected to the GSM modem via an interface. FreePBX is a web-based interface for managing an Asterisk server, allowing users to set up and modify IVR menus and VoIP settings. Using open-source libraries, we've written scripts to bring RASPBX's functionality for Voice over IP (VoIP), short messaging service, and localized SIP transfers to a broader.
Depending on the situation, the Asterisk domain server can route the incoming GSM call over a local or worldwide VoIP network. The VoIP communications can be directed to different extensions based on the client's dial input. They can be answered from any desktop or mobile device with a domestic SIP account and a SIP client like Zoiper. Furthermore, the VoIP conversation can be routed to third-party platforms like Twillio to use their cloud-based solutions like speech-to-text engines or cloud-based storage. In contrast, RASP-IVR requires no external resources, making it ideal for collaborative innovation or limited rollouts.
The cost of using an API to make phone calls from a Raspberry Pi can add up quickly. You can use python and Raspberry Pi to make inexpensive phone calls using several different service providers, including Twilio. These solutions are fantastic; however, the price has two significant drawbacks. Almost wherever you go, you'll be charged by the minute, which goes for both outgoing and incoming communications. You might not think this is significant, but if you make more than a hundred calls daily, you'll soon realize how much it costs. The second issue is buying and managing a different cellphone number from which to make these calls. You cannot use an existing number because these are all made up, and depending on your area, you may have to pay more to get a number that works in your nation.
After researching the rates of several API-based telephone conversation services, it became evident that the cheapest option is to use a Gsm technology like SIM800L with Pi to place calls through a network service provider like Airtel. To that aim, we'll connect a SIM800L module to a Raspberry Pi so we can send text messages and make phone calls automatically.
As 5G and the IoT become increasingly popular, numerous innovative new GSM modules have been released that are compatible with 5G networks while using less energy. But I had the bright notion of employing a ubiquitous and inexpensive commodity to purchase at any nearby hobby store. So, we put the popular SIM800L and the Ai-thinking A9 through their paces. Even when just powered by my laptop's USB port, the artificial intelligent-thinker A9 Gsm modem proved completely reliable and responsive right from the get-go. However, the primary issue was that the in-line voice input interface did not operate very well, and the artificial intelligent Thinker A9 Gsm modem did not enable DTMF recognition. So, I switched to the SIM800L Global System for Mobile communications Modem, a power-hungry beast that, if fed enough juice, proved ideal for this task. There is no need for expensive external DTMF hardware because it has both in-line audio for playing automated voice and built-in DTMF detection.
The SIM800L is only compatible with 2G networks, not 3G or 4G. Only Airtel and BSNL provide 2G services in this area. Therefore, get an Airtel SIM card or use one we already have. After purchasing a new Airtel subscriber identity module, card, I activated it on my cell phone and began using it with my SIM800L.
Complete schematics for a Raspberry Pi-based telephone and message system are provided below. It's clear how simple it is to draw connections between ideas.
The method by which the SIM800L module is supplied with electricity is crucial here. Within a voltage range of 3.7V to 4.2V, the SIM800L chip functioned. The optimum working voltage is close to 4V. For the SIM800L module, we needed to reduce the adapter's 12V 2A output to 4V; thus, we utilized an LM2596 Buck converter. Thicker, shorter wires are preferable when linking the buck component to the SIM800L so that the module can easily handle the high current. When powered, if the element detects improper power connections, it will reset and send invalid data through the serial port. You'll need a 12V 2A adapter to power the SIM800L module, and you should use bulky wires just to carry a lot of current without causing too much resistance. Connecting a fully loaded Lithium battery across the SIM800L module's Vcc and Ground pins should resolve any power difficulties.
Those unfamiliar with the jargon of electronics engineering know that "AT Commands" are what we use to talk to the SIM800L module. Calling, texting, and keypress detection are just a few of the many functions that may be accomplished with AT commands. This tutorial will use Py from RPi to transmit these AT instructions to the Global System for Mobile Communications SIM800L module. Connecting the SIM800L module's Rx and Tx pins to the Raspberry Pi's USB port required a universal serial bus to TTL converter.
Through its MIC+ and microphone- pins, the SIM800L component supports mic input. Any audio information sent to these pins after the call has been placed will play on the call recipient's phone. In our scenario, we have to play recorded audio from the Rpi; however, these go pins are primarily designed to connect a microphone. To hear it on the GSM component, we must convert our audio output from the RPi through the 3.5mm port, known as line-out audio, to mic-level audio. You might construct a line-to-mic converter circuit to complete this task professionally. Still, I connected the two devices and set the volume level on the Raspberry Pi to barely two decibels. I had no trouble getting it to function this way.
I assembled the entire circuit on the perf board, ensuring the voltage connectors got enough lead to offer low-resistance contact. This is how my board appears after soldering. Since the LM2596 is an adjustable buck converter, ensure you use the onboard trim pot to set the voltage output to 4 Volts before using it. Anything above 4.2 volts can permanently damage the SIM800L component.
Simply turn on the circuit and attach the Cell phone card when you get here. Once more, confirm that the SIM card is inserted correctly and that the antenna is securely fastened. If all is done correctly, you should see the SIM800L board's inbuilt led flashing once every three seconds. As a result, the SIM800L module may create a network using our SIM card. This guarantees the appropriate Operation of our powering circuit. Now that the board is connected, we can build our Python code without an RPi.
You may find the entire Python script for the RPi interactive voice response system at the end of this tutorial. Due to the size of the code, it is not practical to detail every step. It is incorporated with comments and procedures to do reading and comprehending the code easier. Importing the necessary header files allows us to launch the program. We used the serial module to enable the serial connection between the Raspberry Pi and SIM800L components. The pygame software is employed to play audio, in this case, audio files. We also have the time component to cause delays, so that's something. You don't need to install anything new because the Buster OS comes pre-installed with all three packages.
import serial #for serial communication with GSM SIM800L
import time
import pygame #to play music
Using this method, an AT command can be sent from a PI computer to a SIM800L device and then received in return. All AT commands transmitted to SIM800L must be written in ASCII and conclude with the character "rn." Before sending them to SIM800L, this method appends the character "rn" to all our AT instructions and transforms them into the ASCII character set. Once the response has been read, it decodes the ASCII data so we may utilize them in our code.
def SIM800(command):
AT_command = command + "\r\n"
ser.write(str(AT_command).encode('ascii'))
time.sleep(1)
if ser.inWaiting() > 0:
echo = ser.readline() #waste the echo
response_byte = ser.readline()
response_str = response_byte.decode('ascii')
return (response_str)
else:
return ("ERROR")
This function is quite similar to the one before, except instead of sending a value to the SIM800 component, it just awaits a response from the SIM800L module. As a result, it returns the answer when it receives one.
def wait_for_SIM800():
echo = ser.readline() # waste the echo
response_byte = ser.readline()
response_str = response_byte.decode('ascii')
return (response_str)
The GSM modem is ready for interactive voice response operations after being initialized. Before sending particular AT instructions to the Gsm modem to activate the message and DTMF receiver modes, it sends an "AT" to check for the module and waits for an "OK" response. In addition, it turns off all alerts so that we won't be distracted throughout a call by texting notifications.
def Init_GSM():
if "OK" in SIM800("AT"):
if ("OK" in (SIM800("AT+CLCC=1"))) and ("OK" in (SIM800("AT+DDET=1"))) and ("OK" in (SIM800("AT+CNMI =0,0,0,0,0"))) and ("OK" in (SIM800("AT+CMGF=1"))) and ("OK" in (SIM800("AT+CSMP=17,167,0,0"))): # enble DTMF / disable notifications
print("SIM800 Module -> Active and Ready")
else:
print("------->ERROR -> SIM800 Module not found")
After answering the call, the following method is employed to play the audio files. We have recorded audio files like "cancel.wav," "confirm.wav," and "intro.wav" stored. Following the user's keyboard answer, we must play every one of these files. We can use the play audio function to play any audio file of our choosing. Assume that your Python script is stored within the same folder as these audio files.
def play_wav(file_name):
pygame.mixer.init(8000)
pygame.mixer.music.load(file_name)
pygame.mixer.music.play()
#while pygame.mixer.music.get_busy() == True:
#continue
The software's most crucial feature is this one. It obtains the mobile number that has to be called and offers the callback for that session. Any response, such as NOT REACHABLE, CALL REJECTED, CONFIRMED, CANCELED, etc., can be given in return. The function calls a specified phone number using AT instructions and then plays recorded audio. The system then listens for the caller's DTMF reply and, depending on that reaction, plays the relevant recorded voice before informing us of the caller's choice. The method will also respond with that information if the caller declines the call or cannot be reached.
def Call_response_for (phone_number):
AT_call = "ATD" + phone_number + ";"
response = "NONE"
time.sleep(1)
ser.flushInput() #clear serial data in buffer if any
if ("OK" in (SIM800(AT_call))) and (",2," in (wait_for_SIM800())) and (",3," in (wait_for_SIM800())):
print("RINGING...->", phone_number)
call_status = wait_for_SIM800()
if "1,0,0,0,0" in call_status:
print("**ANSWERED**")
ser.flushInput()
play_wav("intro.wav")
time.sleep(0.5)
dtmf_response = "start_over"
while dtmf_response == "start_over":
play_wav("press_request.wav")
time.sleep(1)
dtmf_response = wait_for_SIM800()
if "+DTMF: 1" in dtmf_response:
play_wav("confirmed.wav")
response = "CONFIRMED"
hang = SIM800("ATH")
break
if "+DTMF: 2" in dtmf_response:
play_wav("canceled.wav")
response = "CANCELED"
hang = SIM800("ATH")
break
if "+DTMF: 9" in dtmf_response:
play_wav("callback_response.wav")
response = "REQ_CALLBACK"
hang = SIM800("ATH")
break
if "+DTMF: 0" in dtmf_response:
dtmf_response = "start_over"
continue
if "+DTMF: " in dtmf_response:
play_wav("invalid_input.wav")
dtmf_response = "start_over"
continue
else:
response = "REJECTED_AFTER_ANSWERING"
break
else:
#print("REJECTED")
response = "CALL_REJECTED"
hang = SIM800("ATH")
time.sleep(1)
#ser.flushInput()
else:
#print("NOT_REACHABLE")
response = "NOT_REACHABLE"
hang = SIM800("ATH")
time.sleep(1)
#ser.flushInput()
ser.flushInput()
return (response)
The send message method in this program enables us to send messages in addition to making calls and receiving responses. The message is sent after it receives both the text and the participant's mobile number.
def send_message(message, recipient):
ser.write(b'AT+CMGS="' + recipient.encode() + b'"\r')
time.sleep(0.5)
ser.write(message.encode() + b"\r")
time.sleep(0.5)
ser.write(bytes([26]))
time.sleep(0.5)
print ("Message sent to customer")
time.sleep(2)
ser.flushInput() # clear serial data in buffer if any
The very last method I created for this project allows you to figure out who is calling by their phone number. Some people might attempt to call back to this line because this SIM card will make calls to new persons. If so, you can use this function to see which line is making the call, send them a message, or create a follow-up call if necessary.
def incoming_call():
while ser.in_waiting: #if I have something in the serial monitor
print ("%%Wait got something in the buffer")
ser.flushInput()
response = SIM800("ATH") #cut the incoming call
if "+CLCC" in response:
cus_phone = response[21:31]
print("%%Incoming Phone call detect from ->", cus_phone)
return (cus_phone)
else:
print("Nope its something else")
return "0"
return "0"
It's time to create the main program, in which we will employ all of these functions to accomplish something nice now that all of them have been defined. The customer id and phone number are now being hard-coded for demonstration purposes, but you can obtain them using a Shopify API request or retrieve them from a spreadsheet as needed. For testing purposes, we use the customer's identity, "AISHA," and phone number, "9877XXXXXX."
cus_name = "Aisha"
cus_phone = "968837XXXX"
We will begin a serial conversation with a 15-second delay at 9600 baud speeds within the main endless while loop block. Considering that various SIM800L components may operate at a different baud rate, ensure that you enter the correct COM folder and baud rate in this field.
ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=15) # timeout affects call duration and waiting for response currently 30sec
print("Established communication with", ser.name)
After making the call and getting the necessary reply from the consumer, we will send the recipient a text based on their response. For instance, if the answer is validated, we can send a message about it. Likewise, we can alter the message if the client provides a different reply.
response = Call_response_for(cus_phone) #place a call and get response from customer
print ("Response from customer => ", response)
if response == "CONFIRMED":
text_message = "Hi " + cus_name + ". Your booking has been confirmed.Thank you. -Circuitdigest"
send_message(text_message, cus_phone)
if response == "CANCELED": # if the response was to cancel
text_message = "Hi " + cus_name +. "Sorry that you have decided to cancel your booking. If you canceled by mistake, kindly contact us by phone. -Circuitdigest"
send_message(text_message, cus_phone)
if ((response == "CALL_REJECTED") or (response == "REJECTED_AFTER_ANSWERING")): # if the response was rejected
text_message = "Hi " + cus_name + ". We from circuitdigest.com have been trying to reach you, to confirm your
booking. You will receive another call within a few minutes, and we kindly request you answer it. Thank you"
send_message(text_message, cus_phone)
Just double-check the connectors and turn on the GSM component board and RPi. Make that the appropriate COM port is listed in the code before running the application; in my instance, it was "/dev/ttyUSB0." After that, check that the sound is set to atrioventricular ( av ) node jack by right-clicking on the loudspeaker icon and that the audio level is low.
Simply alter the contact number and client name in the following step to your liking, or modify the program to retrieve the information from an excel spreadsheet or cloud Application programming interface, and our automated interactive voice response is ready to go.
The application will dial the specified number and listen for DTMF responses. Additionally, it will play relevant sound clips and transmit a text message dependent on the recipient's response. Below are a few sample messages that I obtained on my cellphone.
The audio tracks and texts can easily be changed to meet your application's needs. I hope the assignment was enjoyable for you and that you learned something.
Call routing within a company is among the most popular uses of an interactive voice response system. Previously, you would employ a switchboard controller or receptionist to answer all callers and direct callers to the appropriate line. When answering customer calls, an interactive voice response system is beneficial. A caller may be given a menu of choices and inquiries about the system's type of call. If possible, the system will respond to the more typical inquiries while referring the less common questions to qualified experts.
Interactive voice response systems are excellent for getting detailed, current info from databases—for instance, movie times. On a significant database, the weekly movie lists are updated. The cinema theater's website can also be filled with information from these databases. When making a call to the cinema, the caller can use the keypad or voice instructions to search the database for movie timings. The same technology can be used to check account balances, evaluate the latest credit card payments, check flight times, refill medicines at a pharmacy, plan auto maintenance, and register for university classes. The list is endless.
Interactive voice response systems are helpful for sales as well. A sales department can create an interactive voice response order form, enabling callers to complete it on their phone's keyboard. When the form is finished, the computer can send a copy to a sales team representative through fax or email. The sales department could also use the IVR as a virtual flyer that highlights the characteristics of a good or service and offers customers the chance to speak with a live agent at any time.
Marketing teams and election pollsters can use the interactive voice response systems' outgoing call functions. A political campaign may send a voicemail message with a phone-in survey for voters to complete. An advertiser may determine whether a buyer is interested in his goods or services. They might press a key to speak with a sales representative if interested in the advertiser's computerized pitch.
Electronic alert systems may also be combined with interactive voice response systems. Let's assume that your company has worldwide workers working from home. Worker contact details, such as home phone numbers, mobile phone numbers, fax numbers, pager numbers, email addresses, etc., can be coded into the interactive voice response system. The IVR prog will use every form of contact until a connection is established if a call has to be directed to that worker.
Transcribing health records is an intriguing application of interactive voice response technology. Currently, doctors record their patient notes and submit the audio to a service that performs medical transcription. However, a doctor may contact the interactive voice response system, record his notes, and have a filed transcript emailed to their office thanks to advanced speech recognition software.
The creators have been collaborating with a few Rwandan health industry partners. The developers want to create solutions that will expand the coverage and reach of the partners' already-existing face-to-face operations. Interactive voice response can extend services to clients who cannot travel to existing facilities. Interestingly, one non-partner frequently visits remote communities and considers the interactive voice response as a tool for drawing people to these outreach efforts. By providing automated processes that operate outside of regular business hours or by gathering and analyzing customer data, the IVR can lessen the employees' workload. One partner will use this function to computerize donor-sponsor reports. In the opinion of one of the partners, the interactive voice response is a small step towards a more significant switch from hard copies to soft copies. Before conversing with a counselor, the web service might pull up the patient's EHR using information gathered by the IVR synchronized with the hard copy to soft copy system and the interactive voice response. After the call, a text message is sent to the customer, and another is sent to the dispatch center that is most convenient for the client.
Using its speech and texting platforms, the RASP-interactive voice response system opens the door to creating unique apps that can assist with contextually relevant difficulties. Features including automated call rerouting, user-selected content, caller audio content recording, text message-based engagement, data collecting, and tailored resources that can be accessed on caller ID are all made possible by the RASP-Interactive voice response system.
We acknowledge, however, that interactive voice response-based solutions, like all technology, must be developed to enhance current human development efforts. The following are IVR-based systems' benefits, although certain limitations are covered below.
A voice-only system is more appealing to people with limited literacy
than texting or internet-based apps.
To use an IVR system, users just dial a number on their readily available cell phone, as they would with any other service.
I am using a mobile phone to get entry to discreet and stigma-free services like psychological counseling, and family planning might be advantageous.
Interactive voice response systems can reconnect dropped calls thanks to caller ID and track many simultaneous activities from the same telephone.
Finally, the speech signal is informative, providing estimations of the speaker's age, body weight, sexuality, anxiety, and other health indicators.
Some drawbacks exist, though, which must be weighed against the advantages. Since the interactive voice response system is language-dependent, the prompts must be recorded in users' native tongues. Interactive voice response ern systems are constrained by emerging communities' cultural and social conventions, even though the telephone interface is familiar.
Users more accustomed to interpersonal communication may resist automated data inquiries and exchanges. To that end, one of the partners believes that in-person demonstrations of the IVR system to clients will provide the most positive results.
Another barrier we discovered for people with few resources was the lack of phone access. Due to fluctuating electricity prices and supply, charging a phone is not always possible. In many cases, people will use various telephones, or multiple people will use the same phone. It's possible that follow-up calls and texts won't be received.
In addition, having a shared phone line can raise questions and suspicions about who is calling. Finally, there are several ways in which users' privacy could be compromised by IVR technologies, from the storage and transmission of data to the reporting of such data to the difficulty of preventing one user from accessing the information of another.
The existing system demands developer-side programming expertise that a CBO might not have access to. The dongle's inability to talk to the Raspberry Pi occasionally resulted from a hardware malfunction. The network failed in some cases. When making a mobile-to-mobile call, one internet provider did not forward the touch-tone signals.
Unfortunately, the system can only handle a single call at a time, making it unsuitable for deployments with a high rate of incoming calls. Our co-operators who expect low call volumes can benefit from the RASP-IVR. A shift to a more scalable approach would be justifiable if volume increased.
Through this tutorial, we have gained a thorough understanding of IVRs and their inner workings. We proceeded to assemble our own Raspberry Pi 4 IVR with a handful of components and some test audio samples. We have investigated the mechanism behind this system and spoken about some of the primary uses for the IVR system. We also had a look at some of the advantages and disadvantages of using it. The following tutorial will teach you how to connect a USB barcode scanner to a Raspberry Pi so that you can read 2D barcodes.
Hello Friends. I hope you are doing great. In this article, I will cover the nature of flow responsible for the changes in density. The nature of flows responsible for density change is known as compressible flows.
Fluid dynamics and thermodynamics combine for the theory of compressible flows. The compressible flow creates a relationship with the ideal gas. First, I will explain the stagnation state, speed of sound, and then the Mach number. This all comes under compressible flows. Then there come the static and stagnation fluid properties, shock waves, and variation of fluid properties in the case of regular and oblique waves. All of these are discussed in this article. So without wasting any time, let us start with the Stagnation property.
The definition of the stagnation property is as follows:
The enthalpy and kinetic energy of the fluid is combined in a term called stagnation or total enthalpy.
The formula of Stagnation Property:
The procedure of stagnation property is as follows:
ho=h+V22
Units of Stagnation property:
The units of stagnation property are kilo Joule per kilogram.
Some of the essential key points related to the stagnation property are as follows:
In the definition of stagnation property, there is a term enthalpy. The enthalpy is the combined flow and internal energy of the fluid. The formula of enthalpy is given below:
h=u+P
It is better to say that enthalpy is equal to the total energy in the case when the potential and the kinetic energy of the fluid are not considered (or negligible).
So, when there are high fluid flows (usually in jet flows/high flows), the potential energy is not considered, whereas kinetic energy is thought. In this situation, the enthalpy and the kinetic energy combine and are called the stagnation enthalpy.
Whenever the fluid's potential energy is not considered, the total energy is said to be stagnation enthalpy.
To differentiate the stagnation enthalpy from the standard enthalpy, the ordinary enthalpy is known as static enthalpy. In contrast, both enthalpies become the same when the kinetic energy is not considered.
Derivation of Stagnation Enthalpy
I will share some essential points related to stagnation enthalpy in this part. So without wasting any time, let us start.
In order to start the derivation of the stagnation enthalpy, we will consider the preferably steady flow, which flows from a nozzle or diffuser. The main property of the flow is that it is flowing on its own, not with the aid of a motor or anything.
The same thing is also implemented; the potential energy is considered minor or negligible.
In this case of a single stream of the steady flow device, the energy balance equation is said to be as follows:
h1+V122=h2+V222 …(a)
h01=h02 (b)
It is better to say that the above equation represents that during the single stream steady flow, there is no change of potential energy, heat, and work interaction is also not present.
A decrease in static enthalpy is observed when there is an increase in velocity. This usually happens in devices that are diffusers and nozzles, respectively.
Another equation is observed, and from equation (a), the velocity of state two will equal zero when the fluid is stopped. So the equation transforms into new, and that is as below:
h1+V122=h2
h02=h1+V122
Another exciting fact says that when there is no heat transfer from the system to the system, it is called an adiabatic state. So the stagnation enthalpy is also considered to be the enthalpy of fluid.
Pressure and temperature also increase when there is the conversion of kinetic energy to enthalpy.
You might be wondering from the heading that says Stagnation Properties. So Stagnation Property is the property of fluid at the stagnation state.
You have observed from equation (b) that there is a transcript 0. So actually, 0 represents the stagnation stage.
Here is another term called isentropic stagnation state and the definition of it is as follows:
The isentropic stagnation state is the one when the stagnation process is adiabatic as well as reversible.
one of the salient features of the isentropic stagnation state is that the entropy remains constant, so in the case of an actual stagnation state, the entropy might increase or decrease depending on the situation.
Both the stagnation state and the isentropic stagnation state are considered the same sometimes.
There is another equation that says that in the case of an ideal gas, equation (b) will become as follows:
CpT0=CpT+V22
The final equation after dividing Cp from both sides is:
T0=T+V22Cp
Here T0 is said to be the stagnation temperature ( transcript with 0 presents stagnation state).
T0 is the temperature at which ideal gas adiabatically becomes a state of rest.
The next term is stagnation pressure. Before defining it, let us see the equation first, and it is as follows:
P0P=(T0T)k/(k-1) (c)
So stagnation pressure is defined as the pressure of a fluid that becomes in a rest state adiabatically.
equation (c) presents the stagnation pressure.
At the start of these critical points, I have used a term, i.e. single stream steady fluid flow. So for this term, the energy balance equation becomes:
qin+win+h01+gz1=qout+wout+(h02+gz2)
The equation in the case of an ideal gas with the specific heats will be as follows:
qin-qout+win-wout=CpT02-T01+g(z2-z1)
So here h02 and h01 are the stagnation enthalpies, whereas T02 and T01 are the stagnation temperature
So this is all from the stagnation enthalpy, property, temperature, and property.
Now I will explain what Mach number is and the speed of sound. So let us start.
Both are interrelated to, first, the speed of sound.
Speed of Sound
After reading the heading, you might be wondering why the article is about compressible flow low then why we are discussing the speed of sound. So better not to worry and let me explain to you in easy words.
The speed of sound in terms of compressible flows is explained as follows:
The sound rate is an integral part of the study of compressible flows as it is the sonic speed at which infinitesimally small pressure waves travel through a medium.
Some of the essential key points and the equation are discussed below. Have a look.
If you look into the definition, there is a statement that says that small pressure waves travel through some medium. Here the pressure waves are created from turbulence or some disturbance.
To explain the topic more precisely, I will explain the speed of sound through some theoretical derivation background.
There is a duct has fluid in it, and that fluid is at rest. There is also a piston inside the duct, which is moved inside. The piston is being moved at some velocity known as constant incremental velocity.
This disturbance of the piston moves the waves of fluid and the movement is made at the speed of sound.
The waves are separated from the fluid adjacent to the piston thus resulting in a change in thermodynamics property.
To elaborate on the whole scenario, the following diagram is presented below:
For a more precise explanation a control volume is considered., In this situation, the waves created by the disturbance or any movement inside remain within the boundary.
Here mass balance equation for the single stream, steady flow is as follows:
mright=mleft
And on simplification, the equation will become as follows:
ρAc=ρ+dρA(c-dV)
Let me explain this equation to you. As you know that in the above theory we have considered a control volume. So when something passes through, there are some movements of the waves, and the fluid moving in the right direction will now move in the direction of the wave front. The speed at which the fluid moves is the speed of sound c. Now the fluid moving in the direction of the left will move away from the wave front, and now rate will be c-Dv, respectively.
So I hope that now the equation is quite understandable to you.
we can further simplify the equation by deduction of cross-sectional area, and now the equation will become:
cdρ-ρdV=0 (a)
The definition of control volume says that there is no heat transfer and work done throughout the process. The equation will not have the potential energy for the steady flow process, and it will be as follows:
h+c22=h+dh+(c-dV)22 (1)
And after the simplification, the equation becomes as follows:
dh-cdV=0
You might be shocked at how the equation is reduced so much as it has so many terms before. So here is the answer. In equation (1), the term dV2 is not considered.
The ordinary sonic wave is nearly unneglectable. They are small, yet they are still considered. So they are somehow isentropic. Now the equation in the case of thermodynamics will be as follows:
Tds=dh-dP (b)
Here the term on the left Tds will be equal to zero, and after the simplification, the equation will become:
dh=dP (c)
For the calculation of the speed of sound, we will combine the equation (a), (b), and (c) will become as follows:
c2=dPdρ
After the simplification, the final equation for the speed of sound will be as follows:
c2=k(∂P∂ρ)T
So here is the final equation of the speed of the sound.
We are moving towards the second part, the Mach Number. Let us see the definition and the equations of it.
Mach Number
The Mach number is also one of the essential parts of compressible flows.
The definition of the Mach Number is as follows:
The Mach Number is the ratio of the actual velocity of the fluid to the speed of sound in the same fluid.
Formula of Mach Number:
The formula of the Mach number is as follows:
Ma=Vc
Some of the essential key points of the Mach number are as follows:
The Mach number has a direct relationship with the velocity of fluid means an increase in the Mach number increases the velocity and vice versa. Whereas the Mach number has an indirect relationship with the speed of sound. The increase in one quantity decreases the other.
There are some important parameters for the flow regimes, and they are as follows:
In the case of
Sonic Mac=1
Subsonic … Mac<1
Supersonic Mac>1
Hypersonic Mac≫1
Transonic Mac≅1
While discussing the flow type, the one-dimensional isentropic flow comes under the compressed fluids.
Examples:
The nozzle diffusers and the turbines are examples of one-dimensional fluid flow.
Some of the essential key points related to the one-dimensional isentropic flow are as follows:
I will explain to you the theoretical background of the one-dimensional flow. Before that, look at the diagram as it will be convenient for you to understand the theory.
As you have seen the diagram and know about the number, let me explain. The value of the Mach number is one at the smallest flow area, called the throat.
Increase in fluid velocity is observed when the fluid passes through the throat. But this increase in velocity is also due to the decrease in the density of the fluid.
If you have a look at the diagram, then there is a word i.e. converging nozzle. But here the converging-diverging nozzle is used so it is the one in which the flow area first increases and then decreases at the throat. Some might confuse these converging nozzles with the Venturi ones. But the Venturi nozzles are used for the incompressible flow.
In this topic, we will pinpoint the main parameter that involves the coupling in the case of isentropic duct flow between the density and velocity.
In this area, we will look forward to some equations of steady flow and the changes in the fluid velocity accordingly to the flow area. So following are some essential key points related to it:
The equation will present the relation between the temperature, pressure, density velocity, Mach number and flow area. These are the equation for the isentropic one-dimensional flow.
The following is the mass balance equation in the case of a steady flow process:
m=ρAV=constant (a)
The equation (a) will be differentiated and divided and the following result will be obtained;
dρ+dAA+dVV=0 (b)
Now the next equation will be related to the isentropic flow in which there is no potential energy and it is as follows:
dP+VdV (c)
The next equation is expressed in terms of Bernoulli’s Equation and again the potential energy is neglected. For convenience, we will combine the equation (b) and (c) and it will become:
dAA=dP(1V2-dρdP)
Now here comes the final equation that describes the isentropic flow in the terms of changes in the pressure accordingly to the flow area.
dAA=dPV2(1-Ma2)
The above-mentioned equation has everything it has an area, density, pressure and Mach number
For this equation there are some limitations in the case of Mach number and they are mentioned below:
Subsonic Flow … Ma<1 and (1-Ma2)term is Positive
Supersonic Flow Ma>1 and (1-Ma2) term is negative
Let me explain these limitations more extensively. In the case of subsonic, the value of differential is dA and differential pressure dP should have the same signs. The increase in pressure increases the flow area and vice versa. Meanwhile, in the case of a supersonic, the value of a differential area and the pressure should have opposite signs. Also, an, increase in pressure quantity should have decreased the flow area of the duct.
There is another equation that is also related to the isentropic flow and it says in equation (c) the value of density and value is substituted in the final equation and it is as follows:
dAA=dVV1-Ma2
So ending this topic on the limitations of Mach number for this equation and they are as follows:
Subsonic Flow (Ma<1) dAdV<0
Supersonic Flow (Ma>1) dAdV>0
Sonic Flow (Ma=1) dAdV=0
Isentropic Flows for Ideal Gas
While discussing the isentropic flow this topic holds its importance as related to the ideal gas. Let’s have a look at the equations and some important key points of it:
For ideal gases both the static and the stagnation properties are combined together, and with the help of the Mach number and specific heat, the equations will be transformed.
The first equation is about the stagnation temperature T0and the ideal gas temperature T. And the equation will be like this:
T0=T+V22Cp
And after simplification, the equation will become:
T0T=1+V22CpT
In this equation, we will substitute the values of V and specific heat. The values we will be substituting are:
Cp=kRk-1
c2=kRT
Ma=Vc
After substation of all the values and doing the simplification, the final equation will become:
T0T=1+(k-12) Ma2
If you remember that at the start, I used two terms, i.e., static and stagnation pressure. So now, I will show you one by one equation of both these terms, and they come under ideal gas. So presenting you the ratio of stagnation to the static pressure, and the equation is:
P0P=[1+k-12Ma2]kk-1
This equation is the result of substituting the value of T0T in this equation.
P0P=(T0T)k/(k-1)
Now presenting you the ratio of stagnation to static density:
0=[1+k-12Ma2]kk-1
There is some limitation where the value of the Mach number is one, so all the points where the Mach number is unity are called the Critical Properties.
While writing the equations of compressible flows the asterisk( *) is used to present the critical points. So their equations will be as follows:
T*T0=2k+1
P*P0=(2k+1)k/(k-1)
*0=(2k+1)1/(k-1)
So these are the equations that present the critical points. That is all from the one-dimensional isentropic flow.
In compressible flows, isentropic is considered to be one of the most important branches of it. Here under this topic, I will discuss the isentropic flow that passes through the nozzles, what are their nature equations, and the nozzle type. Let us start.
First of all, I will share some of the essential key points with you that covers all the information about the topic.
Here in this topic we will learn a new term i.e. Back pressure. A brief definition of back pressure is as follows:
Back pressure is pressure that is applied at the discharge region of the nozzle.
Here the nozzle can be converging and diverge depending on its requirement of it. I will discuss the nozzle type and the isentropic flow through it.
Converging Nozzle
The derivation and the equation of the converging nozzle are as follows:
A subsonic flow is considered in the case of a converging nozzle. The diagram elaborates on the flow:
Here you can clearly see that the inlet of the nozzle is connected to the reservoir. The temperature is presented as Tr whereas the pressure is as Pr respectively.
the velocity at the inlet is neglected and the flow is isentropic. The reservoir has a huge volume so that is the main reason the fluid velocity’s not being considered.
The reservoir pressure and temperature are equal to the nozzle’s pressure and temperature.
Now the working is being followed and the back pressure is being reduced. After doing so the change in the flow pressure is observed.
The back pressure is equal to the P1 and that P1 is equal to the reservoir pressure. This is all due to the uniform distribution of pressure among the nozzle.
Similarly when the back pressure is reduced to P2 then the value of at the outlet becomes equal to P2 also. As a result of this procedure, the pressure of the nozzle decreases in the direction of the flow.
This all working is elaborated by the diagram mentioned below;
The back pressure is now reduced at pressure point three and that is equal to the critical pressure. Actually, pressure three equal to the critical pressure shows that the pressure that is required by the fluid increases the velocity of the fluid and this increases the speed of sound at the throat.
Now the back pressure is reduced to pressure point four. Here there is no change in the pressure and the flow is being observed as it is at the end position.
Now we will look forward to the equation that is related to the mass flow rate.
m=ρAV
m=PRTAMakRT
m=PAMakRT
We will do further simplification and the final result will be as follows:
m=AMaP0k(RT0)[1+(k-1)Ma2/2](k+1)/[2k-1]
Whenever there is a Mach number there are certain limitations as discussed above according to the equations. Here when there is a specified flow area the mass flow rate can be determined by differentiating the above equation and equalizing it to zero. The value of the Mach number here is one. We all the when the value of the Mach number is one (it is at the throat) and the mass flow is maximum at the throat.
Now the equation will be as follows:
m=A*P0kRT0(2k+1)(k+1)/[2k-1]
In order to have a maximum flow rate there are two parameters to be fulfilled. The temperature and the pressure at the inlet of stagnation of a given throat give the maximum flow rate in the case of an ideal gas.
It is a characteristic property that by changing the stagnation pressure and temperature we can control the flow rate values.
So these are the theoretical background and equation related to flow rate. Hence there is another point related to this topic and that is the critical Mach number.
The equation for it is the same as the formula for the Mach number but there are a few modifications, and they are as follows:
Ma*=Vc*
The formula can be expressed in the term of temperature, and the working is as follows:
Ma*=Vc.cc*
Ma*=Ma. cc*
Ma*=MakRTRkT*
Ma*=MaTT*
We can further simplify this equation and can get the final critical Mach number equation so by substituting the values of local and critical temperature, we get:
Ma*=Mak+12+(k-1)Ma2
So, this is the final equation. There is a difference in both the values of the Mach number.
The critical Mach number Ma* is the local velocity non-dimensionalized concerning the sonic velocity at the throat. The other one Ma is the local velocity non-dimensionalized concerning the local sonic velocity.
Their values also differ from one another. The value of Ma* is provided on a table that is listed against the Ma when the value of k is 1.4.
The table is shown below for your clarification:
So that is all from the isentropic flow through nozzles. Let’s move toward the next topic, related to the waves.
Where ever there is flow, there are waves created. As we have studied in depth how sound waves are made, the question is how shock waves are formed. Let us have a concept about it.
There are changes in the fluid properties that can either be temperature pressure, increase or decrease in volume, etc. These changes occur in a thin layer of the converging-diverging nozzle under supersonic flow conditions. So in this way, shock waves are created. Now I will explain the type of shock waves, their working principle, and the equations. So without wasting any time, have a look at it.
Normal Shock Wave
The definition of normal shock waves is as follows:
The normal shock waves are the ones that form in a plane normal to the direction of flow.
Some of the essential key points, along with the equations of normal shock waves, are explained below:
The shock wave is all irreversible and not being approximated as being isentropic.
The process includes all the energy, momentum, and conservation of mass relation to define the flow properties before and after shock.
The normal waves are different in the sense that they are thin and this property benefits the entrance and exit flow areas. The exit and the entrance flow area are the same.
Now moving towards the mathematical part. Let’s start with the conservation of mass. As you all know about the formula of conservation of mass but for convenience let me show you.
1AV1=2AV2
The equation can further be simplified with the cancellation of cross-sectional area.
For the conservation of energy, the equation is as follows:
h1+V122=h2+V222
Now let’s have an overview of the conservation of momentum:
AP1-P2=m(V2-V1)
While working on the equation for the normal shock waves we combine the law of conservation of mass and energy into one equation.
The equation is then plotted on the h-s diagram.
If you look at the diagram below, it shows all the important aspects that I am going to share.
The h-s diagram shows a line i.e., Fanno Line and that is the resultant curve. This curve has similar values of stagnation enthalpy and mass flux.
Moving towards the second curve i.e. the Rayleigh Line. There are two point on the h-s diagram and these two points are correspondence to the Mach (Ma=1).
Further you can see in the diagram that the upper part is for the subsonic flow whereas the lower part is for the supersonic flow.
The two lines Fanno and the Rayleigh line intersect at two points as you can see from the diagram. One point presents the condition that is before the shock and the second shows after the shock condition. At point 1, it is supersonic and before shock condition, whereas at point 2 it is subsonic and aftershock condition.
Also the high is the value of the Mach number before the shock there is a chance that the shock will occur.
When the Mach number is unity then the shock waves are simply sound waves.
One of the important points related to this is that the conservation of energy principle demands that the stagnation enthalpy should be constant throughout the process.
h01=h02
In the case of an ideal gas, the enthalpy is as follows:
T01=T02
After the shock, the temperature of the ideal gas remains constant.
Moving forward, there are some important equations that are related to the ideal gas. These equations show the before and after shock and after substituting the values required results can be obtained.
So following are two important equations.
T01T1=1+(k-12)Ma12
T02T2=1+(k-12)Ma22
We will further simplify the equation by taking T01=T02 and the result will be:
T2T1=1+Ma12(k-1)/21+Ma22(k-1)/2 (a)
In the case of an ideal gas, we know that:
1=P1RT1
2=P2RT2
The value of temperature can be easily substituted using the law of conservation of mass while the values of Mach number and c are used which we can substitute in equation(a). the values are as follows:
Ma= V/c
c=kRT
Now we can substitute all the values and get the result as follows:
T2T1=P2V2P1V1=P2Ma2c2P1Ma1c1=P2Ma2T2P1Ma1T1=(P2P1)2(Ma2Ma1)2 (b)
Now this is the final result we get after substituting all the values. We can further simplify this equation and can get the equation for the pressure ratio across the block and for that we will combine the equation (a) and (b):
P2P1=Ma11+Ma12(k-1)/2Ma21+Ma22(k-1)/2
If you recall the law of conservation of mass and energy, then after looking at the equation you will understand that it is the combination of laws.
Thus this equation about the Fanno Line for ideal gas.
The other curve is Rayleigh Line and its derivation is as follows:
P1-P2=mAV2-V1
P1-P2=2V22-1V12
As:
V2=(PRT)(Ma.c)2
V2=(PRT)(MakRT)2
V2=Pk Ma2
The pressure ratio can be as follows:
P2P1=1+kMa121+kMa22
Now we will move towards the final equation that is about the Fanno and the Rayleigh lines relating the Mach number upstream of a shock to that downstream of the shock. Let’s us have a look at an equation:
Ma22=Ma12+2/(k-1)2Ma12k/(k-1)
The oblique shock is a type of shock waves. It is better to say that there are various variations of waves. So moving toward the topic in order to define the oblique shock I will explain it through an example. So have a look at the example:
Example:
The space shuttle traveling through the atmosphere at supersonic speed creates a complicated pattern with shock waves. Such complex patterns and shock waves are called Oblique Shock Waves.
The following is the diagram that elaborates the shock waves:
Some of the essential key point and equations related to the oblique shock waves is as follows. Have a look at it:
Here in the diagram you can see there are some certain angles mentioned and they these angles helps in the formation of the oblique shock waves.
So talking about the first angle i.e. the theta and this is named as a turning angle or angle of deflection. The background of this angle is that at first, we consider the oblique shock waves traveling in a straight line. This straight line is much similar when the Ma>1 and in supersonic flow, a two-dimensional wedge half angle is formed. So here the fluid cannot flow through the wedge and at that point, it turns into the turning angle.
The other angle is about the shock angle or wave angle (). The background of this angle is that when the turning angle is formed then the straight oblique shock wave is formed and this wave is aligned with the wave angle.
For the conservation of mass, the wave angle should be greater than the two-dimensional half-wedge angle.
In the case of supersonic flows, Reynold’s number has a high value, and the boundary layer along the wedge is thin so its effects are not considered.
Now the flow is turned by another angle that is much similar to the wedge angle and it is named a deflection angle .
The deflection angle is the same as the half wedge angle.
Here there is an interesting fact about the half wedge and deflection angle i.e. when the thickness effect of the boundary layer is considered then the deflection angle is observed to be greater than the half wedge angle.
In the case of the oblique shock waves there are also the limitations of the Mach number. A decrease in the Mach number is observed in oblique shock waves.
Also oblique shock waves are possible when the upstream flow is supersonic.
Now moving towards some mathematical part of the oblique shock waves. The straight oblique shock wave is considered.
The diagram below shows the straight oblique shock waves:
Now here you can see that the straight wave is decamped into the velocity vector upstream and downstream of the normal and tangent components.
For working a small control volume is being considered and all the working happens on it.
If you look at the diagram closely, the upstream of the shock, all the fluid properties (such as pressure velocity) along the lower left face of the control volume are similar to those of the upper right face.
In this case, the law of conservation of mass equation is changed into the following equation:
1V1,nA=2V2,nA
Canceling the area of the control surface (A) on both sides we will get:
1V1,n=2V2,n
There is another important point related to the tangential component of velocity. So the tangential component of the velocity is parallel to the oblique shock and in order to prove this point the tangential momentum equation to the control volume is applied.
So conservation of momentum is being applied in the normal direction to oblique shock waves. So the equation we get is as follows that presented the forces that are only pressure forces:
P1A-P2A=ρV2,nAV2,n-ρV1,nAV1,n
P1-P2=2V2,n2-1V1,n2
Since we have considered a small control volume so we know that there is no transfer of heat and no transfer of work done. The stagnation enthalpy also does not change and eventually, the conservation of energy equation becomes as follows:
h01=h02=h0
h1+12V1,n2+12V1,t2
h2+12V2,n2+12V2,t2
Here the V1,t=V2,t. The equation will be reduced as follows:
h1+12V1,n2=h2+12V2,n2
Here is the final equation.
You might have observed that the equation of the conservation of mass, energy, and momentum have the same equations but when we are writing them in the terms of normal velocity components then they vary. But the equation for the normal shock is the same.
The equations that are derived for the normal shock waves can be applied oblique shock waves. Here is a condition that the oblique waves equation should be written in the terms of Mach number.
So we come to the conclusion that the equation for the oblique shock waves is much similar to the normal ones but the only difference is that the normal components of the Mach number are used in oblique ones.
It is also one of the important types of waves and it may differ from other ones also. Let us share some of the important key points related to it;
One of the important points about the supersonic flow is that when it travels in the opposite direction just in the upper portion of a two-dimensional wedge at an angled attack is greater than the half-angle sigma (δ).
The flow of such kind is known as expanding flow. But when the flow is in oblique shock then the flow is called the compressing flow.
The diagram shows the whole flow type and the angles created by it.
So there is not a abrupt change in the turning of flow by the shock but the Mach wave turn and thus the flow also turn by infinitesimal amount.
One of the important information about the flow is that the flow is isentropic.
In the downstream direction, a decrease in the pressure, temperature and density is observed whereas the Mach number increases.
Just have a look at the diagram you will see that Prandtl-Meyer is inclined at some angle called the Mach angle (μ) also the first expansion wave has an angle and we call it Mach angle. This angle is determined in the following way:
1=(1Ma1)
2=(1Ma2)
Now there is important to question how can we determine the Mach number 2. So for Ma2, there is a formula for it and that formula shows a turning angle across the expansion fan and can easily be calculated by integration. So the formula is as follows:
=v(Ma2)-v(Ma1)
Now, this is the formula for the turning angle across the expansion fan and can be used to find Ma2.
Here in this formula vMa is the Prandtl-Meyer function and it has an equation where we can find the unknown. So the equation is as follows:
vMa=k+1k-1( k-1k+1(Ma2-1))-( Ma2-1)
Here is an important point and i.e. that vMais an angle and it should not be confused with kinematic viscosity.
When the Mach number is unity then the Prandtl-Meyer function vMa taken as zero for getting the supersonic Mach number (Ma>1)
One of the interesting features of the Prandtl-Meyer function is that it has numerous advantages in our daily life.
The shock wave and boundary layer both have a unique significance. There are numerous advantages of both of these in our daily life.
The following are some important applications of shock waves and boundary layers. Have a look at them:
The boundary layer is susceptible to separation from aerodynamics whenever strong adverse pressure occurs
The shock wave on the other hand produces a strong pressure gradient.
Whenever the boundary layer and the shock wave interact with each other the result is a complex flow pattern and in some cases, the boundary layer separates from the region on which it is attached
The interaction between the shock wave and the boundary layer is viscous and inviscid interaction in which the viscous flow in the boundary layer encounters the essentially inviscid shock wave that is generated in the free stream.
The change in the shock wave and the boundary layer continues until an equilibrium condition is reached.
The shock wave and boundary layer have become one of the most pacing problems of modern fluid mechanics research.
Conclusion
Dear friends I hope you have enjoyed reading the article. I have tried best to explain extensively about the compressible flows, isentropic flows, shock waves, boundary layers, and the applications of both of them. That’s all my side. Thanks for reading.
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.