Interface PCF8591 ADC/DAC Analog Digital Converter Module with Raspberry Pi 4

Welcome back to another Python tutorial for the Raspberry Pi 4! The previous tutorial showed us how to construct a Raspberry Pi-powered cell phone with a microphone and speaker for making and receiving calls and reading text messages (SMS). To make our Raspberry Pi 4 into a fully functional smartphone, we built software in Python. As we monitored text and phone calls being sent and received between the raspberry pi and our mobile phone, we experienced no technical difficulties. But in this tutorial, you'll learn how to hook up the PCF8591 ADC/DAC module to a Raspberry Pi 4.

Since most sensors only output their data in analog values, converting them to binary values that a microcontroller can understand is a crucial part of any integrated electronics project. A microcontroller's ability to process analog data necessitates using an analog-to-digital converter.

Some microcontrollers, including the Arduino, MSP430, and PIC16F877A, contain an onboard analog-to-digital converter (ADC), whereas others, like the 8051 and Raspberry Pi, do not.

Where To Buy?
No.ComponentsDistributorLink To Buy
1Jumper WiresAmazonBuy Now
2PCF8591AmazonBuy Now
3Raspberry Pi 4AmazonBuy Now

Required Components

  1. Raspberry-pi 4

  2. PCF8591 ADC Module

  3. 100K Pot

  4. Jumper wires

You are expected to have a Raspberry Pi 4 with the most recent version of Raspbian OS installed on it, and that you are familiar with using a terminal program like putty to connect to the Pi via the Internet and access its file system remotely. Those unfamiliar with Raspberry Pi can learn the basics by reading the articles below.

PCF8591 ADC/DAC Module

Each of the ten pins on the PCF8591 module may read analog values as high as 256 on the PCF8591's digital side or vice versa. The board has a thermistor and LDR circuit. Input and output from this module are both analogs. To facilitate the I2C protocol, it has a dedicated serial clock and serial data address pins. The supply voltage ranges from 2.5 to 6V, and the stand-by current is minimal. We can further turn the module's potentiometer knob to control the input voltage. A total of three jumpers can be found on the board. Switching between the thermistor, LDR/photoresistor, and adjustable voltage access circuits is possible by connecting J4, J5, and J6. D1 and D2 are two LEDs on the board, with D1 displaying the strength of the output voltage and D2 indicating the power of the supply voltage. When the supply or output voltage is increased, the brightness of LEDs D1 and D2 are correspondingly enhanced. Potentiometers connected to the LEDs' VCC or AOUT pins also allow testing.

Microprocessors, Arduinos, Raspberry Pis, and other digital logic circuits can interact with the physical environment thanks to Analogue-to-Digital Converters (ADCs). Many digital systems gather information about their settings by analyzing the analog signals produced by transducers such as microphones, light detectors, thermometers, and accelerometers. These signals constantly vary in value since they are derived from the physical world.

Digital circuits use binary signals, which can only be in one of two states, "1" (HIGH) or "0" (LOW), as opposed to the infinitely variable voltage values provided by analog signals (LOW). Therefore, Analogue-to-Digital Converters (A/D) is an essential electronic circuit for translating between constantly varying analog impulses and discrete digital signals.

To put it simply, an analog-to-digital converter (ADC) is a device that, given a single instantaneous reading of an analog voltage, generates a unique digital output code that stands in for that reading. The precision of an A/D converter determines how many binary digits, or bits, are utilized to represent the original analog voltage value.

Analogue and Digital Signals

By rotating the potentiometer's wiper terminal between 0 and VMAX, we may see a continuous output signal with an endless set of output values related to the wiper position. In a potentiometer, the output voltage constantly varies while the wiper is moved between fixed positions. Variations in temperature, pressure, liquid levels, and brightness are all examples of analog signals.

A digital circuit uses a single rotary switch to control the potential divider network, taking the place of the potentiometer's wiper at each node. The output voltage, VOUT, rapidly transitions from one node to the next as the switch is turned, with each node's value representing a multiple of 1.0 volts.

The output is guaranteed at 2-volt, 3-volt, 5 volts, etc., but NOT a 2.5-volt, 3.1-volt, or 4.6-volt output. Using a multi-position switch and more resistive components in the voltage-divider network, resulting in more discrete switching steps, would allow for generating finer output voltage levels.

By this definition, we can see that a digital signal has discrete (step-by-step) values, while an analog signal's values change continuously over time. We are going from "LOW" to "HIGH" or "HIGH" to "LOW."

So the question becomes how to transform an infinitely variable signal into one with discrete values or steps that a digital circuit can work with.

Converting from Analog to Digital

Although several commercially available analog-to-digital converter (ADC) chips exist, such as the ADC08xx family, for converting analog voltage signals to their digital equivalents, a primary ADC can be constructed out of discrete components.

Using comparators to detect various voltage levels and output their switching signal state to an encoder is a straightforward method known as parallel encoding, flash encoding, simultaneous encoding, or multiple comparator converters.

The equivalence output script for a given n-bit resolution is formed by a chain network of accuracy resistors and a series of comparators that are connected but equally spaced.

As soon as an analog signal is provided to the comparator input, it is evaluated with a reference voltage, making parallel converters advantageous because of their ease of construction and lack of need for timing clocks. The following comparator circuit may be of interest.

A Logic Comparator

The LM339N is an analog comparator that compares the relative magnitudes of two voltage levels via its two analog inputs (one positive and one negative).

The comparator receives two signals, one representing the input voltage (VIN) and the other representing the reference value (VREF). The comparator's digital circuits state, "1" or "0," is determined by comparing two output voltages at the input of the comparator.

One input (VREF) receives a reference voltage, and the other input (VIN) receives the input voltage to be compared to it. Output is "OFF" by an LM339 comparator when the input power is lower than (VIN VREF) and "ON" when the input power is higher than the standard voltage (VIN > VREF). A comparator is a device to determine which of two voltages is greater.

Using the potential divider network established by R1 and R2, we can calculate VREF. If the two resistors are identical in value (R1 = R2), then the reference voltage will be half the input power (V/2). Therefore, like with a 1-bit ADC, the output of an open-collector comparator is HIGH if VIN is lower than V/2 and LOW otherwise.

However, by increasing the number of resistors in the voltage divider circuit, we can "divide" the voltage source by an amount equal to the ratio of the resistors' resistances. However, the number of comparators needed increases with the number of resistors in the voltage-divider network.

For an "n"-bit binary output, where "n" is commonly between 8 and 16 bits, a 2n- 1 comparator would be needed in general. As we saw previously, the comparator utilized by the one-bit ADC to determine whether or not VIN was more significant than the V/2 voltage output was 21 minus 1, which equals 1.

If we want to build a 2-bit ADC, we'll need 22-1 or "3" comparators since the 4-to-2-bit encoder circuitry depicted above requires four distinct voltage levels to represent the four digital values.

Circuit for 2-bit A/D Conversion

For each of the four potential values of the analog input of:

A/D Conversion Output, 2-Bit

Where X is a "don't care" statement, representing a logical 0 or 1.

Explain how this analog-to-digital device operates. An analog-to-digital converter (A/D) must generate a faithful digital copy of the Analog input signal to be of any value. To keep things straightforward, we've assumed that VIN is somewhere between 0 and 4 volts and have adjusted VREF and the voltage divider network so that there is a 1 V drop between each resistor in this simple 2-bit Analog - to - digital example.

A binary zero (00) is output by the encoder on pins Q0 and Q1 when the input voltage, VIN, is less than the reference voltage level, which occurs when VIN is between 0 and 1 volts (1V). Since comparator U1's reference voltage input is set to 1 volt, when VIN rises above 1 volt but is below 2 volts, U1's HIGH output is triggered. When the input changes at D1, the priority encoder, used for the 4-to-2-bit encoding, generates a binary result of "1." (01).

Remember that the inputs of a Priority Encoder, like the TTL 74LS148, are all assigned different priority levels. The highest priority input is always used as the output of the priority encoder. So, when a higher priority input is available, lesser priority inputs are disregarded. Therefore, if there are many inputs simultaneously at logic state "1", only the input with high priority will have its output code reflected on D0 and D1.

Thus, now that VIN is greater than 2 volts—the next reference voltage level—comparator U2 will sense the difference and output HIGH. However, when VIN is more than 3 volts, the priority encoder will output a binary "3" (11), as input D2 has a high priority than inputs D0 and D1. Each comparator outputs a HIGH or LOW state to the encoder, generating 2-bit binary data between 00 and 11 as VIN decreases or changes between every reference voltage level.

This is great and all, but commercially available priority encoders, like the TTL, are 8-bit circuits, and if we use one of these, six of the binary numbers will go unused. A digital Ex-OR gate and a grid of signaling diodes can create a straightforward encoder circuit.

Diode-based 2-bit ADC

Before feeding the diodes, the results of the comparators go through an Exclusive-OR gate to be encoded. Whenever the diode is reverse biased, an external pull-down resistor is connected between the diodes' outputs and ground (0V) to maintain a LOW state and prevent the outputs from floating.

Also, as with the main board, the value of VIN controls which comparator sends a HIGH (or LOW) signal to the exclusive-OR gates, which provide a HIGH output if either of the inputs is HIGH but not both (the corresponding Boolean is Q = A.B + A.B). The AND-OR-NAND gates of combinational logic could also be used to build these Ex-OR gates.

The difficulty with both of these 4-to-2 converter designs is that the input analog voltage at VIN needs to vary by one full volt for the encoder to vary its output code, limiting the precision of the simple two-bit A/D converter to 1 volt. The output resolution can be improved by employing more comparators to convert to a three-bit A/D converter.

D/A Converter, 3-Bit

The aforementioned parallel ADC takes a voltage reading between 0 and over 3 volts as an analog input and turns it into a binary code with only 2 bits. Since there are 23 = 8 possible digital outputs from a 3-bit digital circuits system, the input analog voltage can be compared to a scale of eight voltages, each of which is one-eighth (1/8) of the voltage supply. This means that we can now measure to an accuracy of 0.5 (4/8) volts and that 23-1 comparators are needed to generate a binary code with a 3-bit resolution (from 000 (0) to 111 (7)).

Circuit for 3-bit Analog-to-Digital Conversion

This will provide us with a three-bit code for each of the eight potential values of the analog input of:

The result of a Three-Bit Analog-to-Digital Converter

An "X" may be a logic 0 or a logic 1 to indicate a "don't care" state.

Then we can see that more comparators and power levels are required and more output binary bits when the ADC's resolution is increased.

Therefore, an analog-to-digital converter with a 4-bit resolution needs only 15 (24-1) comparators. An eight-bit resolution requires 255 (28-1) comparators. A 10-bit resolution needs 1023 comparators, etc. Therefore, the complexity of this type of Analog-to-Digital Converter circuit increases as the number of output bits increases.

Only if a few binary bits are needed to make a read on a display unit to represent the reference voltage of an input analog signal can a parallel or flashed A/D converter quickly be developed as part of a project due to its fast real-time conversion rate.

As an input interface circuit component, an analog signal from sensors or transducers is converted into a digital binary code by an analog-to-digital converter. Similarly, a digital binary code can be converted into a comparable analog quantity using a Digital-to-Analog Conversion for output interfacing to operate a motor or actuator or, more often, in audio applications.

Raspberry Pi's I2C pins

Knowing the Raspberry Pi's I2C port pins and setting up the I2C connection in the pi 4 are the initial steps in using a PCF8591 with the Pi.

GPIO2 and GPIO3 on the Rpi Model are utilized for I2C communication in this guide.

Raspberry Pi I2C Configuration

Raspberry Pi lacks I2C support by default. Therefore, it must be activated before anything else. Turn on Raspberry Pi's I2C port.

  1. First, open a terminal and enter sudo raspi-config.

  2. The RPi 4 Software Configuration Tool has opened.

  3. Third, activate the I2C by selecting Interfacing options.

    1. Restart the Pi after enabling I2C.

    Reading the PCF8591's I2C Address with a Raspberry Pi

    The Raspberry Pi has to know the I2C address of the PCF8591 IC before communication can begin. You may get the address by linking the PCF8591's SDA and SCL pins to the Raspberry Pi's own SDA and SCL jacks. The 5-volts and GND pins should be connected as well.

    You may find the address of an attached I2C device by opening a terminal and entering the following command.

    sudo i2cdetect –y 1 or sudo i2cdetect –y 0

    After locating the I2C address, the next step is constructing the circuit and setting up the required libraries to use PCF8591 and a Raspberry Pi 4.

    Connecting the PCF8591 ADC/DAC Module to the Raspberry Pi 4

    The circuit diagram to interface the PCF8591 with the Raspberry Pi is straightforward. In this example of interfacing, we'll read the analog signal from any analog inputs and display them in the Raspberry Pi terminal. We have a 100K pot to adjust the settings.

    Pi's GPIO2 and GPIO must be connected to the power supply and ground. Then, hook up GPIO3 and GPIO5 to SDA and SCL, respectively. Last but not least, link AIN0 to a 100K pot. Instead of using the Terminal to view the ADC values, a 16x2 LCD can be added.

    The A/D Conversion Python Program

    The complete code and demo video are included after this guide.

    To communicate with the I2C bus, you must first import the SMBus library and then use the time library to specify how long to wait before outputting the value.

    import smbus

    import time

    Create some variables now. The I2C bus address is stored in the first variable, and the first analog input pin's address is stored in the second variable.

    address = 0x48

    A0 = 0x40

    Next, we've invoked the library smbus's SMBus(1) function to create an object.

    bus = smbus.SMBus(1)

    The first line in the while instructs IC to take a reading from the first analog signal pin. Address information read from an Analog pin is saved as a numeric variable in the second line. Exit with the value printed.

    While True:

        bus.write_byte(address,A0)

        value = bus.read_byte(address)

        print(value)

        time.sleep(0.1)

    Finally, put the Python script in a file ending in.py and run it in the Raspberry Pi terminal with the command below.

    python filename.py

    Ensure that the I2C communication is turned on and that the pins are linked according to the diagram before running the code, or else you will get errors. It's time for the analog readings to appear in the terminal format below. The values gradually shift as you turn the pot's knob. Find out more about getting the software to work in

    Here is the full Python script.

    import smbus

    import time

    address = 0x48

    bus = smbus.SMBus(1)

    while True:

        bus.write_byte(address,A0)

        value = bus.read_byte(address)

        print(value)

        time.sleep(0.1)

    ADC's Practical Uses

    We rely heavily on electronic gadgets in today's high-tech society. The digital signal is the driving force behind these digital devices. While most numbers are represented digitally, few still use analog notation. Thus, an ADC is employed to transform analog impulses into digital ones. ADC can be used in an infinite variety of contexts. Here are only a few examples of their use:

    • The digitized voice signal is used by cell phones. The voice is first transformed to digital form using an ADC before being sent to the cell phone's transmitter.

    • Digital photos and movies shot with a camera can be viewed on any computer or mobile device thanks to an analog-to-digital converter.

    • X-rays and MRIs are just two examples of medical imaging techniques that use ADC to go from Analog to digital before further processing. Then, they're adjusted so that everyone can follow along.

    • ADC converters can also transfer music from a cassette tape to a digital format, such as a CD or a USB flash drive.

    • The Analog-to-Digital Converter (ADC) in a digital oscilloscope converts analog signals to digital ones that can then be displayed and used for other reasons.

    • The air conditioner's built-in temperature sensors allow for consistent comfort levels. The onboard controller reads the temperature and makes adjustments based on the data it receives from the ADC.

    Nowadays, practically everything has a digital counterpart, so every gadget must also include an ADC. For the simple reason that its operations require a digital domain accessible only via an analog-to-digital converter (ADC).

    Conclusion

    This piece taught us how to connect a Raspberry Pi 4 to a PCF8591 Analogue - to - digital decoder module. We have observed the output being shown as integers on our Terminal. We have also researched how the ADC generates its output signals. Here we will use OpenCV and a Raspberry Pi 4 to create a social distance detector.

    Control Project with Ladder Logic Programming

    Hey guys! hope you are all very well. Today I come to you with a new process to learn, program, and simulate for practicing ladder logic more and more. The process we are going to implement today is a very common process that could be there in many many industries which is a silo process that aims to automate the process of filling containers or bottles with a liquid. Figure 1 shows the complete scene of the process including the system components, switches, indicators, sensors, and actuators that are integrated to make the system operate. Briefly and before going into deep details, let’s state what the system does and how it operates. Well! The system automatically fills the boxes that are traveling on the conveyor which is driven by a motor. They are filled with a liquid stored in the silo shown in the middle of figure 1. The process operates continuously from the moment we hit the start button shown in the tail of the control panel on the left side of figure 1 until termination of the process is requested by pressing the stop push in the same panel. Many inputs and outputs are utilized to address the sensors, switches, push buttons, motors, and valves. So let’s get started on the project.

    Project Logic Philosophy

    As we have thought, the first step in the development of a control system is to sit with the operator or the client to get to comprehend how the system works including all details and scenarios. So the system starts by receiving the kickoff by hitting the start pushbutton. Unless there is no stop has been requested or faults, the box moves on the conveyor that is driven by a motor until it reaches the filling station which is at the silo. At that position, the box should stop for filling, and the flow of the liquid starts and goes on until the box is full. Then, it is time for the box to continue its journey to the end of the conveyor and another box commences a new trip for filling. At any time a stop is requested, the system should halt until a command to continue is presented. Operation status should be shown thanks to indicators showing the run, fill, and full status. Now, friends, that’s all the story we have gotten by sitting with the client or the operator who requested us to implement his system. have understood the requested silo operation? Well done! I know it is simple to understand but what is the next step? Yes, the next station in the project is to interpret the story narrated by our client into operation sequences and conditions and determine the list of inputs and outputs to get that project done. 

    Logic sequence

    The aims of the project we are going to implement is to implement the ladder logic program that execute the narrated logic of SILO by client. The logic can be resumed in the following sequence of operations: 

    • The batch process can be started or stopped at any point of execution 

    • Indicator lamps should be appropriately controlled to present the run, fill, and full statuses of the operation throughout the whole process.

    • All actuators should be stopped at any time a termination requested by the end user

    • The FULL lamp is switched on showing the full status of the box as long as the box at its filling position under the silo.

    • After converting the logic narrative received from the client into clear logic sequences, now the time comes to list the inputs and outputs to use to accomplish these logic sequences. In the next section, the complete list of inputs represented by sensors and switches and outputs represented by motors, valves, and light indicators. 

    Project I/Os

    Figure 2 shows the location and address of all inputs and outputs used in this project. Also, the table below lists all inputs and outputs of the project including descriptions and addresses. The control panel on the lift shows two inputs that enable an operator to start and stop the operation. Also, it shows indicators showing the status of the operation throughout the whole process. These status indicators are RUN. FILL, FULL to show the process is running, the box is filling, and when it is full. Also, it shows the motor that drives the conveyor and the proxy sensor that detects the position where the box is exactly under the silo and ready to be filled for initiating the filling process. Also, a level sensor is utilized to determine when the box is filled up to full. In addition, a valve is used to open and close the silo.

      Table 1: list of inputs and outputs of the project     

    IO

    type

    Description

    Address

    RUN

    Output

    Indicator lamp to show the running status

    Q2.2 for siemens

    O:2/02 for AB

    FILL

    Output

    An indicator lamp to show the filling process is in progress

    Q2.3 for siemens

    O:2/03 for AB

    Full 

    output

    An indicator lamp to show the full status of the box

    Q2.4 for siemens

    O:2/04 for AB

    MOTOR

    Output 

    The main motor drives the conveyor to take the boxes through their journey  

    Q2.0 for siemens

    O:2/00

    Valve

    Output

    A solenoid valve to control the silo to open or close according to the logic

    Q2.1 for siemens

    O:2/01 for AB

    Start

    input

    A pushbutton enables the operator to start the process

    I1.0 for siemens

    I:1/00 for AB

    Stop 

    Input 

    A pushbutton enables the operator to stop the process

    I1.1 for siemens

    I:1/01 for AB

    Level sensor

    input

    A level switch to detect the level of the liquid being filled into the box

    I1.4 for siemens

    I:1/04 

    Proximity switch

    Input 

    A proximity switch to sense the position of the approaching box 

    I1.3 for siemens

    I:1/03 


    Logic Flow Diagram

    Guys, this is not an essential step to accomplish the project development. But this is one of the professional ways to represent graphically the design of the logic. Figure 3 depicts the logic of the silo project graphically. You can follow paths of logic to understand how we can chart the logic flow running in our head graphically to help in writing the correct and precise code. For example, to run the conveyor motor, the start button is pressed and checked if a stop is requested, if not the run lamp indicator will be energized and latched as long as no stop is requested. Then check if a fill process is in progress. If not then the motor of the conveyor will keep running. But the question is how to know if the fill is in progress or not. On the left side of the chart, you can see if the proxy switch is on and the level switch does not show full, then the filling process is in progress. Also, if the level switch shows not full then the valve will keep open to continue filling the boxes.

    Ladder Logic Programming of the project

    Now we have just arrived at what you are waiting for! I know you want to practice programming and then simulation. Figure 4 shows the program of the silo project while the left part shows the initial state of our simulation. The first rung is to energize the run indicator when the start pushbutton is hit and no stop is requested noting the latch as we have learned. In the second rung, knowing the run is the status of the operation and no filling process is in progress, then the motor is running. In the third rung, the filling status can be determined by the proximity switch showing the boss is at the position were ready to fill and full status is not there. While the full status can be determined in the last rung when the level switch is on showing level has reached the full limit of the box and pursuing the proximity switch tells the box is on the filling spot. Before that very last rung, the valve of the silo can be determined by having the fill status on and the full status is not there yet.

    Simulating the program

    After showing you the code of the design step by step based on the received narrative from the client, deciding the IOs, and charting the logic of the program. Now it is time to simulate the program to make sure the design and the code are correct. Figure 5 shows the running status of the operation. By hitting the start push button, the conveyor move by the driving motor and takes the box to the filling station. Guys, notice please the run indication lamp is on in the code highlighted in yellow and on the control panel on the right as well. Also, notice the motor is spinning.

    Figure 6 shows the box stopped for filling at the silo thanks to the proximity switch. Notice the run lamp is on and the motor is de-energized for letting the box fill. Also, notice the fill status is on and the lamp indicator is energized. Also, see the valve is open to let the liquid fills the box.

    Figure 7 shows when the box comes to be full. You can see the run operation status is still on. And the full status is indicated by the full lamp. Also, once the box is full, the motor starts spinning again taking the filled box out from the line to let other incoming boxes come.

    And finally, after filling to full, the filled boxes keep going as shown in figure 8 to the end of the conveyor. You can see the run status is still energized and the motor is spinning. After that, the cycle will continuously be repeated until the stop is requested. So let us see the termination of the process.   

    on the other hand, when the stop push button is pressed requesting termination of the process, the motor stops spinning and the whole process stopped until a proceeding instruction is issued by hitting start again. Guys, that is very common to enable the machine operator to stop for any emergence or do any repainting before baking to work again 

    What is next???

    First of all, I would like to thank you all for continue following the tutorial till this very point. As you see we are taking projects from real life. It might be small projects or processes but that is what you will see in real industry life. So next time we select one of the common processes in the real life and do the same design, coding, and without question practicing using our simulator. So please be ready, study hard, and let’s meet for our next project.

    MATLAB Windows | Figure Window | Editor Window

    Hello learners, Welcome to another tutorial on MATLAB. In the previous tutorial, we learned a lot about MATLAB's command window, saw some exciting commands related to the system, and found guidance from the pre-defined data. In this lecture, you will learn a great deal about the other two types of windows we defined in the earlier sessions. Let me discuss the points that will be discussed today. 

    • What is a Figure window?

    • How to get started with the figure window?

    • How can you change the background colour of the figure window?

    • What are some functions of the figure window?

    • Give a brief introduction to the editor window.

    • What is the live script?

    • How to run code on the live script?

    • What is the difference between the run all and run section options in MATLAB?

    We shall discuss all these questions during our session you are going to learn a lot of things because we have precise and interesting data for your learning and practice related to MALTAB.

    Figure Window

    MATLAB provides us with various functionalities related to the mathematical operations and working of different theorems in the best way. When talking about graphics, we come to know that they provide the perfect way to facilitate the user in the best way. So, it provides the user with a high-quality graphic window that shows the results of different calculations in a pictorial way. This will be clear when you see the implementation of different commands while designing your own figure window in the command prompt. 

    Getting Started with the Figure Window

    It is amazing to know that you can easily label your own figure window according to your task by using some simple commands. So, have a look at the following steps:

    Open your MATLAB software.

    Go to the command window.

    The syntax for creating a new figure window is as follows:

    figure (‘Name’, ‘Value’)

    Where the keyword “Name” tells MATLAB that you want to name your figure window according to your will, and the value shows the value that you want to store in place of the window’s name.

    Now, write the following command there.

    figure (‘Name’, ‘My Figure Window’)

    You will observe that it will create a square window that is labelled with your required title, and it will appear instantly when you finish your command and press enter.

    Making The Graph in Your Figure WIndow

    As we have been discussing since the beginning, the figure window has made the representation of different graphs super easy. You just have to put in the values and the graph with the accurate values will appear on the screen. If you want to do so, check out the following way:

    Go to your Command window and provide the values of the bar to MATLAB. In our case, we are storing these values in a variable named “Y”. Examine that all the values are stored in a square bracket. 

    Y = [1,44,66,8,33,89,34,4,22]

    In the next line, you have to write the function of the window's formation. Write the next line in your code.  We are making a new window because we wanted to teach you another thing related to the figure window. Write the next line in your code.

    figure ('Name', 'My Figure Window', 'NumberTitle', 'off')

    With the help of this command, MATLAB will surely create a window for you not only with the same title but also without any additional title other than your written statement, as we have observed in the previous case (title with the figure number).  It seems like an ordinary feature of the figure window, but most of the time, you are not going to use these options.

    In the end, we are using the pre-defined function of MATLAB named bar that creates the bar graph of the values stored in your variable Y.

    bar (Y)

    You will see, a nice and interesting figure window with all the data that was fed by you.

    Background Colors in Figure WIndow

    During this discussion, when I said that you are also going to design your own window, I meant that you can change the background colours and the data of the figure window made by you. If you want to do so, then you just have to make little changes in the command for the formation of your window.

    figure ('Name', 'My Figure Window', 'NumberTitle', 'off', 'Color', 'r');

    Here, the colour function is specified in red by using the keyword “r”. There are different keywords for different colours. Check the same command by using ‘b’ instead of ‘r’ and you will get the blue screen. 

    Functions in Figure Window

    Let me tell you another command through which you will get some points scattered on the screen with the blue background. Just write the following command on the command prompt.

    figure ('Name', 'My Figure Window', 'NumberTitle', 'off', 'Color', 'b')scatter((1:23),(rand(1,23));

    Here we have used two different functions that may be new to you. 

    The scatter function gives the MATLAB some values, say x and y, where x shows the starting point and y shows the ending point, in between which the distance between the points shown in the figure is taken by MATLAB. 

    On the other hand, the random function chooses one of the random numbers between the limits provided by us. After that, it shows the number of dots accordingly. Both of these are important functions, and one thing that must be kept in mind is that the limits of both these functions must be equal. Otherwise, MATLAB will make the error that the dimension of these functions must be the same. You can pick any number for these limits. 

    Editor Window in MATLAB

    The MATLAB editor is a fantastic window because most of the commands and functions that are related to different functions are done with the help of pre-defined commands and functions. We discussed the basic introduction of the editor window in our previous lecture. This time, we are discussing it deeply. MATLAB provides two versions of the editor window:

    1. Editor Window

    2. Live Editor

    To use the editor window, simply follow the steps that we are specifying here:

    • Open your MATLAB software.

    • Go to the command window.

    • Write “Edit” in the command window. 

    It will open a new screen where you can create multiple windows, and the screen now looks like this:

    As soon as you try to run this file, a window will appear that will require the information of the file where this code will be saved in your MATLAB folder. So, I suggest naming it meaningful so that any time you need the code, you simply click on the saved file, and your saved code will be shown as expected.

    The command window now lies below the editor window, and you can use it for several operations. The editor window is also referred to as the script window, and at this point, we want to work on the other type of editor, which is the live window. 

    • Go to the main menu of your screen and choose the live editor there. You will be directed to the new window.

    Let’s start by writing the code in this window. 

    • For now, I am going to show you the result of some coding and, hopefully, you will love it. 

    • Copy this code from here and paste it into the editor window. 

    For the compilation of this code, t=2:0.1:1

    x=[1 2 4 7]

    h=[4 7 8 1]

    a=xcorr(x,h)

    subplot(2,1,1)

    stem(a)

    title('Correlation')

    xlabel('Time / The Engineering Projects’)

    ylabel('Amplitude')

    grid on;

    • You have to press f5 for the compilation of this code. The advantage of this window is that the results can be seen instantly without the need to store the code in a file. 

    So, you will get the result as shown in the picture.

    For now, I am not going to elaborate on the code and the concepts, but for now, you just have to get an idea of how the live window is used. 

    The Difference in MATLAB Editor Windows

    The difference between these two types of editor windows is given below:

    Editor Window

    Live WIndow

    The code has to be saved in a separate file to see the results.

    There is no restriction on saving the results into a separate file. 

    The results are shown in a separate figure window if applicable. 

    The results can be seen instantly when we run the program by pressing f5 in a side window. 

    We can change the position and size of the figure window and can minimize it if required. 

    The results can be shown at the side of the code or just below it. 

    It is a simple window resembling the command prompt window with a white background. 

    It is a relatively stylish window with a grey background. 

    The compilation process shows the results all at once when we run the program. 

    An indicator at each line tells us the position of the current compilation line.

    Hence, both of them have the same type of work, but they are different with respect to some features that are used according to the skills and requirements of the user. 

    Live Script Options in MATLAB

    You can find different types of operations related to the live editor or simple editor window that you will use every time no matter what type of function it is performing. These options appear when you hover over the options present on the upper side of the screen just above the live editor window.

    For different operations on MATLAB, you can use all these windows, but for now, our concentration is on the live editor window. It gives us the independence to use the new, open and save file options. You are not new to these functions, so I am not going to elaborate, but the things that must be clarified here are the workings of the run all and run section options. 

    These buttons have the same function, but the way they work is a bit different. The "Run all" button obviously runs the code at once, but when we talk about the "Run section" button, it is somehow different from the first case. 

    Run Section in MATLAB

    The "Run Section" button gives us the independence to run the codes in different parts. It was designed to give ease to the coder because in most of the codes, we have long and confusing codes, and it feels like a gift from the designers because many times, you do not know which part of the code is not working or showing the error. So, it becomes super easy to run the code in different sections to check the results separately and detect the error.

    Hence, it was an important lecture where we found interesting information about the windows of MATLAB. Keep in mind, MATLAB has a gigantic amount of information about different types of functions used in math, and therefore, it provides sections and different windows for the usage and working of different tasks related to the academic and professional world in the best way. If we talk about the commands and functions along with all the features it provides with the help of these manus, then the lecture will become very lengthy. For now, your homework is to check the manus by applying different options to your code. 

    MATLAB has amazing windows for its work, and the figure window is one of the most important because it allows you to have the results in the form of graphs. By the same token, the editor window is the one that is used to write code and get the result in different ways. We have two types of windows to write code that is called editor windows and live scripts. Both of them seem alike but have different features, and programmers use them according to their needs.

    Differential Analysis of Fluid Flow

    In this article, I will explain the differential equations of fluid motion, i.e., conservation of mass (the continuity equation.  So without wasting any time, let us start.

    What is differential Analysis?

    As a part of this article, it is essential to know what differential analysis is and how we can apply it to explain continuity and Naiver Stroke’s theorem.

    Some of the essential key points related to the differential analysis are as follows:

    • Differential analysis is the application of a differential equation of fluid motion to any or every point in the flow field over a region called the Flow Domain.

    • Some readers might confuse the word differential with the small control volumes piled up on each other in the flow field.

    • Whenever the size of the control volume crosses the limit and extends to infinity, then the size of each control volume becomes so small that the conservation equations simplify to a set of partial differential equations. These partial equations can easily be applicable whenever required in any flow field.

    • As I have discussed earlier, two differential equations, the Law of Conservation of Mass (Continuity Equation) and Newton’s Second Law (Naiver Strokes Equation), are the ones on which there is a drastic change in the temperature and density such kind of equations are easily solved with the help of differential equation.

    • The following diagram shows the study of control volume in which the control volume seems to be much similar to the black box.

    • Now, the second diagram shows that all the flow points are solved within the flow domain in the case of differential analysis.

    • While solving the differential equation in the case of incompressible flow, there are about four unknown, i.e., velocity components (u, v, w), one pressure component, and four equations (three equations from Naiver Strokes Law and one from Law of Conservation of Mass).

    • There are variables and constants in equations, but in differential equations, all the variables are solved at once because, in such situations, the equations are coupled. Now, what is coupled, and how are equations coupled? We will see it in the upcoming topics.

    • While solving the differential equation, the boundary conditions must be defined.

    We are moving towards the first important part of our article, i.e., the Law of Conservation of Mass. Let us start.

    Conservation of Mass–Continuity Equation

    In one of my previous articles, I have extensively explained the conservation of mass. But now, here, I will explain the derivation in terms of the infinitesimal control volume by the divergence theorem. So let’s start.

    To explain the topic, I will divide it into essential critical points in the following way.

    • First of all, let us recall the conservation of the mass equation through the application of Reynold’s Transport Theorem;

    0=∫CV∂ρ∂t dV+∫CSV.n dA   (a)

    The equation is for the fixed and control volumes. 

    • In the case of well-defined and selected inlets and outlets, the equation will be as follows:

    ∫CV∂ρ∂tdV=inm-outn  (b)

    • The above equation explains that the rate of change of mass within the control volume equals the rate at which mass flows into the control volume subtracting the rate with mass flow out of the control volume.

    Now I will explain the derivation using the divergence theorem.

    Derivation Using the Divergence Theorem:

    The other name of the divergence theorem is called Gauss’s Theorem.

    The statement of the divergence theorem is as follows:

    The Divergence Theorem (Gauss’s Theorem) is used to transform a volume integral of the divergence of a vector into an area integral over the surface that defines the volume.

    Some of the essential key points related to the Divergence theorem are as follows:

    • Mathematically, the divergence theorem is defined as the divergence G and can be written as follows:

    ∫vV.GdV=∮AG.n dA   (c)

    • There are two kinds of integration in the equation one is simple, and the other has circled it. This indicates that the entire area surrounds the volume. So as you can see that the equation is beneficial in gaining data. 

    • The primary purpose of using the divergence theorem is to transform the volume integral of the divergence vector into an area integral over the surface, and that surface defines the volume.

    • In the case of any vector, the divergence will be defined as a G, and the equation as m will be used to describe it.

    • In some cases, we also define the divergence as follows:

    G=ρV

    • We can also define it by playing with the values, and for that, we substitute the value of equation (c) into equation (a), and we will get the results as follows:

    0=∫cv∂ρ∂t dV+∫cvV. (ρV) dV

    • As you can see that there are two integrals, so to get the required equation, we will combine the two integrals into one and then the result will be as follows:

    ∫cv∂ρ∂t+V. VdV=0

    • Now, we come to the conclusion that the equation that is mentioned above is for the control volumes, regardless of any size and shape.

    • So, the statement above is only possible if the terms within the brackets are identically zero. 

    • Moving towards the critical statement, i.e. the equation of continuity. So the general differential equation for the conservation of mass is also known as the continuity equation, and the equation is as follows:

    ∂ρ∂t+V. V=0

    • So, this is the equation of continuity. This equation is for compressible flows only and does not implement for incompressible ones; the -mentioned equation ensures the validity of the flow domain point.

    Now that is all from the derivation using the divergence theorem. The next topic is also a part of it. Have a look.

    Derivation using an Infinitesimal Control Volume

    The continuity theorem is defined in different ways, and one of them will describe by me. The continuity theorem starts with the control volume, and, taking it as a base, I will tell the whole topic. 


    So following are some essential key points related to the topic:

    • We will start with the assumption. Let us consider an infinitesimal box that controls volume and aligns with the axes in the Cartesian Coordinates system. 

    • The following is the diagram that shows the box-shaped control volume.

    • As you can see from the diagram along the x-direction, the length is mentioned as dx, in the y-direction as dy and along the z-direction as the dz, respectively.

    • Moreover, at the centre of the box, there is information that says that the density is defined as a symbol and the velocity is defined in velocity components as u, v, and w, respectively.

    • So, we use Taylor's Theorem within the box at different locations away from the centre. And to define this point, we will use an example as follows:

    (u)centre of right face=ρu+∂(ρu)∂xdx2+12!2(ρu)x2(dx2)2

    • In the case of the above-mentioned equation, the control volume has just limited to a point only, and the higher power or even the second power terms are negligible.

    • So, for the six faces of the box, we use the Taylor series expansion to density times the normal velocity component at the central point of each of the six faces, so they are as follows:

    • Center of Right Face

    (u)centre of right face≅ ρu+∂(ρu)∂xdx2

    • Centre of left face

    (u)centre of left face≅ ρu-∂(ρu)∂xdx2

    • Centre of Front Face

    (w)centre of front face≅ ρw+∂(ρw)∂zdz2

    • Center of Rear Face

    (w)centre of rear face≅ ρw-∂(ρw)∂zdz2

    • Center of Top face

    (v)centre of top face≅ ρv+∂(ρv)∂ydy2

    • Center of Bottom face

    (v)centre of bottom face≅ ρv-∂(ρv)∂ydy2

    • Now, there is another statement that says that

    The mass flow rate into or out of the faces of the box is equal to the density times the normal velocity components at the centre point of the face times the surface area of the face.

    • We can define it as mathematically as follows:

    m=VnA

    • The above equation is valid for each face. The Vn shows the magnitude of the normal velocity through the face, and the A shows the surface areas of the face. 

    • The following diagram shows the mass flow rate through each face of our infinitesimal control volume; you will easily get the idea about it:

      • So all the theoretical background that I have mentioned in the diagram that is above can be easily understandable by the diagram.

      • For all the nonnormal velocity components, the truncated Taylor series expansions at the centre of each face can also be defined. But we have not represented as these components are tangential to the face.

      • Now we will move towards another equation, and that equation says the control volume shrinks at any of a point, and the value of the volume integral on the left side of the equation (b) will become as follows:

      ∫cv∂ρ∂t dV≅∂ρ∂tdxdydz

      • As we know that the volume of the box is dx, dy, and dz, respectively. 

      • Here is a trick: with the help of the diagram, we can apply the approximations from the figure to the right side of the equation mentioned above. In this case, we will add all the mass flow rates at the inlet and the outlet of the control volume through all of the faces. Then take a left, bottom, and back faces contributing to the mass flow rate. Then concerning the equation, the right side will be as follows:

      inm≅(ρu-ρu∂xdx2)dydz+ρv-ρv∂ydy2dxdz+(ρw-ρw∂zdz2)dxdy

      The following are the faces that are mentioned in the equation:

      • Left Face =ρu-ρu∂xdx2dydz

      • Bottom Face=ρv-ρv∂ydy2

      • Rear Face=(ρw-ρw∂zdz2)dxdy

      The next topic is also part of the Continuity Equation. So without wasting any time, let us start.

      Alternative Form of the Continuity Equation

      There is also an alternative way to present the continuity equation as we know that the following equation is according to the product rule of divergence theorem:

      ∂ρ∂t+V. V=∂ρ∂t+V. ρ+ρ.V=0

      In order to explain the continuity equation alternative way, I will explain it in a few important key points:

      • The following is the alternative form of presenting the continuity equation:

      1DρDt+.V=0

      • The above-mentioned equations show the fluid element that is flowing through the flow field, and it is also called the material element. Here there is a change that the .V is the change in the density.

      • So we can say that if the change in the density of the material element (fluid element) is small as compared to the magnitudes of the velocity gradient in the .V also if the element moves around, then the flow is said to be incompressible, and it is limited to it only.

      So that is all from the alternative way of presenting the continuity equation. Now the next topic is another part of presenting the continuity equation.

      Continuity Equation in Cylindrical Coordinates

      The cylindrical polar coordinates system is a way of presenting the terms in (r,,z). it is also known as the cylindrical coordinates system. 

      In this topic, I will show you how the terms can be explained in a cylindrical system, and it is another way of presenting the continuity equation. So following are some of the important key points related to the topic. Have a look at it:

      • There can be three-dimensional, one-dimensional and two-dimensional cylindrical coordinates, but here in this topic at the start, I will explain in terms of the two-coordinates system only.

      • The following are the explanation of the (r, θ):

      • Here, r shows the radial distance i.e., from the origin to any point (let us say P). 

      • Then there comes , now which shows the angular measurement from the x-axis (if we talk about generally, then is defined as a positive value, and it is in a counterclockwise direction).

      • The following is a figure that shows the complete explanation of the theoretical background:

      • There are more important terminologies that need to be defined. So following is the explanation of it:

      • ur and u are the velocity components 

      • er and e are the unit vectors.

      • In the case of three-dimensional, there is obviously a z-axis. So in order to show the points, the following diagrams explain well. Have a look at it.

      • So as you can see that in the three-dimension case, there are two more values, one for the velocity component and the second for the unit vector.

      • So the following equation shows the coordinate transformation:

      r=x2+y2

      x=rcos

      y=sin

      θ=yx

      • So following is the equation that expresses the continuity equation in terms of cylindrical coordinates.

      ∂ρ∂t+1r(rρur)r+1r(rρu)+1r(rρuz)z =0

      Thank you for reading.

      Drag and Lift in Fluids

      It is one of the most critical topics whenever. It is related to the resistance a fluid faces in motion. A fluid exerts a force on a body in a different direction. Now the main question is, what is drag? And what do we know about it?

      What is Drag?

      The definition of drag is as follows:

      The force exerted on a flowing fluid in the direction of fluid flow is called drag.

      Some of the essential key points related to the drag are as follows:

      • In order to elaborate on the drag force through an example. The body is attached to calibrated spring, and it is used to measure the displacement in the direction of flow. 

      • The drag balances are one of those devices that are commonly used to measure the drag force.

      • It is not wrong to say that the drag force is much similar to the frictional force.

      • The more reduction in the drag force, the less fuel will be consumed. 

      • An interesting fact about drag is that we can also produce a beneficial effect by drag, so we need to maximize its value. In this scenario, drag helps in pollen flying, usage of parachutes, movement of leaves and much more. These are one of the common examples used in our daily life.

      • The drag force is a combination of pressure and the wall shear forces in the flow direction.

      What is Lift?

      In order to explain the lift in easy words, let us have a look at the definition.

      The component of pressure and the wall shear forces in the normal direction to the fluid flow that tends to move the body in that direction is called lift.

      Some of the important key points related to the lift is as follows:

      • Whenever we are dealing with lift and drag, these both have different responsibilities. In the case of two-dimensional flow, the resultant of the shear and the pressure forces are divided into two important components. The flow in one direction only is the drag force, whereas the normal flow is the lift.

      Mathematical Presentation of Lift and Drag:

      The lift and drag have the equations through we can find the accurate values theatrically and can compare them with the practical ones.

      • To calculate the differential drag force, we have a differential area dA on a surface PdA and w so the equation will be:

      dFD=-P dAcos +wdAsin

      • The differential lift force is as follows:

      dFL=-P dAsin -wdAcos

      • By integrating the above two equations, we can get the total drag and lift forces that are acting on a body:

      • Drag Force

      FD=∫AdFD=∫A(-Pcos +wsin )dA

      • Lift Force

      FL=∫AdFL=-∫A(Psin +wcos )dA

      • The above equations show the skin friction (wall shear) and pressure, which contribute to the drag and lift.

      • The lift and the drag are a strong function of angle attack.

      • The drag and lift forces depend on the upstream velocity, density, size, shape, and orientation of the body. It is better to work with the dimensionless numbers that are used for the representation of drag and lift characteristics of the body.

      • The drag and lift coefficient equations are as follows:

      • Drag Coefficient

      CD=FD12V2A

      • Lift Coefficient

      CL=FL12V2A

      Here A is the ordinarily Frontal Area.

      Friction and Pressure Force

      The topic is related to drag and lift. In order to define the friction and pressure forces, I will explain in few key points:

      • The net force exerted on a body by fluid in the flow direction drag due to the combined effect of wall shear and pressure forces.

      Skin Friction Drag:

      The part of due directly to wall shear stress called skin friction drag.

      Pressure Drag

      It is the part that is due directly to the pressure P, called the pressure drag.

      • The friction and pressure drag coefficients are presented mathematically as follows:

      • Drag Coefficients Friction

      CD, friction=FD, friction12V2A

      • Drag Coefficient Pressure

      CD,pressure=FD,pressure12V2A

      • So these are the drag coefficients of pressure and friction.

      • If the values of these coefficients are available, then it becomes easier for us to find the value of the total drag coefficient and total drag force. The formulae of both of these are given as follows:

      • Total Drag Coefficient

      CD=CD,friction+CD,pressure

      • Total Drag Force

      FD=FD,friction+FD,pressure

      • The friction of drag is the main component of the wall shear force, and this force is in the direction of flow. 

      • In the case of a flat surface, the value of friction drag is zero, and it is normal to the flow direction. The value is said to be the maximum for a flat surface parallel to the flow.

      • With the increase in the viscosity, there is an increase in the drag.

      • Another exciting fact about it is that Reynold’s Number is inversely proportional to the viscosity of a fluid. So when the value of Reynold’s number is high, then the value of the total drag or the friction drag is less.

      • When the value of Reynold’s number is less, it is due to the friction drag and mostly happens in the streamlined bodies.

      • the bodies having a large surface area have a significant friction drag value. But it is independent of the surface roughness.

      • In the case of pressure drag, it is proportional to the frontal area. 

      • The value of drag pressure for the blunt bodies is maximum; for the streamlined bodies is less, and in the case of the thin flat plates that are parallel to the flow, the value is zero.

      Reducing Drag by Streamlining

      It is also one of the important topics of drag. 

      The following are some important key points related to reducing drag by streamlining:

      • As I have discussed earlier that the drag pressure in the case of streamlined bodies is less.

      • Decrease the drag for a streamlined body by reducing the flow separation, ultimately reducing the pressure drag.

      • The streamlining delay the boundary layer separation resulting in a decrease in the pressure drag and an increase in friction drag.

      • The following diagram shows the difference in the values of friction, pressure, and total drag coefficients of a streamlined strut.

      • As you can see from the diagram, the value of total drag at minimum is D/L=0.25.

      • The drag coefficient value will be five times in the case of a circular cylinder having the same thickness as the streamlined shape.

      • In the case of an elliptical cylinder shape, the value of the drag coefficient is less. The elliptical cylinder shape is considered the perfect example for defining the effect of streamlining on a drag coefficient.

      Flow Separation

      I will define flow separation extensively, so the following is the definition of it.

      • The fluid has high velocity when force flows over a curved body. Similarly, fluid can climb uphill on a curved surface without distraction.

      • At high velocities, the fluid stream detaches itself from the body’s surface, known as flow separation.

      • A flow can be separated from a surface when fully submerged in an immersed gas or liquid.

      Parallel Flow over Flat Surface

      There are many essential terminologies for this topic, and the following are some important key points, equations, and definitions for the parallel flow over the flat surface. So let us start.

      • The following diagram shows a flat plate on which a fluid has flowed.

      • Taking this diagram as a reference, I will explain the whole topic through this.

      • Here, in this flat plate, the x-axis is measured along the plate surface (starting from the leading edge of the plate in the direction the fluid is flowing), whereas the y-coordinate is measured from the surface in the normal direction.

      • The surface’s velocity is equal to the velocity of the fluid that travels along the x-coordinate.

      • As you can see through the diagram, for our convenience, we have assumed that the fluid is in adjacent layers and they are piled onto one another

      • By doing so, the velocity of the first layer of fluid adjacent to the plate becomes zero, and this is due to the no-slip condition.

      • The first layer impacts the other layers by slowing the motion of particles of other different. And the process goes on as the layer slows down the next layer’s molecules. 

      • The presence of the layer is then felt up to some normal distance (), from the plate, beyond which the free-stream velocity remains unchanged. 

      • There are some critical regions and layers present on this layer, and they are defined as follows:

      • Velocity Boundary Layer

      It is the region of the flow that is above the plate bounded by normal distance () in which the effect of the viscous shearing force caused by fluid viscosity is felt.

      • Irrotational Flow Region

      It is the region where the frictional effect is negligible, and the velocity is constant.

      • The thickness of the boundary layer (δ) is the distance y from the surface at which u=0.99V.

      • There is a hypothetical line that is present on the layer (u=0.99V) that divides the flow into two regions, and they are named as follows:

      • Boundary Layer Region

      • Irrotational Flow Region

      • In this flat plate parallel to the flow condition, the pressure drag is zero, and the drag coefficient equals the friction drag coefficient. Mathematically we can present it as follows:

      CD=CD,friction=Cf

      Here Cf is the drag friction coefficient.

      • The equation for calculating the friction force on the plate is as follows:

      FD=Ff=12CfAρV2

      Here the A is the surface area of the plate.

      • From the diagram, you have observed that the velocity profile is in laminar and turbulent flows.

      • Also, the turbulent is much fuller than the laminar one. As it has four regions, and they are named as follows:

      • Viscous Sublayer

      • Buffer Layer

      • Overlap Layer 

      • Turbulent Layer

      • The transition of laminar to turbulent flow is dependent on the geometry of the surface, roughness, upstream velocity, surface temperature, and many things.

      • The Reynold’s number at a distance x from the leading edge of a flat plate is as follows:

      Rex=ρVx=Vxv

      • In the case of a flat smooth plate, the transition from a laminar to a turbulent flow starts at Reynold’s number RE≅1×105. The flow does not become turbulent until the value of Reynold’s number reaches RE≅3×106

      Friction Coefficient

      The following are some key points related to the friction coefficients:

      • In the case of laminar flow, we can calculate the value of friction coefficients by using the law of conservation of mass and momentum.

      • In the case of turbulent flow, it should be calculated experimentally and should be expressed in the empirical correlation.

      • The drag force for the whole surface can be calculated by using the average friction coefficient value.

      • In some cases, if we want drag force for a specific location, then in this condition, we must know the local value of the friction coefficient.

      • If we have the value of local values, then it becomes easy for us to calculate the average friction coefficient values:

      Cf=1L0LCf,xdx

      Flow over Cylinders and Spheres

      It is one of the important related to lift and drag. So following are the important key points related to the flow over the cylinder and spheres:

      • In our daily life, if we look around, there are multiple examples of it. In tubes (shell and tube heat exchanger) involves the internal and external flow over the tubes.

      • In sports, cricket, soccer, and tennis balls are the best examples of this topic.

      • For calculating the circular cylinder or sphere, the external diameter is taken as D.

      • In Reynold’s number, the formula is as follows:

      Re=VDv

      Here the V stands for the uniform velocity of the fluid as it approaches the cylinder and sphere.

      • Here, the value of the critical Reynold’s number is Recr≅2×105.

      • The change in total drag coefficient value is observed for the flow of cylinders and spheres.

      • It is not wrong to say that the drag force is due to the friction drag at the low value of Reynold’s number (Re< 10) and in the case of pressure drag at a higher value of Reynold’s number (Re>5000).

      • The following diagram shows the separation of the laminar boundary layer with the turbulent over a cylinder. 

      Effect of Surface Roughness

      In the previous topic, I discussed this thing that the impact of having a surface makes a huge difference. So while discussing the cylinders and the spheres, it becomes important to discuss them in detail.

      The following are some essential key points related to the topic:

      • The increase in surface roughness increases the drag coefficient in the case of turbulent flow.

      • For the streamlined case, it is also the same. But for the spheres and the cylinders, the increase in the roughness of the surface decreases the coefficient of drag. This means they have an indirect relationship.

      • The following diagram shows the indirect relation for cylinders and spheres.

        • The indirect relation is done by tripping the boundary layer into turbulence at the lower value of Reynold’s number. The result is that the fluid is close in behind the body, reducing the pressure drag force.

        • The value of Reynold’s number is Re≅2×105, and the value of the drag coefficient is  CD≅0.1 in the case of a rough surface along with D=0.0015. In the case of a smooth surface, the values changes, and they become CD≅0.5.

        • The value of Reynold’s number for the rough sphere is Re≅106, and the drag coefficient value is CD≅0.4.

        • So the value of the drag coefficient for a smooth sphere is CD≅0.1.

        • The rougher the sphere will become, the more drag will also increase.

        • In order to exemplify the values, let us take an example of a golf ball. The velocity value ranges from 15 to 150m/s for the golf ball, and the value of Reynold’s number is 4×105,.

        Lift

        At the start of the article, I have already discussed what lift is. Here in this topic, I will explain extensively about the lift and the mathematical equation.

        In order to explain the topic in a symmetric manner, I will explain it in key points, and these are as follows:

        • As you know that lift is the component of the net force, and this net force is because of the viscous and pressure force. 

        • The coefficient of the lift is explained as follows:

        CL=FL12V2A

        • The A here presents the planform area, and this area is viewed by someone that is looking at it from above in a direction normal to the body. 

        • The V is the upstream velocity.

        • We will consider the airfoil with a width b and chord length c and the planform area as A=bc, respectively.

        • The following is the diagram that shows the airfoil structure.

        • Here, there is a term called wingspan or span. It is the distance between the two ends of the foil. 

        • In the case of aircraft, the wingspan is the total distance between the tips of two wings.

        • Another important term is wing loading. It is the average lift per unit planform area FLA.

        • The airplanes are all based on the lift.

        • The purpose of discussing the lift in detail is to know how airfoils are designed and how they generate lift by keeping the value of drag minimum.

        • The streamlined bodies, such as airfoils that intends to generate the lift, have a negligible lift, and the wall shear is parallel to the surface.

        • I will show you the pictorial representation of the irrotational and actual flow past the non-symmetrical two-dimensional airfoils.


        • The following diagram shows the irrotational flow past a symmetrical airfoil (here the lift is zero).

        • The following diagram shows irrotational flow past a non-symmetrical airfoil (having zero lift).

        • The following diagram shows the actual flow past a non-symmetrical airfoil, and here the lift is positive.

        Conclusion

        Hope you enjoy reading the article. I have tried my best to explain you every point in easy words. Thank you for reading.

        Types of Fluid Flows

        Hello Friends. I hope you are doing great. Here I am with another exciting topic of fluid mechanics, i.e. flow over bodies. In this article, I will explain the flow of fluids, the flow rate, their nature, the flow in pipes and much more. Fluid mechanics is all related to the fluid and its nature. I will discuss the forces that are on the body that is immersed in a fluid and the flow that is over the body. As the title shows, the main emphasis will be on the lift and drag forces. Moreover, the external and the internal flow will also be discussed in this article. And I am sure that you will enjoy reading this article. So without wasting any time, let us start.

        I will start with an introduction to fluid flows.

        Introduction

        In this article, our focus will be the fluid flow over the bodies immersed in the fluid. There are six different types of flows, and they are named as follows:

        1. Steady and Unsteady Flow

        2. Uniform and Non-Uniform Flow

        3. One, two and three-dimensional Flow

        4. Rotational or Irrotational Flow

        5. Laminar and Turbulent Flow 

        6. Compressible and Incompressible Flow

        Before discussing them extensively, I will briefly explain the external flow.

        External Flow

        Let me explain the external flow in critical points:

        • We will take two situations. The first situation says that the body is at rest, and the fluid flow moves over it, and the second one says that the body is moving through some quiescent fluid.

        For example: 

        • If you look around, there are building standing still, and the wind is blowing over the building. This is the case when the body is stationary

        • The second condition is that the car is moving through the air.

        So now, these are two different scenarios, but the main thing that matters is the relative motion of the fluid and the body. So, such motions are analysed by fixing the coordinate system on the body, called External Flow or Flow over the body.

        Now moving towards the six types of flows, let us start explaining them one by one.

        Steady and Unsteady Fluid Flow

        Steady Flow

        The definition of the steady flow is as follows:

        The steady flow is where pressure, velocity, and cross-section differ from one point to another, and it does not change with time.

        Some of the essential key point about the steady flow is as follows:

        • There are changes in the flow, but the change is so small that one particular parameter remains constant for a fixed period. But we can say that it is an ideal case because, in the actual case, there are very few chances that the parameters can remain constant.

        Unsteady Flow

        The definition of the unsteady flow is as follows:

        Changes in parameters at some stage can make the floe unstable. In practical cases, there is always a change in values of pressure and velocity values. Average values are constant; then, the flow is constant.

        Some of the essential key point about the unsteady flow is as follows:

        • The unstable flow is said to be uniform and non-uniform both.

        • In the case of uniform flow, the cross-sectional area of fluid flow through the stream is said to be constant.

        Uniform and Uniform Flow

        Uniform Flow

        The definition of the uniform flow is as follows:

        The distance along the flow path is constant then the flow parameter is also said to be constant. The fluid flow is called uniform flow.

        Some of the essential key points about the uniform flow are as follows:

        • The cross-sectional area in the case of uniform flow is constant.

        • One of the best examples of uniform flow is the flow through the pipeline.

        Non-Uniform Flow

        The definition of the non-uniform flow is as follows:

        The non-uniform fluid flow is due to the variations in the flow parameters, varying at different points on the flow path.

        Some of the essential key points about the non-uniform flow are as follows:

        • It is evident, as the names show, that the parameters do not remain constant. A change in velocity can be observed; ultimately, the flow is also said to be non-uniform.

        • In practical cases, the flow near the solid boundary is said to be a non-uniform flow.

        One, two and three-dimensional Fluid flow

        The term has three types of fluid flows. 

        One-dimensional Flow

        Starting the one-dimensional flow its definition is as follows:

        The flow that travels in one dimension and changes parameters such as pressure, velocity, depth etc., in one flow direction only is said to be one-dimensional flow.

        Some of the essential key points about the one-dimensional flow are as follows:

        • The change in parameters in one direction at a given moment is considered a one-dimensional flow.

        • There are many chances that the flow can be unstable if the parameter alters in time, but it is still not across the cross-section.

        Two-dimensional Flow

        The definition of the two-dimensional flow is as follows:

        The flow parameters differ in the flow direction, and in one direction in the right angles, the flow is then said to be two-dimensional flow.

        Some of the essential key points about the two-dimensional flow are as follows:

        • Toto elaborates on the two-dimensional flow; following diagram explains the flow well. Have a look at it.

        • The flow is either in the x direction or y. there is no change in the z-direction.

        • In two-dimensional flow, streamlines are usually curved in one plane and the same on every parallel plane. 

        Three-dimensional Flow

        The definition of the three dimensional flow:

        The element of the fluid moves in three dimensions (translation, rate of deformation and rotation) in space. Such a kind is called the three-dimensional flow.

        Some of the important key points related to the three-dimensional flow is as follows:

        • The following is the diagram that shows the three-dimensional flow:

        Rotational and Irrotational Fluid Flow

        Let us start with the rotational flow:

        Rotational Fluid Flow

        The definition of the rotational flow is as follows:

        The flow in which the fluid particles rotate on their axis while along the flow line is called the rotational fluid flow.

        Irrotational Fluid Flow 

        The definition of fluid flow is as follows:

        The flow in which fluid particles do not rotate in their own axis when theyw along the flow lines.

        The visual representation of both flows is as follows;

        • The following is the diagram that shows the rotational fluid flow:

        • The following diagram shows the irrotational fluid flow:

        Laminar and Turbulent fluid flow

        Let us start with laminar flow

        Laminar Flow

        The definition of the laminar flow is as follows:

        The flow in which fluid particles move in a well define path and the streamlines straight and parallel. Such kind of flow is called laminar flow.

        Some of the important key point related to the laminar flow is as follows:

        • The pictorial representation of the laminar flow is as follows:

        Turbulent Flow

        The definition of the turbulent flow is as follows:

        The flow in which the fluid particles do not move in a well define path and it lead to high energy losses throughout.

        Some of the important key point related to the turbulent flow is as follows:

        • The pictorial representation of the turbulent flow is as follows:

        Compressible and Incompressible Fluid Flow

        Compressible Fluid Flow

        The definition of the compressible fluid flow is as follows:

        The flow in which the density of fluid varies from one point to another point (not constant) is called the compressible flow.

        • The pictorial representation of the compressible flow is as follows:

        Incompressible Flow

        The definition of incompressible flow is as follows:

        The flow in which the density of the fluid flow is constant is said to be incompressible flow.

        • The pictorial representation of the incompressible flow is as follows:

        That is all from the types of fluid flow. Now, we will move towards the main topic, i.e. lift and drag. Let us start.

        Sending SMS & Call with GSM Module and Raspberry Pi 4

        Greetings, and welcome to another tutorial in our series on the raspberry pi 4 Python programming. The previous guide covered the basics of transmitting data over the radio using the nrf24l01 chip in Pi 4. We also learned about interfacing Arduino and raspberry pi 4 and sending radio signals between the two devices. However, this tutorial will walk you through building a Raspberry Pi-based mobile phone with a microphone and speaker for making and receiving calls and reading text messages (SMS). This Project also serves as a proper GSM Module for the Raspberry Pi interface, with all the necessary Code to run the most fundamental features of any modern smartphone. First, we will understand what gsm is, its architecture and how it works, then we will learn how to program it in our pi 4; therefore, let us begin.

        Where To Buy?
        No.ComponentsDistributorLink To Buy
        1Jumper WiresAmazonBuy Now
        2LCD 16x2AmazonBuy Now
        3Raspberry Pi 4AmazonBuy Now

        Components:

        • Raspberry Pi 4

        • GSM Module

        • 16x2 LCD

        • 4 *4 Keypad

        • 10k pot

        • Breadboard

        • Connecting jumper wire

        • Power supply

        • Speaker

        • Microphone

        • SIM Card

        • Loudspeaker

        Structure and Uses of the Global System for Mobile Communications

        The acronym "GSM" refers to the "global system for mobile communication" and is the name of a type of mobile communication modem (GSM). Bell Labs was responsible for conceptualizing GSM in the 1970s. It's one of the most common forms of mobile communication around the globe. The 850MegaHertz, 900MegaHertz, 1800 Megahertz, and 1900 Megahertz frequency bands are utilized by GSM networks, which are part of an open and digital mobile network used to carry voice and data services.

        Using the telecommunications method of multiple time division access (TDMA), GSM technology was created as a digital system. For transmission, a GSM converts analog signals to digital ones, compresses them further and delivers them through a channel sharing bandwidth with two data streams from separate clients. The data rates transported by the digital system range from 64 kilobytes per second to 120 Megabytes per second.

        In a GSM network, macro, micro, and umbrella cells coexist. The implementation context determines the specifics of each cell. The macro, micro, and umbrella cell sizes are in use in a GSM network. Each cell may have a different range of coverage depending on the setting.

        Time-division multiple access (TDMA) works by giving each user a specific amount of time to transmit on the same frequency. It's flexible, supporting data rates from 64kbps to 120Mbps and allowing for clear voice communications.

        Structure of GSM-Based Technologies

        The following are the primary components of the GSM architecture.

        • Connectivity and Switching Infrastructure (NSS)

        • All three of these components—the Base Station (BS), the Mobile Station (MS), and the Operations and Maintenance Subsystem (OSS)—are necessary for proper communication (OSS)

        Network Switching Subsystem (NSS)

        Each component of the GSM system design contributes to what is collectively called the core system/network. In this case, the mobile network system is primarily controlled and interfaced with via a data network consisting of several different components. Listed below are some of the most crucial elements of the underlying network.

        Mobile Switching Centre (MSC)

        One of the essential parts of a GSM network is its core network, where the Mobile Switching Center (MSC) resides. This MSC performs the same functions as a common switching node in an ISDN or PSTN. Still, it provides additional features to accommodate mobile users' requirements, such as authentication, registration, inter-MSC handovers, call localization, and routing.

        In addition, it gives users an advantage in connecting their mobile phone networks to the PSTN (public switched telephone network) for making and receiving landline calls. To facilitate mobile-to-mobile calls across different networks, interfaces to all other switched telephone networks ( PSTN center servers are given.

        Home Location Register (HLR)

        Every subscriber's administrative details, including their last known location, are stored in this HLR database. This manner, calls can be routed over the GSM network to the appropriate mobile switch base station. If a call comes in when an operator has their phone turned on, the network can determine which base transmitter station the call is coming from and link it to the correct phone.

        When the phone is turned on but not being used, it nevertheless registers to ensure the HLR system is aware of its current location. Each network has a single HLR, which may be physically split across several data centers for practical reasons.

        Visitor Location Register (VLR)

        To facilitate the VLR's desired services for the individual subscriber, it incorporates data from the HLR network. It is possible to run the visitor coordinates register independently, but it is most commonly implemented as a core component of the MSC. Because of this, getting access is more manageable, and it takes less time overall.

        Equipment Identity Register (EIR)

        The Equipment Identity Register (EIR) is the part of the network infrastructure in charge of deciding whether or not certain pieces of mobile equipment are allowed access. The International Mobile Equipment Identification (IMEI) numbers uniquely identify each mobile technology work.

        This IMEI number is permanently embedded within the mobile device and checked by the network after registration. Depending on the data in the EIR, the mobile phone may be given one of three possible network access states: allowed, banned, or monitored.

        Authentication Centre (AuC)

        When users insert their SIM card into their phone, the secret key is stored in a secure file known as the AUC (authentication center). The AUC sees the extensive application as a radio channel coding and verification standard.

        Gateway Mobile Switching Centre (GMSC)

        In the absence of location information for the mobile station (MS), a call placed by a ME terminates with the GMSC (Gateway Mobile Switching Centre). Using the Mobile Subscriber Identifier Service Data Number (MSISDN) and the HLR, the GMSC can locate the specific MSC that has been visited and connect the call to the appropriate location. It's unclear what the "MSC" part of GMSC stands for, as the gateway procedure does not require relating to an MSC.

        SMS Gateway (SMS-G)

        Both SMS-Gateways are referred to collectively as the SMS gateway in the GSM specifications. The messages passing via these gateways are directed in various ways.

        Sending a short message to mobile equipment (ME) requires the usage of the Short Messaging Service Gateway Switching Center. Short messages sent over a mobile network are routed through the  SMS Inter-Working Switching Center. While the SMS-primary GMSC's function concerns the GMSC, the SMS-IWMSC serves as a constant endpoint for access to the Short Message Service Centre.

        These were the primary nodes in the GSM system's infrastructure. While they frequently shared physical space, the entire middle network would sometimes be broadcast throughout the country. In the event of a failure, it will provide a degree of leeway.

        Base Station Subsystem (BSS)

        The connection point between the mobile node and the broader network infrastructure. The radio transceivers and protocol management for mobile devices are housed in the Base Transceiver Station. In addition, a Base Station Controller manages the Base Transceiver and serves as a bridge between mobile devices and the mobile switching hub.

        The network subsystem handles connectivity between the network and the mobile stations. The Phone Service Switch Centre is the backbone of the Network Subsystem, allowing users to connect to other networks (ISDN, PSTN, etc.). The GSM system's ability to route calls and allow for roaming depends on two additional components, the Home Location Record and the guest Location Record.

        In addition, it stores the Equipment Identity Register, which keeps track of all the mobile devices and their associated IMEI numbers. The acronym IMEI refers to the unique identifier for mobile devices worldwide.

        In the second generation of GSM network design, the mobile devices communicate with the BSS, or Base Station Subsystem. These components comprise this subsystem, and each will be examined.

        Base Transceiver Station (BTS)

        As part of a GSM network, the radio Tx, Rx, and their associated antennas make up the base Transceiver Station, which is used for transmitting, receiving, and communicating directly through mobiles. The base station is the central component of each cell, and it communicates with mobile devices using an interface known as the Um interface and related protocols.

        Base Station Controller (BSC)

        The base station controller (BSC) is employed for the following step back into GSM technology. This controller is typically co-located within one of the base transceiver stations it controls. This controller handles radio resource management, including channel allocation and handover between base station groups. Over the Abis interface, it communicates with the BTSs.

        The acceptable radio technology is used by the GSM network's subsystems component in the ground station to ensure that multiple operators can utilize the system at the same time. Each base station can support many operators because each channel can support up to eight users.

        The network provider strategically places these to ensure comprehensive coverage. A base station, sometimes known as a "cell," can surround this space. Signals can't be prevented from bleeding into neighbouring cells, and the channels used in one don't transfer to the next.

        Mobile Station

        Mobile phones include a transceiver, a display, and a CPU, all of which are network-connected and operated using a SIM card. In a GSM mobile transmission medium, the operator monitors and controls the mobile station or mobile equipment, which are most commonly represented by cell phones. Their size has shrunk significantly while their functionality has skyrocketed. The benefit of a much longer interval between charges is still another advantage. Phone hardware and the subscriber identity module (SIM) are two of many components.

        A mobile device's hardware consists of its primary components, such as the housing, screen, battery, and electronics used to generate the signal and process the signal receiver before transmission. The IMEI is a unique number assigned to each mobile device. This feature can be permanently programmed into a phone throughout its manufacturing process. During the registration process, the network accesses this database to see if the device has been flagged as stolen.

        A user's identity on the network is stored in the information contained in their SIMcard. It also includes other data, such as the IMSI number. With this IMSI stored in the Sim, the phone user could easily switch phones by swapping SIM cards. As a result, if switching to a new mobile phone were simple and didn't require a unique phone number, more people would do it, generating more revenue for network operators and contributing to GSM's overall economic triumph.

        Operation and Support Subsystem (OSS)

        The OSS is an integral aspect of any functional GSM network. The NSS and BSC parts are linked here. The GSM network and BSS traffic load are the primary areas of focus for this OSS. It is worth noting that some preservation responsibilities are relocated to the base station controller to lower the maintenance expense of the system when the amount of BS increases through the consumer population growth.

        The 2G GSM network architecture is predicated on a rational functioning method. This approach is remarkably straightforward compared to today's mobile network architectures, which rely on software-defined units to facilitate highly adaptable operations. However, the 2G GSM architecture will show how the necessary voice and essential operational functions are organized. 

        Specifications of a GSM Module

        The following are some of the functions provided by the GSM module.

        • Enhanced spectrum efficiency

        • Features including "international roaming," "integrated services digital network" (ISDN) compatibility, and "support for future services" are also included.

        • High-quality voice communications; encrypted phone conversations;

        • Features like a programmable alarm clock, high-quality voice communication, a fixed calling number, a real-time clock, and the ability to send and receive SMS messages are all standard on modern smartphones (SMS)

        As a result of its rigorous security measures, the GSM system is currently the safest available for use in the telecommunications industry. Call privacy and subscriber anonymity for GSM users are only protected during transmission, but this is still a massive step toward attaining end-to-end security.

        GSM Modem

        In either its mobile phone or modem form, a Global System for Mobile Communications (GSM) modem enables two computers or processors to connect across a network. A SIM card is needed to run a GSM modem, and it can only be used within the coverage area the network provider has paid for. It has serial, USB, and Bluetooth connectivity options for linking to a personal computer.

        Any regular GSM cell phone can double as a GSM modem if you have a suitable cable and driver installed on your PC. It would be best if you used a GSM modem instead of a GSM cell phone. The GSM modem is helpful in many devices, including POS terminals, inventory management systems, surveillance cameras, weather stations, and GPRS-mode remote data loggers.

        GSM Module Operation

        Below is a circuit showing how to connect a GSM modem to the MC using the level-shifting IC Max232. When a numeric command is received by short message service (SMS) from any mobile device, the SIM card-mounted GSM modem transfers that information to the MC via serial connection. The GSM modem is programmed to respond to the order "STOP" by producing an MC output, the point which is utilized to deactivate the ignition switch.

        If the input is driven low, the GSM modem will send a predetermined message (in this case, "ALERT") to the user. A 162 LCD screen displays the entirety of the procedure.

        In-depth working Explanation of raspberry pi 4

        We have utilized a GSM module and a Raspberry Pi 4 to manage the entire system and interface its many parts in this Project. You can input data of any kind, including phone numbers, text messages, and phone calls, read and respond to text messages, and more, using a 4x4 alphanumeric keypad. The SIM900A GSM module connects mobile phones to wireless networks for making and receiving calls and sending and receiving text messages. We've integrated a microphone, a loudspeaker for making and receiving voice calls, and a 16 * 2 liquid crystal displays information like menu options and alarms.

        With alphanumeric input, you can use the same keyboard to type in both numbers and letters. For the Code we used to allow alphabets in addition to numbers in this method, scroll down to the "Code in Code" section.

        It's simple to put this plan into action. The alphanumeric keypad is used for all functions. Below you'll find a link to the complete Code and a demonstration video. This section will elaborate on the four aspects of the listed projects.

        The Pi 4 Mobile Phone Four Main Attributes

        Make Call

        The Pi 4 phone we built requires us to press the letter "C" and provide the cellphone number we wish to call. We'll use an alphanumeric keyboard to enter the number. Once the correct number has been entered, we must hit "C" again. The AT command is now processed by pi 4 to connect the call to a specified number.

        ATDxxxxxxxxxx; <Enter>     where xxxxxxxxx is entered Mobile Number.

        Receive Call

        Answering a phone call is simple. When a call comes into the SIM number stored in the GSM Module of your system, the LCD will display the message "Incoming..." along with the caller's number. All that's left to do is hit the 'A' key to answer the call. Pi 4 will send the following command to the GSM Module when the "A" button is pressed:

        ATA <enter>

        Transmit SMS

        Pressing "D" on our Raspberry Pi phone allows us to send a text message. To whom (or what) should we address the SMS message that the system has just requested? Once the number has been entered, pressing "D" again will prompt the LCD to request a message. To send an SMS, enter the message using the keypad as you would with any other mobile device, and then hit the 'D' key again. Raspberry Pi can send SMS with the following command:

        AT+CMGF=1 <enter>

        AT+CMGS=”xxxxxxxxxx” <enter>     where: xxxxxxxxxx is entered mobile number

        Receive and Read SMS

        Even this component is easy to use. Here, the SIM card is used to receive SMS messages from the GSM. The Raspberry Pi also keeps a close eye on the UART SMS signal. New notes are shown by the LCD displaying the text "New message," and reading them is as simple as pressing the "B" key. This is an SMS Received signal:

        +CMTI: "SM," 6  Where 6 is the message location where it is stored in the SIM card.

        When the RPi detects the 'SMS received' signal, it will get the SMS storage location and instruct the Global system for mobile to read the message. Moreover, the LCD will flash the words "New Message" in a prominent location.

        AT+CMGR=<SMS stored location><enter>

        The GSM now delivers the saved message to the Raspberry Pi, and the Pi, having extracted the primary SMS, shows it on the LCD. When it comes to MIC and Speaker, there is no secret code.

        Detailed Circuit Layout and Explanation

        The GPIO pins of the Raspberry Pi are wired to the RS, EN, D4, D5, D6, and D7 pins of the 16 * 2 liquid crystal display. A direct connection is made between the GSM module's Rx and Tx pins and the Raspberry Pi's Tx and Rx pins. Connectors R1, R2, R3, and R4 of a 4 * 4 keypad are connected to GPIOs 12, 16, 20, and 21, whereas pins C1, C2, C3, and C4 are connected to GPIOs 26, 19, 13, and 6. If you want to boost the audio volume from the GSM Module, you can join the microphone directly to the mic+ and mic- pins and the loudspeaker to the sp+ and sp- pins. The loudspeaker can be connected directly to the GSM module without using the Audio Amplifier circuit.

        Explanation of the Code

        This Pi 4 mobile phone's programming interface may be challenging to novices—the programming language of choice for this Project is Python.

        Here, we define the keypad() function to be used with a basic numeric keypad. We've also added a def alpha keypad(): for typing alphabets so that you may use the same keypad for both purposes. To make it compatible with the Arduino keypad library, we've given this keypad a wide range of new capabilities. This keypad only takes 10 presses to enter a whole string of text or a numeric value.

        For example, if we push key 2 (abc2) once, the LCD will display the letter 'a.' If we press it again, the letter 'b' will take its place, and if we hit it three more times, the letter 'c' will appear in the same spot. After holding down a key for a short time, the LCD pointer will advance to the following available location. We can now proceed to the next character or number. Any other keys can be processed in the same way.

        def keypad():

           for j in range(4):

             gpio.setup(COL[j], gpio.OUT)

             gpio.output(COL[j], 0)

             ch=0

             for i in range(4):

               if gpio.input(ROW[i])==0:

                 ch=MATRIX[i][j]

                 return ch

                 while (gpio.input(ROW[i]) == 0):

                   pass

             gpio.output(COL[j],1)

        def alphaKeypad():

            lcdclear()

            setCursor(x,y)

            lcdcmd(0x0f)

            msg=""

            while 1:

                key=0

                count=0

                key=keypad()

                if key == '1':

                    ind=0

                    maxInd=6

                    Key='1'

                    getChar(Key, ind, maxInd)

                    .... .....

                    ..... .....

        To begin, we have declared the pins for the liquid crystal display, the keypad, and other components, as well as included the necessary libraries in this python script:

        import RPi.GPIO as gpio

        import serial

        import time


        msg=""

        alpha="1!@.,:?ABC2DEF3GHI4JKL5MNO6PQRS7TUV8WXYZ90 *#"

        x=0

        y=0


        MATRIX = [

                    ['1','2','3','A'],

                    ['4','5','6','B'],

                    ['7','8','9','C'],

                    ['*','0','#','D']

                 ]

        ROW = [21,20,16,12]

        COL = [26,19,13,6]

        ... .....

        ..... .....

        The pins need to be pointed in the proper direction.

        gpio.setwarnings(False)

        gpio.setmode(gpio.BCM)

        gpio.setup(RS, gpio.OUT)

        gpio.setup(EN, gpio.OUT)

        gpio.setup(D4, gpio.OUT)

        gpio.setup(D5, gpio.OUT)

        gpio.setup(D6, gpio.OUT)

        gpio.setup(D7, gpio.OUT)

        gpio.setup(led, gpio.OUT)

        gpio.setup(buz, gpio.OUT)

        gpio.setup(m11, gpio.OUT)

        gpio.setup(m12, gpio.OUT)

        gpio.setup(button, gpio.IN)

        gpio.output(led , 0)

        gpio.output(buz , 0)

        gpio.output(m11 , 0)

        gpio.output(m12 , 0)

        To begin Serial communication, follow the steps below.

        Serial = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=2)

        We must now create a liquid crystal display driving function. The def lcdcmd(ch): and def lcdwrite(ch): functions are used to deliver commands and data to the LCD, respectively. The liquid crystal display may also be cleared with def lcdclear(), the cursor position can be set with def setCursor(x,y), and a string can be sent to the liquid crystal display with def lcdprint(Str).

        def lcdcmd(ch): 

          gpio.output(RS, 0)

          gpio.output(D4, 0)

          gpio.output(D5, 0)

          gpio.output(D6, 0)

          gpio.output(D7, 0)

          if ch&0x10==0x10:

            gpio.output(D4, 1)

            .... .....

            ..... ....

        def lcdwrite(ch): 

          gpio.output(RS, 1)

          gpio.output(D4, 0)

          gpio.output(D5, 0)

          gpio.output(D6, 0)

          gpio.output(D7, 0)

          if ch&0x10==0x10:

            gpio.output(D4, 1)

          if ch&0x20==0x20:

            gpio.output(D5, 1)

            .... .....

            ..... ....

        def lcdclear():

          lcdcmd(0x01)

         

        def lcdprint(Str):

          l=0;

          l=len(Str)

          for i in range(l):

            lcdwrite(ord(Str[i]))

        def setCursor(x,y):

            if y == 0:

                n=128+x

            elif y == 1:

                n=192+x

            lcdcmd(n)

        Next, we'll need to code some features for interacting with text messages, phone calls, and incoming calls.

        The call is placed using the function def call():. Also, the LCD can display the receiving message and number via the function def receiveCall(data):. Finally, the call is answered with def attendCall():.

        The message is composed and sent using the alphaKeypad() method, accessed via the def sendSMS(): function. The SMS is received, and its location is retrieved using the def receive SMS(data) function. And finally, the LCD gets updated with the message thanks to def readSMS(index:).

        All of the operations mentioned above are included in the Code that follows.

        import RPi.GPIO as gpio

        import serial

        import time

        msg=""

        #     0      7   11  15  19  23  27   32  36   414244   ROLL45

        alpha="1!@.,:?ABC2DEF3GHI4JKL5MNO6PQRS7TUV8WXYZ90 *#"

        x=0

        y=0

        MATRIX = [

                    ['1','2','3','A'],

                    ['4','5','6','B'],

                    ['7','8','9','C'],

                    ['*','0','#','D']

                 ]

        ROW = [21,20,16,12]

        COL = [26,19,13,6]

        moNum=['0','0','0','0','0','0','0','0','0','0']

        m11=17

        m12=27

        led=5

        buz=26

        button=19

        RS =18

        EN =23

        D4 =24

        D5 =25

        D6 =8

        D7 =7

        HIGH=1

        LOW=0

        gpio.setwarnings(False)

        gpio.setmode(gpio.BCM)

        gpio.setup(RS, gpio.OUT)

        gpio.setup(EN, gpio.OUT)

        gpio.setup(D4, gpio.OUT)

        gpio.setup(D5, gpio.OUT)

        gpio.setup(D6, gpio.OUT)

        gpio.setup(D7, gpio.OUT)

        gpio.setup(led, gpio.OUT)

        gpio.setup(buz, gpio.OUT)

        gpio.setup(m11, gpio.OUT)

        gpio.setup(m12, gpio.OUT)

        gpio.setup(button, gpio.IN)

        gpio.output(led , 0)

        gpio.output(buz , 0)

        gpio.output(m11 , 0)

        gpio.output(m12 , 0)

        for j in range(4):

            gpio.setup(COL[j], gpio.OUT)

            gpio.setup(COL[j],1)

        for i in range (4):

            gpio.setup(ROW[i],gpio.IN,pull_up_down=gpio.PUD_UP)

        Serial = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=2)

         

        data=""

        def begin():

          lcdcmd(0x33) 

          lcdcmd(0x32) 

          lcdcmd(0x06)

          lcdcmd(0x0C) 

          lcdcmd(0x28) 

          lcdcmd(0x01) 

          time.sleep(0.0005)

        def lcdcmd(ch): 

          gpio.output(RS, 0)

          gpio.output(D4, 0)

          gpio.output(D5, 0)

          gpio.output(D6, 0)

          gpio.output(D7, 0)

          if ch&0x10==0x10:

            gpio.output(D4, 1)

          if ch&0x20==0x20:

            gpio.output(D5, 1)

          if ch&0x40==0x40:

            gpio.output(D6, 1)

          if ch&0x80==0x80:

            gpio.output(D7, 1)

          gpio.output(EN, 1)

          time.sleep(0.005)

          gpio.output(EN, 0)

          # Low bits

          gpio.output(D4, 0)

          gpio.output(D5, 0)

          gpio.output(D6, 0)

          gpio.output(D7, 0)

          if ch&0x01==0x01:

            gpio.output(D4, 1)

          if ch&0x02==0x02:

            gpio.output(D5, 1)

          if ch&0x04==0x04:

            gpio.output(D6, 1)

          if ch&0x08==0x08:

            gpio.output(D7, 1)

          gpio.output(EN, 1)

          time.sleep(0.005)

          gpio.output(EN, 0)

        def lcdwrite(ch): 

          gpio.output(RS, 1)

          gpio.output(D4, 0)

          gpio.output(D5, 0)

          gpio.output(D6, 0)

          gpio.output(D7, 0)

          if ch&0x10==0x10:

            gpio.output(D4, 1)

          if ch&0x20==0x20:

            gpio.output(D5, 1)

          if ch&0x40==0x40:

            gpio.output(D6, 1)

          if ch&0x80==0x80:

            gpio.output(D7, 1)

          gpio.output(EN, 1)

          time.sleep(0.005)

          gpio.output(EN, 0)

          # Low bits

          gpio.output(D4, 0)

          gpio.output(D5, 0)

          gpio.output(D6, 0)

          gpio.output(D7, 0)

          if ch&0x01==0x01:

            gpio.output(D4, 1)

          if ch&0x02==0x02:

            gpio.output(D5, 1)

          if ch&0x04==0x04:

            gpio.output(D6, 1)

          if ch&0x08==0x08:

            gpio.output(D7, 1)

          gpio.output(EN, 1)

          time.sleep(0.005)

          gpio.output(EN, 0)

        def lcdclear():

          lcdcmd(0x01)

        def lcdprint(Str):

          l=0;

          l=len(Str)

          for i in range(l):

            lcdwrite(ord(Str[i]))

        def setCursor(x,y):

            if y == 0:

                n=128+x

            elif y == 1:

                n=192+x

            lcdcmd(n)

        def keypad():

           for j in range(4):

             gpio.setup(COL[j], gpio.OUT)

             gpio.output(COL[j], 0)

             ch=0

             for i in range(4):

               if gpio.input(ROW[i])==0:

                 ch=MATRIX[i][j]

                 #lcdwrite(ord(ch))

                # print "Key Pressed:",ch

                # time.sleep(2)

                 return ch

                 while (gpio.input(ROW[i]) == 0):

                   pass

             gpio.output(COL[j],1)

            # callNum[n]=ch

        def serialEvent():

            data = Serial.read(20)

            #if data != '\0':

            print data

            data=""

        def gsmInit():

            lcdclear()

            lcdprint("Finding Module");

            time.sleep(1)

            while 1:

                data=""

                Serial.write("AT\r");

                data=Serial.read(10)

                print data

                r=data.find("OK")

                if r>=0:

                    break

                time.sleep(0.5)

            while 1:

                data=""

                Serial.write("AT+CLIP=1\r");

                data=Serial.read(10)

                print data

                r=data.find("OK")

                if r>=0:

                    break

                time.sleep(0.5)

            lcdclear()

            lcdprint("Finding Network")

            time.sleep(1)

            while 1:

                data=""

                Serial.flush()

                Serial.write("AT+CPIN?\r");

                data=Serial.read(30)

                print data

                r=data.find("READY")

                if r>=0:

                    break

                time.sleep(0.5)

            lcdclear()

            lcdprint("Finding Operator")

            time.sleep(1)

            while 1:

                data=""

                Serial.flush()

                Serial.read(20)

                Serial.write("AT+COPS?\r");

                data=Serial.read(40)

                #print data

                r=data.find("+COPS:")

                if r>=0:

                    l1=data.find(",\"")+2

                    l2=data.find("\"\r")

                    operator=data[l1:l2]

                    lcdclear()

                    lcdprint(operator)

                    time.sleep(3)

                    print operator

                    break;

                time.sleep(0.5)

            Serial.write("AT+CMGF=1\r");

            time.sleep(0.5)

           # Serial.write("AT+CNMI=2,2,0,0,0\r");

           # time.sleep(0.5)

            Serial.write("AT+CSMP=17,167,0,0\r");

            time.sleep(0.5)

        def receiveCall(data):

                inNumber=""

                r=data.find("+CLIP:")

                if r>0:

                    inNumber=""

                    inNumber=data[r+8:r+21]

                    lcdclear()

                    lcdprint("incoming")

                    setCursor(0,1)

                    lcdprint(inNumber)

                    time.sleep(1)

                    return 1

        def receive SMS(data):

            print data

            r=data.find("\",")

            print r

            if r>0:

                if data[r+4] == "\r":

                    smsNum=data[r+2:r+4]

                elif data[r+3] == "\r":

                    smsNum=data[r+2]

                elif data[r+5] == "\r":

                    smsNum=data[r+2:r+5]

                else:

                    print "else"

                print smsNum

                if r>0:

                    lcdclear()

                    lcdprint("SMS Received")

                    setCursor(0,1)

                    lcdprint("Press Button B")

                    print "AT+CMGR="+smsNum+"\r"

                    time.sleep(2)

                    return str(smsNum)

            else:

                return 0

        def attendCall():

            print "Attend call"

            Serial.write("ATA\r")

            data=""

            data=Serial.read(10)

            l=data.find("OK")

            if l>=0:

                lcdclear()

                lcdprint("Call attended")

                time.sleep(2)

                flag=-1;

                while flag<0:

                    data=Serial.read(12);

                    print data

                    flag=data.find("NO CARRIER")

                    #flag=data.find("BUSY")

                    print flag

                lcdclear()

                lcdprint("Call Ended")

                time.sleep(1)

                lcdclear()

        def readSMS(index):

                        print index

                        Serial.write("AT+CMGR="+index+"\r")

                        data=""

                        data=Serial.read(200)

                        print data

                        r=data.find("OK")

                        if r>=0:

                            r1=data.find("\"\r\n")

                            msg=""

                            msg=data[r1+3:r-4]

                            lcdclear()

                            lcdprint(msg)

                            print msg

                            time.sleep(5)

                            lcdclear();

                            smsFlag=0

                            print "Receive SMS"

        def getChar(Key, ind, maxInd):

                    ch=0

                    ch=ind

                    lcdcmd(0x0e)

                   Char=''

                    count=0

         

                    global msg

                    global x

                    global y

                    while count<20:

                        key=keypad()

                        print key

                        if key== Key:

                            setCursor(x,y)

                            Char=alpha[ch]

                            lcdwrite(ord(Char))

                            ch=ch+1

                            if ch>maxInd:

                                ch=ind

                            count=0

                        count=count+1

                        time.sleep(0.1)

                    msg+=Char

                    x=x+1

                    if x>15:

                        x=0

                        y=1

                    lcdcmd(0x0f)

         

        def alphaKeypad():

            lcdclear()

            setCursor(x,y)

            lcdcmd(0x0f)

            msg=""

            while 1:

                key=0

                count=0

                key=keypad()

                if key == '1':

                    ind=0

                    maxInd=6

                    Key='1'

                    getChar(Key, ind, maxInd)

                elif key == '2':

                    ind=7

                    maxInd=10

                    Key='2'

                    getChar(Key, ind, maxInd)

                elif key == '3':

                    ind=11

                    maxInd=14

                    Key='3'

                    getChar(Key, ind, maxInd)

                elif key == '4':

                    ind=15

                    maxInd=18

                    Key='4'

                    getChar(Key, ind, maxInd)

                elif key == '5':

                    ind=19

                    maxInd=22

                    Key='5'

                    getChar(Key, ind, maxInd)

                elif key == '6':

                    ind=23

                    maxInd=26

                    Key='6'

                    getChar(Key, ind, maxInd)

                elif key == '7':

                    ind=27

                    maxInd=31

                    Key='7'

                    getChar(Key, ind, maxInd)

                elif key == '8':

                    ind=32

                    maxInd=35

                    Key='8'

                    getChar(Key, ind, maxInd)

                elif key == '9':

                    ind=36

                    maxInd=40

                    Key='9'

                    getChar(Key, ind, maxInd)

                elif key == '0':

                    ind=41

                    maxInd=42

                    Key='0'

                    getChar(Key, ind, maxInd)

                elif key == '*':

                    ind=43

                    maxInd=43

                    Key='*'

                    getChar(Key, ind, maxInd)

                elif key == '#':

                    ind=44

                    maxInd=44

                    Key='#'

                    getChar(Key, ind, maxInd)

                elif key== 'D':

                    return

        def sendSMS():

            print"Sending sms"

            lcdclear()

            lcdprint("Enter Number:")

            setCursor(0,1)

            time.sleep(2)

            moNum=""

            while 1:

                key=0;

                key=keypad()

                #print key

                if key>0:

                    if key == 'A'  or key== 'B' or key== 'C':

                        print key

                        return

                    elif key == 'D':

                        print key

                        print moNum

                        Serial.write("AT+CMGF=1\r")

                        time.sleep(1)

                        Serial.write("AT+CMGS=\"+91"+moNum+"\"\r")

                        time.sleep(2)

                        data=""

                        data=Serial.read(60)

                        print data

                        alphaKeypad()

                        print msg

                        lcdclear()

                        lcdprint("Sending.....")

                        Serial.write(msg)

                        time.sleep(1)

                        Serial.write("\x1A")

                        while 1:

                            data=""

                            data=Serial.read(40)

                            print data

                            l=data.find("+CMGS:")

                           if l>=0:

                                lcdclear()

                                lcdprint("SMS Sent.")

                                time.sleep(2)

                                return;

                            l=data.find("Error")

                            if l>=0:

                                lcdclear()

                                lcdprint("Error")

                                time.sleep(1)

                                return

                    else:

                        print key

                        moNum+=key

                        lcdwrite(ord(key))

                        time.sleep(0.5)

        def call():

            print "Call"

            n=0

            moNum=""

            lcdclear()

            lcdprint("Enter Number:")

            setCursor(0,1)

            time.sleep(2)

            while 1:

                key=0;

                key=keypad()

                #print key

                if key>0:

                    if key == 'A'  or key== 'B' or key== 'D':

                        print key

                        return

                    elif key == 'C':

                        print key

                        print moNum

                        Serial.write("ATD+91"+moNum+";\r")

                        data=""

                        time.sleep(2)

                        data=Serial.read(30)

                        l=data.find("OK")

                        if l>=0:

                            lcdclear()

                            lcdprint("Calling.....")

                           setCursor(0,1)

                            lcdprint("+91"+moNum)

                            time.sleep(30)

                            lcdclear()

                            return

                        #l=data.find("Error")

                        #if l>=0:

                        else:

                            lcdclear()

                            lcdprint("Error")

                            time.sleep(1)

                            return

                    else:

                        print key

                        moNum+=key

                        lcdwrite(ord(key))

                        n=n+1

                        time.sleep(0.5)

        begin()

        lcdcmd(0x01)

        lcdprint("  Mobile Phone  ")

        lcdcmd(0xc0)

        lcdprint("    Using RPI     ")

        time.sleep(3)

        lcdcmd(0x01)

        lcdprint("Circuit Digest")

        lcdcmd(0xc0)

        lcdprint("Welcomes you")

        time.sleep(3)

        gsmInit()

        smsFlag=0

        index=""

        while 1:

            key=0

            key=keypad()

            print key

            if key == 'A':

              attendCall()

            elif key == 'B':

              readSMS(index)

              smsFlag=0

            elif key == 'C':

              call()

            elif key == 'D':

              sendSMS()

            data=""

            Serial.flush()

            data=Serial.read(150)

            print data

            l=data.find("RING")

            if l>=0:

              callstr=data

              receiveCall(data)

            l=data.find("\"SM\"")

            if l>=0:

              smsstr=data

              smsIndex=""

              (smsIndex)=receiveSMS(smsstr)

              print smsIndex

              if smsIndex>0:

                  smsFlag=1

                  index=smsIndex

            if smsFlag == 1:

                lcdclear()

                lcdprint("New Message")

                time.sleep(1)

            setCursor(0,0)

            lcdprint("C--> Call <--A");

            setCursor(0,1);

            lcdprint("D--> SMS  <--B")

        GSM Technology Applications

        Here are some examples of how GSM technology can be put to use.

        1. Automation and Safety via Smart GSM Technology

        Nowadays, we can't live without our GSM mobile terminal. The Mobile phone terminal is essentially an extension of ourselves, allowing us to connect with the world in the same way our wallet/purse, keys, or watch does. Many people like not having to worry about being unavailable or who they can call at any given moment.

        It's clear from the name that this Project relies on the SMS transmission capabilities of GSM networks. The ability to send and receive text messages is widely utilized to provide access to equipment and facilitate home security breach management. There are two proposed subsystems in the system. Controlling appliances in one's house from afar is made possible by the appliance control subsystem, while the security alert subsystem provides automatic security monitoring.

        The system can send consumers instructions via SMS from a designated phone number to adjust the home appliance's state as needed. An automatic SMS can be generated by the system upon detection of an intrusion, warning the user of a potential threat to their data.

        The advent of GSM technology will make global, instantaneous, and universal communication possible. GSM's functional architecture employs intelligent networking principles as the first step toward a genuinely personal communication system with sufficient standards to ensure interoperability.

        1. Medical Uses for GSM-Based Systems

        Here are two examples of similar situations to think about.

        • The patient has sustained a life-threatening injury or illness and requires emergency medical attention. A mobile phone is the only thing he (or his companion) has.

        • After being released from the hospital, the patient plans to rest at home but is reminded that he must return for routine exams. A mobile phone and perhaps some health monitoring or other medical sensor gadgets may be in his possession.

        The only way to solve either problem is via a mobile communication system. In other words, the above scenarios are easily manageable with today's communication technology because all that needs to be done is send the patient's information across a network and have it processed at the receiving end, which may be a hospital or the doctor's office.

        In the first scenario, the doctor keeps tabs on the patient's information and returns the instructions to him so he can take whatever precautions before getting to the hospital. In the second scenario, the doctor keeps tabs on the patient's test results and, if necessary, proceeds with treatment.

        Telemedicine services are the driving force behind this entire operation. The telemedicine system has three different applications.

        • Video conferencing lets patients in one location have face-to-face contact with their doctors and nurses, speeding up the healing process.

        • With the help of sensors that constantly report on a patient's condition and direct medical staff on how to proceed with treatment.

        • By sending the gathered health information for further review and analysis.

        A wireless method of communication is used for the three options mentioned above. When providing healthcare, it is necessary to have many data retrieval mechanisms in place. These can be online medical databases or hosts with equipment that aid recovery and health monitoring. Broadband networks, medium-throughput media, and narrowband GSM access are all viable possibilities.

        There are several benefits to using GSM technology in a telemedicine setup.

        • Cost savings and widespread availability of GSM receivers (including cell phones and modems)

        • It can transfer data quickly.

        1. Typical Telemedical Infrastructure

        The four components that make up a standard telemedicine system are as follows:

        1. The Patient Unit: It takes data from the patient, either in its original analog form or after being converted to digital format, and then manages the data stream before sending it. It is made up of several different types of medical sensors, such as those used to track heart rate, blood pressure, body temperature, spirometry, etc., each of which generates an electrical signal that is sent to a processor or controller for analysis before being transmitted over a wireless network.

        2. Communication Network: As such, it is employed for both data transmission and security. Networks, mobile stations, and base stations are all components of the Global System for Mobile Communication (GSM) system. The mobile station, also known as the mobile phone or primary mobile access point, is the device responsible for connecting mobile devices to the global system for mobile communications (GSM) network.

        3. Receiving/Server Side: This is a healthcare system with a GSM modem installed to receive, decode, and forward signals to the presenting device.

        4. Presentation Unit: This is the brains of the operation. This processor saves the data in a standard format for later retrieval and analysis by doctors and from which they can send text messages to the client side if necessary.

        To demonstrate the fundamentals of telemedicine, a rudimentary model will suffice. It has a sender and a receiver, both of which are separate components. The sensor input is transmitted by the transmitter and received by the receiver unit for processing.

        See below for a simplified telemedicine system to track a patient's heart rate and apply the results as needed.

        The data collected by the heartbeat detector (a light-emitting device whose light is modified as it flows through human blood) is transformed into electrical pulses at the transmitter unit. When the Microcontroller picks up on these pulses, it calculates the heart rate and communicates that information and other data collected to the medical team via a Gsm network. An IC called a Max 232 connects the Microcontroller to the GSM modem.

        The GSM modem at the receiving end grabs the information and passes it to the Microcontroller. The Microcontroller then performs an analysis using the input from the Personal computer and displays the outcome on the LCD. Medical professionals can keep tabs on the patient and begin the necessary treatment after reviewing the results on the screen.

        Medical Applications of Global Systems for Mobile Communication

        The following are some real-world applications for GSM technology.

        1. AT&T Health GlowCaps

        These plain pill bottles serve as a gentle prompt to the patient to take their prescribed medications. It uses GSM technology to contact the patient on their mobile phone at the specified pill-taking time, at which point the cap will light up, the buzzer will sound, and the patient will be reminded to take their medication. Each time a bottle is uncorked, it is documented.

        1. Ultrasound technology

        With the help of a portable ultrasound transducer that connects to a smartphone, it is possible to send ultrasound images captured with a handheld device to a distant location using a global system for mobile communications (GSM).

        1. A Continuous Glucose Monitor (CGM)

        The patient's blood sugar levels can be tracked and reported to the doctor. A sensor is implanted under the skin and monitors blood glucose levels, sending the data to a receiver (a mobile phone) at regular intervals.

        Conclusion

        As part of this guide, we analyzed GSM's architecture and learned how it operates in practice. We wrote a Python program to turn our Raspberry Pi 4 into a fully functional mobile phone. No technical difficulties were encountered as we watched text and phone calls travel between the raspberry pi and our mobile phone. You should feel confident in your ability to apply the ideas and understand the circuits of GSM now. One way to up the difficulty level of this Project is to try to make a live video call using the raspberry pi 4 mobile. Next, we'll look at connecting the pcf8591 ADC/DAC analog-digital converter module to a Raspberry Pi.

        How to Connect parents and teachers?

        A teacher is the one who helps children to develop skills to learn and exploring the world. If we want our children to be skilled person, we need to take care of their education. Schools are not enough for them, homeschooling is a great idea where parents can teach their child with better attention. Parents must collaborate with teacher for better result. A teacher is the one who helps children to develop skills to learn and exploring the world. If we want our children to be skilled person, we need to take care of their education. Schools are not enough for them, homeschooling is a great idea where parents can teach their child with better attention. Parents must collaborate with teacher for better result.

        eLearning News for Pasco Parents

        eLearning News for Pasco Parents is a blog that provides information on educational topics and trends. If you are a parent in Pasco County, Florida, this blog is the perfect place to find out more about the latest developments in the world of education. . How to Get your Child on the School BusPasco County Public Schools has created a video which provides information on how to get your child on the school bus. If you find yourself stuck at home with a sick child, please watch this video to learn the best way for you to get him or her to school.

        Learning Continuity Planning

        Learning Continuity Planning is a process that is used to assess the needs of the organization and plan for future learning. This process can be used to identify gaps in knowledge, skills and abilities of employees, which can later be addressed through training or other means.

        This process can also help organizations to stay competitive by providing continuous learning opportunities for their employees.

        What is a Learning Continuity Plan?

        A Learning Continuity Plan is a workbook that you can use to map out your training. It includes all the learning materials, tools and assessments, so that you know what learners will need for which courses and what they have already completed.

        Continuing Education OutcomesAn outcome is a measurable, quantifiable result that a learner achieves which helps them progress towards achieving their goal.

        Pasco's Plan:

        Pasco's Plan is a revitalization strategy for the Pasco Region, a region that has been plagued by economic uncertainty and unemployment. The planning document is a blueprint for the future of Pasco, defining workforce development, transportation and housing as key areas.The Planning Brochure was approved by the City Council on December 4th, 2017. The plan seeks to address the need for economic stability in Pasco through diversification and improvement of its industrial sector and supporting industries, support for entrepreneurship and small business growth, increased engagement with local governments to develop a regional sustainability strategy that supports agriculture, natural resources management and tourism industries Powered by a regional push towards urban sustainability, the report identifies three key actions to further the region’s sustainability:Establish a regional coalition focused on urban sustainabilityIncrease public awareness of local issues and mobilize support for sustainable policies in each metro areaDevelop educational tools for increasing awareness and action around local sustainability issues in each metro areaThis project is a collaboration among the Metropolitan Planning Organizations of Louisville, Ky.; Phoenix, Ariz.; and Portland, Ore. These cities are selected as they represent a cross-section of metropolitan areas in the United States with diverse livability characteristics.

        MyPascoConnect

        Pasco County, Florida is a county located in the U.S. state of Florida, and it has a population of about 710,000 people. Pasco County is home to some of the most popular tourist attractions in the country such as Busch Gardens Tampa Bay and Adventure Island. It also has some of the best schools in the state with many colleges and universities such as Pasco-Hernando State College, University of South Florida Polytechnic, Hernando State College, and Hillsborough Community College.

        Pasco County offers many different services for its citizens including education services, public safety services such as firefighting and police protection, public works services that provide water treatment and wastewater management systems to protect our environment.

        The Pasco County government provides access to a range of information through their website myPascoConnect which includes information on how to register your dog or cat for rabies shots or where you can find recycling centers near you. The Hillsborough County government provides access to a range of information through their website myHillsborough. This includes information on how to register your pet for a rabies shot or where you can find recycling centers near you.

        Learning Tools & Suggested Routines for Students

        Students are often faced with the difficult task of balancing their education and their personal lives, which can lead to a lack of motivation, stress, and anxiety.

        There are many different ways to learn new skills and improve existing ones. The key is finding what works best for you. There is no one-size-fits-all solution when it comes to learning tools or routines. As such, students should experiment with different tools and routines until they find the right fit for them.

        Learning Tools: 

        There are many different online tools that can help students learn new skills or improve existing ones. For example, Khan Academy provides free videos on a variety of subjects that students can watch at their own pace in order to improve their skills in subjects like math, science, economics and more. Coursera also offers courses on various topics that range from programming languages like Python or JavaScript to psychology to history. 

        Suggested Routines: 

        Students should try out various learning routines until they find one that feels good. Study Skills: Students should learn to set aside time for studying and to study regularly.

        RF Communication with nRF24L01 and Raspberry Pi 4

        Where To Buy?
        No.ComponentsDistributorLink To Buy
        1BreadboardAmazonBuy Now
        2Jumper WiresAmazonBuy Now
        3LCD 16x2AmazonBuy Now
        4nRF24L01AmazonBuy Now
        5Arduino UnoAmazonBuy Now
        6Raspberry Pi 4AmazonBuy Now

        Introduction

        We're glad you could join us for another lesson in our series on programming for the Raspberry Pi 4. The previous chapter covered how to interface the USB barcode scanner with raspberry pi 4. We looked at different types of barcodes and what each stripe represents as well as the different types of barcode scanners available today. We also built a python program for the intelligent shopping cart and now our familiarity with barcodes and scanners and how they function has significantly increased. The benefits and drawbacks of its use were also discussed, but what we're interested in for this article is the transmission of radio frequency signals using the nrf24l01 Module in a raspberry pi 4.

        Components

        • nRF24L01 RF module

        • Raspberry pi 4

        • Arduino Uno

        • Jumper wires

        • Power supply

        • 16x2 liquid crystal display

        Wireless communication systems, such as ESPS266 WiFi modules, are widely used in the design process. Further, the media chosen is determined by the function it will serve. It's no secret that the nRF24L01 is a widely used wireless channel for local area network communication. These modules have a band rate of 250Kbps to 2Mbps and transmit on the 2.4GHz (ISM band), which is permitted in many states and suitable for usage in industrial and healthcare settings. There is also the claim that these modules can communicate at a distance of up to 100 meters with the correct antennae.

        This tutorial demonstrates how to set up wireless communication between an Arduino UNO and a Raspberry Pi by utilizing the nRF24L01 - 2.4GHz RF Transceiver module. Raspberry Pi will broadcast data via nRF24L01, and Arduino Board will receive the data and display it on a 16x2 LCD. In addition to its built-in WiFi and Bluetooth Low Energy (BLE) capabilities, the nRF24L01 is also capable of wireless communication via BLE.

        Both parts of the tutorial are equally important. In the first, we'll see how to connect the nRF24L01 to an Arduino so that it can function as a receiver, and in the second, we'll do the same thing with a Raspberry Pi can send out signals.

        The meaning of "wireless radio frequency."

        There are many different types of electromagnetic waves. Still, the ones utilized for radar signals and communications fall into roughly 3 kHz to 300 GHz range, known as "radio frequencies."

        The term "radio frequency" is more commonly used to refer to electrical than mechanical oscillations. There are, however, examples of mechanical RF systems. Although radio frequency (RF) refers to an oscillation rate, the term "radio frequency" (RF) is sometimes used interchangeably with "radio" to describe the practice of communicating without the need for wires.

        Numerous wireless technologies rely on RF fields, including cordless and cell phones, radio and television broadcasting stations, satellite telecommunication networks, Bluetooth communication modules and WiFi, and two-way radios.

        External communications include various products like garage doors and microwave ovens, which use radio frequencies. The infrared frequencies of various wireless devices, like TV remote controllers, computer mice, and some wireless computer keyboards, have shorter electromagnetic wavelengths.

        So, How Exactly Does Radio Frequency Operate?

        The frequency of radio transmission is expressed in hertz (Hz) units, which stand for the count of cycles per second. Radio waves can travel from one thousand hertz (kHz) to several gigahertz (GHz). Microwaves, a form of radio wave, operate at much higher frequencies. Because of this, we can't see radio frequencies (RFs).

        The wavelength' of a radio wave is proportional to the square root of the frequency 'f.' The relationship between frequency and wavelength can be expressed in megahertz and meters, respectively.

        s = 300/f

        At higher frequencies, electromagnetic radiation is manifested as infrared (IR), ultraviolet (UV), visible (Visible), X-ray (XR), and gamma-ray (GJ).

        Traits of Radio Frequency

        The following are some of the defining features of RF:

        • Low energy consumption

        • It has an excellent operational range (three to thirty meters), a data rate of up to two megabits per second, the ability to pass through walls, and can transmit in any direction.

        The nRF24L01 Radio Frequency (RF) Module

        Due to their half-duplex design, the nRF24L01 modules can only send or receive data but not do both. The Module's data transmission and reception are handled by the generic Nordic semi-conductor nRF24L01 IC. The IC uses the simple serial peripheral interface (SPI) protocol for communication, making it compatible with virtually all microcontrollers. Arduino makes things much simpler because there are numerous library resources available. The following table depicts the pin configurations of a typical nRF24L01 module.

        The Module is battery efficient, as its operating voltage ranges from 1.9V to 3.6V, and it draws minimal current (only 12mA) during regular operation. Most pins can be connected directly with 5V chipsets like Arduino, even though the voltage rating is 3.3V. Each Module also includes 6 Pipelines, which is a huge time saver. Simply put, each Module can exchange information with up to six others. Therefore, the Module can be used for IoT applications requiring the creation of star or mesh networks. With an extensive network address of 125 unique IDs, we may use 125 such components in a contained space without worrying about them interfering with one another.

        Mechanics of Operation

        Given that the Module supports 125 separate channels, creating a network containing 125 fully available modems at a single location is theoretically possible. Each device can simultaneously interface with up to six others on the same channel.

        Transmission with this Module only uses about 12mA of power, less than a single display LED screen. The Module requires a voltage of 1.9V to 3.6V to function. Still, the other pins are 5V logic compatible, allowing us to connect it directly to an Arduino without needing logic-level converters.

        Three of these terminals are used for SPI communication and must be hooked up to the SPI pins on the Arduino; however, the SPI pins on different Arduino boards are labelled differently. Connecting the CSN and CE pins to any input pin on the Arduino board toggles between standby and active modes and transmit and command modes for the Module. The last connector is an interrupt pin, which is optional.

        Variations in Modules

        The NRF24L01 modules can be found in a wide range of versions. The model with a built-in antenna is the clear frontrunner. This reduces the transmission range of the Module to around 100 meters but allows for a smaller module size.

        In the second variant, an SMA connector replaces the onboard antenna, allowing us to use a duck transmitter for enhanced signal strength.

        The third variant displayed here also features the duck antenna with an RFX2401C microprocessor with an integrated Power Amplifier and Low-Noise Amplifier). This can increase the NRF24L01's transmission range in open areas by 1000.

        Circuit Schematic

        Integrating nRF24L01 with Arduino

        The components in the circuit design for linking nRF24L01 to Arduino are few, and the process is straightforward. SPI will be used to link the nRF24l01, and I2C will connect the 16x2 LCD.

        Integrating nRF24L01 on a Raspberry Pi

        Because only the SPI adapter is required to link the Raspberry Pi and the nRF24L01, the corresponding circuit schematic is pretty straightforward.

        How to Use nRF24l01 with Raspberry Pi to Communicate

        Python3 will be used for Raspberry Pi's programming. The Arduino platform is not the only one that can use C/C++. However, if you're programming in Python, you can get a library for nRF24l01 that's already been made. Keep in mind that the library and the python program must be in the same folder for the python program to use it. Create a folder to house your applications and library files after you have downloaded and extracted the library. After the necessary libraries have been installed, you can begin coding immediately. Importing libraries like the GPIO library for communicating with the Raspberry Pi's GPIO pins and the time library for using the Pi's clock and date functions are the first steps in writing any program.

        import RPi.GPIO as GPIO 

        import time     

        import spidev

        from lib_nrf24 import NRF24

        It would be best if you switched to the "Broadcom SOC channel" for the GPIO setting. Pins are referred to by their "Broadcom SOC channel" numbers, which follow the letters "GPIO" (GPIO01, GPIO02, etc.). The Board Numbers are not these.

        GPIO.setmode(GPIO.BCM)

        After that, we'll assign a permanent address for the pipe. To send data to Arduino, you'll need to use this address. There will be a hexadecimal representation of the address.

        pipes = [[0xE0, 0xE0, 0xF1, 0xF1, 0xE0], [0xF1, 0xF1, 0xF0, 0xF0, 0xE0]]

        Start the radio with the CE pin (GPIO08) and the CSN pin (GPIO25).

        radio.begin(0, 25)

        Change the power levels to minimal, the channel address to 76, the data rate to 1 Mbps, and the payload size to 32 bits.

        radio.setPayloadSize(32)  

        radio.setChannel(0x76) 

        radio.setDataRate(NRF24.BR_1MBPS)    

        radio.setPALevel(NRF24.PA_MIN)

        Start the data writing process by opening the pipes and displaying some nRF24l01 basics.

        radio.openWritingPipe(pipes[0])     

        radio.printDetails()

        Get your message ready to send as a string. Arduino UNO will receive this message.

        sendMessage = list("Hi..Arduino UNO")  

        while len(sendMessage) < 32:    

            sendMessage.append(0)

        Send the string's first character to the stereo and continue doing so until the radio is ready to receive it. In addition, a debug statement detailing the time and date the message was delivered should be printed.

        While True:

            start = time.time()      

            radio.write(sendMessage)   

            print("Sent the message: {}".format(sendMessage))  

        send

            radio.start listening()


        A timed-out error message should be printed if the thread is finished and the conduit is closed.

        while not radio.available(0):

                time.sleep(1/100)

                If time.time() - start > 2:

                    print("Timed out.")  # print error message if radio disconnected or not functioning anymore

                    break

        If you want to send another message, turn off the radio and disconnect from the connection for three seconds.

        radio.stopListening()     # close radio

            time.sleep(3)  # give a delay of 3 seconds

        If you know the fundamentals of Python, you can easily comprehend the Raspberry program. You will find a fully functional Python program at the end of this tutorial.

        Putting the Python Code for the Raspberry Pi to Work

        If you follow the steps below, running the software will be a breeze.

        • You should keep the Python source code and library files together.

          • My Sender program file is nrfsend.py, and all the related files are in the same directory.

            • Access Raspberry Pi's command prompt. Use the cd command to get to the directory containing the python script.

              • Navigate to the directory, type "sudo python3 your program.py," and hit enter to run the program. In less than a minute, you'll likely see nRf24's essentials laid out, and the broadcaster will begin broadcasting its bulletins at three-second intervals. Once the send is complete, the debug message will appear.

              The Arduino UNO will now display the same code as the receiver.

              The nRF24l01 and Arduino UNO: Message Reception Programming

              The Arduino UNO can be programmed in a manner not dissimilar to that of the Raspberry Pi. Our procedures will be very similar; however, we'll use a different language for programming and other processes. The procedure will incorporate the nRF24l01 readout. Download the nRF24l01 Arduino library from GitHub. To get started, make sure all required libraries are installed. We're using a 16x2 I2C LCD, so we need to include the Wire.h library; the nRF24l01 communicates via SPI, so we also need the SPI library.

              #include<SPI.h>                   

              #include <Wire.h>

              Don't forget to add the RF24 and LCD libraries so you may use them.

              #include<RF24.h>                  

              #include <LiquidCrystal_I2C.h>

              Put the LCD's I2C address—27 in this case, as it's a 16x2 display—into the appropriate function.

              LiquidCrystal_I2C lcd(0x27, 16, 2);

              Pin 9 serves as the RF24's Common Emitter, and pin 10 serves as its Common Source Negative.

              RF24 radio(9, 10) ;  

              Turn the radio on and tune in to channel 76. In addition, open the pipe for reading by setting the address to that of the Raspberry Pi.

              radio.begin();        

                radio.setPALevel(RF24_PA_MAX) ;   

                radio.setChannel(0x76) ;            

                const uint64_t pipe = 0xE0E0F1F1E0LL ;    

                radio.openReadingPipe(1, pipe) ;

              Start the I2C data transfer and initialize the LCD screen.

              Wire.begin();                 

                lcd.begin();                    

                lcd.home();                       

                lcd.print("Ready to Receive");

              Turn on the radio's receiver and enter a message length of 32.

              radio.startListening() ;        

                char receivedMessage[32] = {0}

              The message will be read and saved immediately if a radio is connected. Display the message on the screen and send it to the serial monitor till the following message is received. Put the radio on hold while you tune in, then try again later. Right this way, in ten microseconds.

              if (radio.available()) {       

                  radio.read(receivedMessage, sizeof(receivedMessage));        

                  Serial.println(receivedMessage) ;    

                  Serial.println("Turning off the radio.") ;   

                  radio.stopListening() ;   

                  String stringMessage(receivedMessage) ;     

                  lcd.clear();    

                  delay(1000);    

                  lcd.print(stringMessage);   

                }

              Copy and paste the code below into your server and allow time for the response to arrive.

              NRF Transmitter Side Code (Raspberry Pi)

              import RPi.GPIO as GPIO  # import gpio

              import time      #import time library

              import spidev

              from lib_nrf24 import NRF24   #import NRF24 library

              GPIO.setmode(GPIO.BCM)       # set the gpio mode

                # set the pipe address. This address should be entered on the receiver to

              pipes = [[0xE0, 0xE0, 0xF1, 0xF1, 0xE0], [0xF1, 0xF1, 0xF0, 0xF0, 0xE0]]

              radio = NRF24(GPIO, spidev.SpiDev())   # use the gpio pins

              radio.begin(0, 25)   # start the radio and set the ce,csn pin ce= GPIO08, csn= GPIO25

              radio.setPayloadSize(32)  #set the payload size as 32 bytes

              radio.setChannel(0x76) # set the channel as 76 hex

              radio.setDataRate(NRF24.BR_1MBPS)    # set radio data rate

              radio.setPALevel(NRF24.PA_MIN)  # set PA level

              radio.setAutoAck(True)       # set acknowledgement as true 

              radio.enableDynamicPayloads()

              radio.enableAckPayload()

              radio.openWritingPipe(pipes[0])     # open the defined pipe for writing

              radio.printDetails()      # print basic detals of radio

              sendMessage = list("Hi..Arduino UNO")  #the message to be sent

              while len(sendMessage) < 32:    

                  sendMessage.append(0)

              While True:

                  start = time.time()      #start the time for checking delivery time

                  radio.write(sendMessage)   # just write the message to radio

                  print("Sent the message: {}".format(sendMessage))  # print a message after succesfull send

                  radio.startListening()        # Start listening the radio

                  while not radio.available(0):

                      time.sleep(1/100)

                      if time.time() - start > 2:

                          print("Timed out.")  # print error message if the radio disconnected or not functioning anymore

                          break

                  radio.stopListening()     # close radio

                  time.sleep(3)  # give delay of 3 seconds

              NRF Receiver Side Code (Arduino):

              #include<SPI.h>                   // spi library for connecting nrf

              #include <Wire.h>                             // i2c libary fro 16x2 lcd display

              #include<RF24.h>                  // nrf library

              #include <LiquidCrystal_I2C.h>     // 16x2 lcd display library

              LiquidCrystal_I2C lcd(0x27, 16, 2);         // i2c address is 0x27

              RF24 radio(9, 10) ;  // ce, csn pins    

              void setup(void) {

                while (!Serial) ;

                Serial.begin(9600) ;     // start serial monitor baud rate

                Serial.println("Starting.. Setting Up.. Radio on..") ; // debug message

                radio.begin();        // start radio at ce csn pin 9 and 10

                radio.setPALevel(RF24_PA_MAX) ;   // set power level

                radio.setChannel(0x76) ;            // set chanel at 76

                const uint64_t pipe = 0xE0E0F1F1E0LL ;    // pipe address same as sender i.e. raspberry pi

                radio.openReadingPipe(1, pipe) ;        // start reading pipe 

                radio.enableDynamicPayloads() ;

                radio.powerUp() ;          

                Wire.begin();                 //start i2c address

                lcd.begin();                    // start lcd 

                lcd.home();                       

                lcd.print("Ready to Receive");  // print starting message on lcd 

                delay(2000);

                lcd.clear();

              }

              void loop(void) {

                radio.startListening() ;        // start listening forever

                char receivedMessage[32] = {0} ;   // set incmng message for 32 bytes

                if (radio.available()) {       // check if message is coming

                  radio.read(receivedMessage, sizeof(receivedMessage));    // read the message and save

                  Serial.println(receivedMessage) ;    // print message on serial monitor 

                  Serial.println("Turning off the radio.") ;   // print message on serial monitor

                  radio.stopListening() ;   // stop listening radio

                  String stringMessage(receivedMessage) ;     // change char to string

                  lcd.clear();    // clear screen for new message

                  delay(1000);    // delay of 1 second 

                  lcd.print(stringMessage);   // print received mesage

                }

                delay(10);

              }

              Features That Have the Most Impact on RF Module Efficiency

              The RF module's performance will be affected by the same factors as any other RF component. For instance, a transmitter's output power can be increased to extend the range of a transmission. However, this will cause a greater consumption of electricity by the transmitters (TX) device, reducing the useful life of battery-operated gadgets. Increasing the system's transmit power also makes it more vulnerable to interference from a second RF source.

              Similarly, boosting the receiver's sensitivity increases the usable communication range but increases the risk of an error brought on by interference from other RF equipment. Matching antennas on both ends of a communication link can potentially boost the overall system's performance.

              Finally, the regarded remote distance of any given system is typically measured in an open-air line-of-sight outline without any interference; nevertheless, problems such as floors, walls, and dense structures will frequently grasp the radio wave signals; thus, the actual operational distance will typically be less than specified.

              Uses for Radio Frequency Communication

              The most common uses of radio frequency communication are in the areas of wireless data and voice transfer, home automation, and remote control, as well as in the industrial and commercial sectors.

              RF-controlled switches can be used in home automation applications as an alternative to traditional switches. An RF remote allows one to operate lights and other electronics without leaving their current location. Those with mobility issues will benefit the most from this app. RF communication is helpful in industrial settings for directing autonomous robots and motorized vehicles. These robot vehicles are often employed in hazardous tasks humans cannot undertake. A data transmission unit is required to direct the motion of the robotic vehicles.

              Multiple factors make radio frequency (RF) transmission preferable to infrared (IR) (infrared). The more extended range of RF signals makes them ideal for long-distance communications. Unlike radio frequency (RF), which can go across obstacles, infrared (IR) generally requires a clear path from transmitter to receiver. The reliability of RF transmission is far greater than that of infrared remote communications. While radio frequency (RF) communications require other IR-emitting devices that can disrupt a precise frequency range, infrared (IR) communications.

              Problems with Radio Frequency

              These are some of RF's drawbacks.

              • Preschoolers, expectant mothers, the elderly, those with pacemakers, little birds, flora, wildlife, insects, etc., are all negatively impacted by unregulated RF radiation.

              • More lightning has been seen in nearby cellular towers that use radio frequency than in other areas.

              • Some fruit crops in the vicinity of RF towers are also negatively impacted.

              • Because RF waves are accessible in both line-of-sight (LOS) and non-LOS zones of the transmitter, hackers can easily break into the system and decode sensitive personal or government data.

              • This problem can be avoided by employing highly protected methods like AES, WEP, WPA, etc., while transmitting data over radio frequency waves. Spread spectrum and frequency hopping modulation methods can also be applied to RF signals to prevent such eavesdropping.


              Conclusion

              This concludes the comprehensive instruction on wireless communication between a Raspberry Pi and an Arduino UNO via nRf24l01 modules. The 16 * 2 liquid crystal display will show the message. Pipe addresses are crucial on the Arduino UNO and the Raspberry Pi 4. In the following tutorial, we will learn how to Call and Text using Raspberry Pi and GSM Module in pi 4.

              Interface USB Barcode Scanner with Raspberry Pi 4

              Hello friends, I hope you all are doing great. Today, we are going to start a new section in our Raspberry Pi Programming Course. In this section-VIII, we will implement advance protocols in the RPi4 board. Today's our first lecture in this section and we are going to interface a USB Bar Code Scanner with Raspberry Pi 4.

              If you have visited any big grocery store, you must have seen, it's quite important as well as difficult to maintain the products in stock at all times. To ease the job, barcode technology is used because it can easily maintain an organized database of your items, costs, and inventory levels in one convenient location. Price changes can be implemented whenever you desire without requiring new labels for previously packaged goods. You can tell exactly when your supply of a particular item is getting low, so you may place a new purchase before you run out. Since the barcode system is so precise, you may assume that any missing (and seemingly unsold) items have been stolen.

              Here's the video demonstration of this barcode tutorial:


              So, let's get started with the implementation of a barcode scanner with Raspberry Pi 4:

              Project Description

              In this post, you'll learn how to read the Barcode scanner's output in the Serial interface of Raspberry Pi 4 and display the scanned code on the 16x2 LCD. When a User reviews an item's code, the LCD will update to reflect the new total number of items in the shopping basket. This configuration allows us to create an intelligent cart with an integrated billing system.

              Components Required

              Here's the list of components, used in designing today's project:

              • Raspberry Pi 4
              • USB Handheld Barcode Scanner
              • 16x2 alphanumeric LCD
              • I2C Module for LCD
              • Jumper Wires
              • Sample Barcoded Items

              Simple Bar Code Scanner: The Fundamentals

              • A barcode is an electronic module used to read a graphical code represented by a series of black-and-white parallel bars.
              • These black and white bars are actually representing a numeric digit, which is extracted by the barcode scanner.
              • Barcode Scanner sends its data to the microcontroller via USB/UART.
              • We are going to use the below barcode scanner:

              Barcode Scanner can read a wide range of linear barcodes. Barcode scanners are commonly utilized in retail settings like supermarkets, grocery stores, restaurants, boutiques, warehouse inventory,  invoices for bookkeeping and other retail establishments. Intelligent shopping carts now use barcode scanners to quickly and accurately identify products.

              Connecting your handheld barcode scanner to a computer is as simple as plugging it into a USB port. Barcode scanners can typically decode at speeds of up to 300 scans/second. Additionally, they can easily read a wide range of scratchy, blurry barcodes.

              Serial output through USB is provided in either H.I.D. mode or RS232 mode, depending on the device's configuration. Users can change the Baud rate from 9600 to 115200 and modify the Suffix by adding a C.R., L.F., CR+LF, or no ending characters. And you may set it to read in either Trigger Mode or Continuous Mode. Scanning the included settings sheet's Barcode will also restore the machine to its factory defaults.

              Barcode Working Principle

              As we discussed above, the black & white bars are actually representing a numeric digit. We are hiding the numeric digit in black & white bars because it's difficult for computers to recognize decimal numbers but reading a simple bar is quite easy. The below figure shows the respective bars for numeric digits 0-9:

              Looking at a barcode, it might be difficult to determine, where one set of numbers stops and another starts. But in reality, it's pretty easy. There are precisely seven units of horizontal space in each letter. So, in order to get the numeric digit "1", the bar code(starting from left) has two white lines, two black lines, two white lines, and finally one black line, as shown in the above figure.

              The barcode printing on the consumer goods has a universal representation i.e. a series of vertical stripes and the numeric code imprinted below, so that,  the Barcode can be manually keyed in, if it is incorrectly printed or scratched in the store. Two-dimensional barcodes are also used on some items i.e. postal stamps, as shown in the below figure:

              Let's pretend that barcodes are specific on-off binary sequences, with every black stripe representing a one and every white stripe representing a zero. (We've seen that actual barcodes are more complex than this, but for now, simplicity is in order.)

              1. The Barcode is illuminated by the scanning head's L.E.D. or laser.
              2. Second, a photoelectric cell, an electronic component that detects light, receives the light reflected from the Barcode. The Barcode's white spaces are the most reflective, while the black ones are the least.
              3. Third, the cell produces an on/off pulse sequence corresponding to black and white lines when the scanner goes through the Barcode. The cell would read "off off off off off off" if the shown Code were to be entered.
              4. These on/off pulses are then translated into numeric values via an electronic circuit connected to the scanner.
              5. A computer program generates the final Barcode using the digital data sent from the scanner.

              Some scanners use a single photosensitive cell that reads the barcode pixel by pixel as you slide the sensor head over the item (or the product across the reader). The complete Code is detected in a single pass, thanks to a row of photoelectric cells in more complex scanners.

              Types of Barcodes

              The following are examples of well-known barcode types:

              • The European Item Numbering Scheme (EAN) is a specialized version of the Uniform Product Code (U.P.C.) for items with a thirteen-digit identifier. There are 13 digits in an EAN13 barcode.

                • The retail sector heavily uses UPC-A barcodes based on the U.P.C. The Universal Product Code, Extended (UPC-A), comprises 12 digits.

                  • (EAN -8) uses a set of numbers superseding the U.P.C. EAN-8 for compact shipments; these numbers include eight digits.

                    • Like code 128's character set C, Intermingled 2 of 5 (I.T.F.) is an arithmetic barcode used to encode pairs of integers in a space-efficient manner.

                      • The Code 39 Q.R. code is the most straightforward of all the alphanumeric barcodes because it performs its character verification.

                        • Code 128 is a high-density, efficient symbology for encoding alphanumeric data. The checksum digit is incorporated into the symbology, and the Barcode's integrity can be checked by comparing the checksum with the original data or by comparing the Barcode's bytes to the original data's parity.

                        Since Code 128 is widely utilized for its ability to hold alphanumeric data of a fixed length, we've chosen it to employ in our project.

                        Types of Barcode Scanners

                        1. Pen-type Barcode

                        This scanner is widely used in retail stores as its cordless. A photodiode and L.E.D. are integrated into its tip. When light is shone on a barcode, its dark bars soak up the rays. In addition, the photodiode's output is reflected in the white areas. Because of this, the scanner can read the generated output waveform. They guarantee low costs and long service life. More specifically, the scanner has to maintain a fixed angle as it moves across the barcodes at a fixed rate. The user may have to spend some time at the gym to get good at this.

                        1. Laser-type Barcode

                        They follow the same principle as traditional pen readers. They use a laser beam as the light source and a revolving prism to detect it. Therefore, they are effective even at a distance of two feet. This allows them to be surface-mounted, eliminating the need for handshakes. Compared to traditional pen-style scanners, these are far superior due to their speed and accuracy.

                        1. Light-Emitting Diode Scanner

                        The ambient light that the Barcode emits is what is measured. The information is translated into a voltage pattern, which is then read by an L.E.D. scanner. Unlike other barcode scanners, this one doesn't come with a light source. Although the C.C.D. systems are pricey, they are more adaptable and accurate than alternatives. They're commonly found in stores.

                        1. Camera barcode reader 

                        The two-dimensional Barcode is usually scanned using a barcode scanner with a two-dimensional camera. The camera must be set to auto-focus and maintained at a fixed distance. Multiple small lights are placed to form the camera. The barcodes will be photographed digitally and uploaded to the system.

                        1. Imaging barcodes with a cell phone

                        These days, practically every smartphone has a built-in scanner. Successfully scanning the 2-dimensional Bar code will not necessitate autofocus. These barcodes are unreadable by a regular scanner.

                        Circuit Diagram of Barcode Scanner with Raspberry Pi 4

                        The Barcode detected by the barcode reader will be displayed on a 16x2 LCD screen connected to the Raspberry Pi 4.

                        The image below illustrates the circuit diagram of Raspberry Pi 4 with an LCD display and barcode scanner.

                        The Barcode scanner is connected via USB to Raspberry Pi 4, while the LCD is connected to the SPI pins of RPi4. The SPI pinout is as follows:

                        Here's the circuit diagram of the LCD 16x2 with RPi4:

                        Here's our hardware setup and as you can see, we have interfaced both LCD and barcode scanner with the Raspberry Pi 4. We also have a sheet of barcodes to scan:

                        Configuring Raspberry Pi's I2C Interface

                        To begin, we need to turn on I2C on the Raspberry Pi. Here is the command to enter in the terminal:

                        sudo raspi-config

                        Now, use the down arrow key to access the Interfacing menu, and from there, select the P5 option, which is the I2C Enable/Disable menu item.

                        Once that's done, it'll inquire whether or not "you want the A.R.M. interface to be enabled." If you want to see "The ARM I2C adapter is enabled," select "Yes>." Select "ok" and then "Complete" to confirm your selections.

                        To begin working on the Liquid crystal display, you must first verify its I2C address in the Python console.

                        sudo i2cdetect -y 1

                        The attached I2C device has address 27, as shown above.

                        Barcode Scanner Configuration

                        This came together with my barcode scanner. This card will allow us to quickly and easily alter the device's default settings and change the Data rate, Trigger mode, and more.

                        Make sure the method of data transmission is USB transmission before we begin programming. The reading mode should be set to Triggering, and the Suffix should be C.R.*. The end of a data set information is always signaled by an enter command when a carriage return is used.

                        Python Code for Barcode Scanner with Raspberry Pi 4

                        Now, access the Pi's command prompt and type pip install RPI LCD to get the software package downloaded and set up. My laptop and Raspberry Pi share the same wifi network; thus, I can control it from here using a V.N.C. viewer. In addition, I used THONNY and Python 3.7.3 to write the Code.

                        Since we'll be using Delay to show the material on the LCD, we're starting the Program by importing the Sleep object from time. Then, the RPI LCD object, used for integrating the 16 x 2 display, will be imported.

                        from time import sleep

                        from rpi_lcd import LCD

                        The number of objects scanned up until the loop's execution is kept in an item count variable. At first, it is set to 0 so that no invalid values are stored. For the same reason, the scanned Barcode will be saved in a variable called score, which will initially be empty.

                        item_count=0   

                        scode="" 

                        LCD.text("Scan the Code... ", 1)   

                        As long as the while loop is active, scanning will continue indefinitely unless the controller is reset. Terminal input is required for this loop's input() function, and the resulting String will be saved in the variable scope. Then, we'll get it shown on an LCD screen:

                        While 1:   

                            scode= str(input())  

                            LCD.text("Scanned Barcode is", 1)

                            LCD.text(code,2)  

                            sleep(2)   

                            LCD.text("   Item Added", 1)

                            sleep(2)

                            item_count=item_count+1   

                            IC=str(item_count)   

                            LCD.text("  Total Item = ",1)

                            LCD.text(IC,2) 

                            sleep(1)

                        The initial value of the item count was 0; however, it will be increased while the loop is executed. The item count is currently set to 1. We'll use typecasting to change the item count value from an integer to a string so that it can be shown on the LCD screen through the LCD.text() function.

                        Viewing the accompanying illustrations may help clarify matters. After two seconds, the LCD will show the total number of items scanned rather than the scanned Barcode itself (which will remain on the screen for two seconds).

                        Complete Code

                        from time import sleep

                        from rpi_lcd import LCD

                        LCD = LCD() 

                        item_count=0   

                        scode="" 

                        LCD.text("Scan the Code... ", 1)   

                        while 1:   

                            scode= str(input()) 

                            LCD.text("Scanned Barcode is", 1)

                            LCD.text(code,2)  

                            sleep(2)   #Delay of 2 seconds

                            LCD.text("   Item Added", 1)

                            sleep(2)

                            item_count=item_count+1   

                            IC=str(item_count)  

                            LCD.text("  Total Item = ",1)

                            LCD.text(IC,2) 

                            sleep(1)

                        Assembling a Shopping Cart with a Barcode Scanner

                        Electrical Schematic of a High-Tech Shopping Cart

                        The following illustration depicts the wiring for connecting a barcode reader, thermal printers, and Liquid crystal display to a Raspberry Pi 4. The following table shows the relationships between these terms for your convenience.

                        Smart Shopping Cart Programming

                        Now that we have all the parts hooked up, we can begin writing the Program for the intelligent cart. Before moving further, let's review the ideas we've covered in our prior assignments. I am compiling a summary of the essential takeaways from the preceding part.

                        • Turn on the I2C port to connect the 20x4 alphanumeric LCD to the computer and the serial port to connect the thermal printer.
                        • Adapt your USB barcode scanner to your specific needs.
                        • Make a Google doc and use it with your Google Apps account.
                        • Use as few commands as possible to test all of the peripherals.
                        • Putting in the Necessary Libraries:
                        • Python ESCPOS
                        • Python RPLCD
                        • Python Gspread

                        Complete Code

                        import spread

                        from time import sleep

                        from RPLCD.i2c import CharLCD

                        LCD = CharLCD('PCF8574', 0x27)

                        from escpos.printer import Serial

                        from DateTime import DateTime

                        now = DateTime.now()

                        dt_string = now.strftime("%b/%d/%Y %H:%M:%S")

                        lcd.cursor_pos = (0, 0)

                        LCD.write_string("Initialising...")

                        #locating the spreadsheet JSON file

                        GC = spread.service_account(filename='/home/pi/Ali Proj/Proj 4 Shopping Cart with Thermal Printer/Shopping Cart on 20_4 LCD/shop-data-thermal-585dc7bffa1f.json')

                        #sheet name is to be passed

                        sh = GC.open("Shop Data for Thermal")

                        worksheet=sh.get_worksheet(0)

                        The preceding Code includes imports for all required libraries, including spread for the Google Sheets Application programming interface, time for wait or rest functions, RPLCD for 20X4 Liquid crystal display, escapes for serially controlling the Heated Printer, and date and Time for retrieving the current date.

                        Using my Google account, I made a spreadsheet titled "Shop Data for Thermal." Please create your own and give it any name you wish. Please see the G spread docs for information on setting up your Google Spreadsheet and JSON for your Google service account.

                        Next, we'll launch Sheet1 by invoking get worksheet(0) and loading it into the sh editor.

                        """ 9600 Baud, 8N1, Flow Control Enabled """

                        p = Serial(devfile='/dev/serial0',

                                   baudrate=9600,

                                   bytesize=8,

                                   parity='N',

                                   stopbits=1,

                                   timeout=1.00,

                                   dsrdtr=True)

                        This Code will be used to set up and initialize the serial port based on the parameters provided.

                        count=0

                        item_cost=0

                        totalCost=0

                        SNo=0

                        scode=""

                        qty=1

                        scodePrev=0

                        item_name=""

                        entryF=[]

                        p.set(

                            align="center",

                            font="a",

                            width=1,

                            height=1, 

                            )

                        The necessary variables will now be initialized to " " or " 0 " to prevent any invalid data from being stored in them. In addition, the set() function will be used to establish the thermal printer's default printing settings.

                        def print_receipt():

                            p.text("\n")

                            p.set(

                                    align="center",

                                    font="a",

                                    width=1,

                                    height=1,   

                                )

                            #Printing the image

                            p.image("/home/pi/Ali Proj/Proj 3 Interfacing thermal printer with pi/CD_new_Logo_black.png",impl="bitImageColumn")

                            #printing the initial data

                            p.set(width=2,

                                 height=2,

                                 align="center",)

                            p.text(" ===============\n")

                            p.text("Tax Invoice\n")

                            p.text(" ===============\n")

                            p.set(width=1,

                                 height=1,

                                 align="left",)

                            p.text("CIRCUIT DIGEST\n")

                            p.text("AIRPORT ROAD\n")

                            p.text("LOCATION : JAIPUR\n")

                            p.text("TEL : 0141222585\n")

                            p.text("GSTIN : 08AAMFT88558855\n")

                            p.text("Bill No. : \n\n")

                            p.text("DATE : ")

                            p.text(dt_string)

                            p.text("\n")

                            p.text("CASHIER : \n")

                            p.text(" ===========================\n")

                            p.text("S.No     ITEM   QTY   PRICE\n")

                            p.text(" ------------------------------\n")

                            print(text_F)

                            p.text(text_F)

                            p.text(" -------------------------------\n")

                            p.set(

                                    # underline=0,

                                    align="right",

                                 )

                            p.text("     SUBTOTAL:  ")

                            p.text(totalCostS)

                            p.text("\n")         

                            p.text("     DISCOUNT:  0\n")

                            p.text("     VAT @ 0%: 0\n")

                            p.text(" ===========================\n")

                            p.set(align="center", 

                               )

                            p.text("    BILL TOTAL: ")

                            p.text(totalCostS)

                            p.text("\n")

                            p.text(" --------------------------\n")

                            p.text("THANK YOU\n")   

                            p.set(width=2,

                                 height=2,

                                 align="center",)

                            p.text(" ===============\n")

                            p.text("Please scan\nto Pay\n")

                            p.text(" ===============\n")

                            p.set(

                                    align="center",

                                    font="a",

                                    width=1,

                                    height=1,

                                    density=2,

                                    invert=0,

                                    smooth=False,

                                    flip=False,      

                                )

                            p.qr("9509957951@ybl",native=True,size=12)

                            p.text("\n")

                            p.barcode('123456', 'CODE39')

                            #if your printer has paper cutting facility, then you can use this function

                            p.cut()

                            print("printing done")

                        With the Code above, we can quickly generate a method to output the total due. The invoice's format is also determined in the same procedure. A '123456' barcode can be printed using the p.barcode() method.

                        Suppose the detected Barcode does not match the database sheet. In that case, a message will be displayed on the terminal's Liquid crystal display and in the terminal's memory reading "Unknown Barcode" or "Item Not Registered," respectively, using the try/except logic. You can view this under the following line of Code.

                        lcd.cursor_pos = (0, 0)

                        LCD.write_string('Please Scan...')

                        while 1:

                            try:

                                scode=input("Scan the barcode")      

                                if scode=="8906128542687": #Bill Printing Barcode pasted on the Thermal Printer

                                    print("done shopping ")

                                    LCD.clear()

                                    print(*entryF)

                                    print("in string")

                                    print(len(entryF))

                                    text_F=" "

                                    for i in range(0,len(entryF)):

                                        text_F=text_F+entryF[i]

                                        i=i+1          

                                    lcd.cursor_pos = (0, 0)

                                    lcd.write_string("Thanks for Shopping")         

                                    lcd.cursor_pos = (1, 7)

                                    lcd.write_string("With Us")          

                                    lcd.cursor_pos = (3, 0)

                                    lcd.write_string("Printing Invoice...")

                                    print_receipt()

                                else:

                                    cell=worksheet.find(code)

                                    print("found on R%sC%s"%(cell.row,cell.col))

                                    item_cost = worksheet.cell(cell.row, cell.col+2).value

                                    item_name = worksheet.cell(cell.row, cell.col+1).value

                                    lcd.clear()

                                    SNo=SNo+1   

                                    entry = [SNo,item_name,qty,item_cost]

                                    entryS=str(entry)+'\n'

                                    print("New Item ",*entry)

                                    lcd.cursor_pos = (0, 2)

                                    LCD.write_string(str(SNo))

                                    lcd.cursor_pos = (0, 5)

                                    LCD.write_string("Item(s) added")          

                                    lcd.cursor_pos = (1, 1)

                                    LCD.write_string(item_name)          

                                    lcd.cursor_pos = (2, 5)

                                    LCD.write_string("of Rs.")

                                    lcd.cursor_pos = (2, 11)

                                    LCD.write_string(item_cost)           

                                    item_cost=int(item_cost)

                                    totalCost=item_cost+totalCost           

                                    lcd.cursor_pos = (3, 4)

                                    LCD.write_string("Cart Total")           

                                    lcd.cursor_pos = (3, 15)

                                    lcd.write_string(str(totalCost))           

                                    entryF.append(entryS)   #adding entry in Final Buffer

                                    sleep(2)           

                            except:

                                print("Unknown Barcode or Item Not Registered")

                                LCD.clear()

                                lcd.cursor_pos = (0, 0)

                                LCD.write_string("Item Not Found...")

                                lcd.cursor_pos = (2, 0)

                                LCD.write_string("Scan Again...")

                                sleep(2)

                        Cart Usage Guide

                        1. First, you pick out the product you want and scan its Barcode.

                        2. Verify the accuracy of the LCD.

                        3. Scan something else and perform the same thing

                        4. Once you have everything you need, scan the Barcode affixed to the thermal printer to initiate the billing process.

                        5. Collect the bill and use the Q.R. code to pay using a U.P.I. account.

                        Real-life Applications of Barcode Scanners

                        • Managing libraries is a specialty of library automation.

                        Each book is equipped with a barcode that the system uses to keep track of its current availability. The barcode scanner provides the librarian with up-to-date information on the books that have been checked out. Books can be checked automatically, allowing for less workforce.

                        • Maintaining a stock-taking system.

                        Barcodes provide for more efficient product recognition and data deployment. Manually entering data at the front end raises the risk of human error, which can cause delays and financial losses. But the barcode scanner is highly accurate and rarely makes mistakes when processing product orders. Because the data is automatically recorded with each sale, this simplifies stock-taking by cutting down on time spent manually looking for items.

                        • Reservations for travel

                        The billing procedure can be lengthy and frustrating at movie theaters, motels, and other establishments. Bills generated through electronic billing systems include a barcode or Q.R. code that can be easily decoded using a scanner kept by the relevant authorities.

                        • Billing office

                        It lessens the likelihood of mistakes occurring during billing's manual data entry process. Barcode scanners have many applications in billing departments, including speedy data gathering and the ability to check pricing and promotions.

                        • For Office Biometrics

                        A company's employees are obligated daily to record their attendance and clock in/out times. Scan the Barcode on their I.D. cards instead of having them manually enter their information.

                        1. For use in the production and logistics sectors

                        Using a barcode scanner, keeping tabs on company property is possible. A quick snapshot of the warehouse's inventory is provided. Raw materials utilized in production must also be sent to different markets. Consequently, there can be no mistakes in the labeling. As a result, it speeds up transactions and generates more money.

                        Reducing the likelihood of making mistakes and responding quickly to consumer requests are critical to growing the business. Time constraints can be met with more efficiency when both incoming and leaving shipments are monitored regularly. As industrial processes become increasingly mechanized, the cost of human labor declines.

                        1. On campus

                        The main features include tracking fixed assets like computers, lab equipment, machinery, etc. Teachers or employees responsible for the safety of their assets, such as the craft, can keep tabs on them with this feature. Barcode scanning keeps track of books and supplies that have gone missing in a library. A student's entrance and exit from the library can be quickly and accurately recorded using barcode scanners.

                        1. Industry of Health Care

                        Surgical supplies, patient specimens, pharmaceuticals, etc., must be tracked. Barcodes on patients' wrists allow doctors to quickly and readily verify that their care is being administered properly. These barcodes make it simple to record and monitor the previous distribution of prescriptions.

                        1. Governmental and Military Affairs

                        They take great care to ensure that sensitive information about the country does not leak. Problems with data recording or disclosure could lead to legal trouble. Official data can be kept safe with the use of barcodes.

                        1. Logistics

                        A worker working in logistics could be accountable for juggling multiple products at once, which increases the likelihood of making mistakes and sending out the wrong items. A barcode scanner can be used to automate this process with little room for error.

                        1. The Retail Industry

                        Including a barcode on each item will speed up the billing process by eliminating the need to enter each purchase manually. It will also make it simpler to view stock levels. Theft can be prevented by installing a barcode-based sensor on the exit door. In addition, this technology makes it easy to track the discounts applied to each item and ensure that they are still valid, reducing the need for human labor.

                        Conclusion

                        Barcode scanners prove essential for managing a wide variety of administrative processes. It appears that barcode scanning technology will continue to evolve in the future. We have seen how to construct our own "Smart Shopping Cart," complete with a barcode scanner to read the item's Barcode, retrieve the prices from the databases, show the information of the scanned object on an LCD for reference, and print the invoice using a thermal receipt printer. In the next tutorial, we will discuss How to design a Cryptocurrency Miner with Raspberry Pi 4. So, stay tuned. Have a good day.

                        Syed Zain Nasir

                        I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

                        Share
                        Published by
                        Syed Zain Nasir