Interface a Ws2812 RGB with Raspberry Pi 4

Thank you for joining us today for our in-depth Raspberry Pi programming tutorial. The previous guide covered the steps necessary to connect a fingerprint scanner to a Raspberry Pi 4. In addition, we developed a python script to complement the sensor's ability to identify fingerprints. Yet, in this guide, we'll discover how to interface a ws2812 RGB to a Raspberry Pi 4.

Bright, colorful lights are the best, and this tutorial shows you how to set up Fully Configurable WS2812B led strips to run on a Pi 4 computer as quickly and flexibly as possible. In that manner, you can have the ambiance of your home reflect your tastes.

In most cases, when people talk about a "WS2812B Strip," they mean a long piece of extensible PCB with a bunch of different RGB LED Nodes spread out and dotting all along the top. As a bonus, WS2812B strips can be addressed individually. Each RGB node can independently set its own color and brightness. The functionality of non-addressable RGB strips will be identical to that of WS2812B strips. WS2812B Strips are superior in every way, allowing for more imaginative LED light shows. It is possible to create more complex animations, stripes, and chases by individually programming the actions of each LED Node.

The "WS" in WS2812B indicates that this is the second major revision of this design; "World Semi" refers to the chip's original equipment manufacturer, "2812" to its specific part number, and "B" to its revision number. Each WS2812B LED Node contains an integrated circuit chip, as shown below.

Fully Configurable Strip LEDs now come in wide varieties. It's important to remember whether the strip operates on 5 volts or 12-volt power. To power our 5V-powered Raspberry Pi Computer, we need to use a 5V power supply. Or we'll have to install extra gear to meet the 12v Dc power specifications. LED Node densities also vary across WS2812B LED strips. Since our strip consists of WS2812B nodes soldered onto rigid PCBs, it may also be controlled by the Python script included in this article. ws2812B LED strips are the ideal LEDs to use because of the benefits above. What this manual entails is listed below.

The control mechanism implemented in this tutorial works with WS2812B LED nodes, whether they are rigidly coupled on a PCB or flexibly arranged over a long strip. No prior experience with Raspberry Pi has required, thanks to our comprehensive online raspberry pi 4 for the introduction. You should be able to follow these guidelines if you've read at least chapter 1. 

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

WS2812B protocol

Let's go over the protocol for these addressable LEDs so you can see how they function. Each WS2812B unit's red, green, and blue LEDs can be independently controlled to one of 256 brightness levels. Each LED module needs 24 bits of data or three groups of eight brightness bits. Here's a quick rundown of the steps involved:

  • The first LED in the string receives this data stream from the microcontroller, which consists of eight green bits, eight red bits, and eight blue bits.

  • In the case of several LEDs, the data sequence for the second LED begins with green, red, and blue information immediately after the information for the first LED. The process repeats itself until each LED is turned on.

  • The first LED acts as a receiver for data for all subsequent LEDs in the chain and then sends that data to the second LED without applying the same sequence.

  • When the original "number one" LED unit runs out of binary LED sequences, it passes the baton to the next available unit.

What You Need

What follows are detailed instructions for configuring a single Raspberry Pi board to manage many individually addressable LEDs.

  • A pi 4

  • 5v led strip

  • A DC barrel jack to 2-pin terminal block adapter. 

More than 30 WS2812B strip Nodes will necessitate the usage of an external power supply. Even with highly efficient LEDs, producing brilliant light takes a lot of energy. On average, each pixel will consume 20mA, and while projecting white light at full brightness, each pixel will consume 60mA. This information shows us that 30 Pixels can consume 600mA on average and 1.8A at full brightness. As a side note, staring directly into a room with the lights set to full white causes blind spots in my vision. Because of this, I typically set the brightness of my WS2812B lights to 20%. Ensure your WS2812B strip's power source is adequate for the illumination level you intend to achieve.

In today's world, 3.3V data logic is compatible with most WS2812B LED nodes. The GPIO Pins on a Raspberry Pi have an operational voltage range of 0 to 3.3V; therefore, this works out perfectly. This surface-mounted WS2812B strip Node has seen five minor changes since its inception. Since the earlier WS2812B strip can only work on 5V Data Logic, a logical level shifter may be necessary if you're experiencing strange or intermittent issues.

Assembling Hardware

We'll configure our Raspberry PI to look and act like a desktop PC because that's how most people use computers at home and because it's the most user-friendly setup for novice makers. To convert our Raspberry Pi into a desktop computer, we'll need to install a micro-SD card pre-flashed with the operating system. Then hook it up to a monitor via HDMI and a mouse/keyboard combo. Also, this is a good moment to install a small heatsink on the Raspberry Pi Board's central processing unit IC. Look at the image below to see the setup adjacent to a short WS2812B LED strip with three wires protruding from it. The WS2812B has three wires that have not yet been connected to the Raspberry Pi. WS2812B LED Strip PCBs are often marked with arrows to indicate the direction of data flow. It is a common problem in troubleshooting when this is ignored.

How to Configure Hardware for WS2812B Chains with fewer than 30 Nodes We need to plug in the 5V WS2812B Strip's three wires to the Raspberry Pi before turning the power on. Link the Raspberry Pi's 5V Power Input Pin with the Red Power Cable. Join the white wire labeled "Ground" to the Pi's Ground pin. Join the Raspberry Pi's Green Input Pin to its GPIO 18 port. It is important to remember that the Green Input Pin could be any GPIO pin as long as the appropriate adjustments are made in your Python programs. In this manual, GPIO 18 will be used for the Data Line in all scripts. The picture below shows how these three wires are joined together. This straightforward system can provide power and data transmission for a limited amount of LEDs.

Hardware Configuration for a WS2812B Strip with more than 30 Nodes in Length. However, the Pi 4 Power Pin Out is not powerful enough to power a full LED strip. It's important to know the power requirements of fully addressable WS2812B LEDs, especially when used in large quantities. 150 fully illuminated RGBW LEDs should be manageable by a high-quality 5v 4A power supply.

Following the diagram below, we will connect a 5V 4A power source via a DC barrel jack. Our WS2812B LEDs are pre-soldered with one green data wire, two red power wires, and two white ground wires. The white wire should be attached to the DC barrel jack's negative terminal using a screwdriver. Join the Red Wire to the Terminal With the Positive Screw Down. The White Connectors all link to one other, indicating a Common Ground shared by the Raspberry Pi and the power source. The two devices can't be connected without ground, which will prevent voltage fluctuations and data transmission mistakes.

Furthermore, the WS2812B Strip is no longer connected to the Pi 4 computer via a red power wire. We have found an alternative to using a Raspberry Pi to run our system. See the diagram below for details on connecting a Raspberry Pi to a string of WS2812B LEDs so that they may be controlled remotely.

There are several great best practices to keep in mind if you're planning on powering many LED strips. If you need to run more than a 5-meter roll of LEDs, I recommend consulting the adafruit documentation on the subject. It's important to think about heat and currents.

Now that everything is hooked up how you like it, you can turn on the Pi 4 System by inserting a USB-C cable.

Set up of software.

You'll need to install a few packages if you're starting with a clean install of Raspberry Pi OS. Since this is the case, WS2812B LEDs will function properly. When you plug the Raspberry Pi into an electrical outlet and finish the initial boot-up wizard, you will be taken to the operating system's familiar desktop.

Click the black button in the upper left corner to open a new terminal window. An interactive terminal will launch. Below is a picture of this happening, with a huge red arrow indicating the pressed terminal icon.

With this terminal window, we can search for specific programs and download them from the internet. Here are the command lines you use in the terminal to install everything you need. Type | Y | to confirm installs if prompted.

sudo pip3 install rpi_ws281x

sudo pip3 install adafruit-circuitpython-neopixel

sudo python3 -m pip install --force-reinstall adafruit-blinka

You now have the software and programming packages installed on your Device to power and run WS2812B properly.

Flashing led demonstration

You may trigger the Raspberry Pi to turn on the associated WS2812B LED strips in various ways. To begin, I will utilize the simplest and quickest technique, which involves hooking up this Raspberry Pi to a monitor, mouse, and keyboard so that I can execute Python scripts directly to control it. Below, you'll find the best and most fun Python script to start with: | strandtest.py |. Even though it's far more involved than the rest of the Python scripts in this tutorial, we felt it was essential to include it first because it provides a comprehensive overview of the various possible patterns and lighting styles.

import time

from rpi_ws281x import *

import argparse

LED_COUNT      = 30     

LED_PIN        = 18      

LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)

LED_DMA        = 10      # DMA channel to use for generating a signal (try 10)

LED_BRIGHTNESS = 65      # Set to 0 for darkest and 255 for brightest

LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)

LED_CHANNEL    = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

def colorWipe(strip, color, wait_ms=50):

    """Wipe color across display a pixel at a time."""

    for i in range(strip.numPixels()):

        strip.setPixelColor(i, color)

        strip.show()

        time.sleep(wait_ms/1000.0)

def theaterChase(strip, color, wait_ms=50, iterations=10):

    """Movie theater light style chaser animation."""

    for j in range(iterations):

        for q in range(3):

            for i in range(0, strip.numPixels(), 3):

                strip.setPixelColor(i+q, color)

            strip.show()

            time.sleep(wait_ms/1000.0)

            for i in range(0, strip.numPixels(), 3):

                strip.setPixelColor(i+q, 0)

def wheel(pos):

    """Generate rainbow colors across 0-255 positions."""

    if pos < 85:

        return Color(pos * 3, 255 - pos * 3, 0)

    elif pos < 170:

        pos -= 85

        return Color(255 - pos * 3, 0, pos * 3)

    else:

        pos -= 170

        return Color(0, pos * 3, 255 - pos * 3)

def rainbow(strip, wait_ms=20, iterations=1):

    """Draw rainbow that fades across all pixels at once."""

    for j in range(256*iterations):

        for i in range(strip.numPixels()):

            strip.setPixelColor(i, wheel((i+j) & 255))

        strip.show()

        time.sleep(wait_ms/1000.0)

def rainbowCycle(strip, wait_ms=20, iterations=5):

    """Draw rainbow that uniformly distributes itself across all pixels."""

    for j in range(256*iterations):

        for i in range(strip.numPixels()):

            strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))

        strip.show()

        time.sleep(wait_ms/1000.0)

def theaterChaseRainbow(strip, wait_ms=50):

    """Rainbow movie theater light style chaser animation."""

    for j in range(256):

        for q in range(3):

            for i in range(0, strip.numPixels(), 3):

                strip.setPixelColor(i+q, wheel((i+j) % 255))

            strip.show()

            time.sleep(wait_ms/1000.0)

            for i in range(0, strip.numPixels(), 3):

                strip.setPixelColor(i+q, 0)

# Main program logic follows:

if __name__ == '__main__':

    # Process arguments

    parser = argparse.ArgumentParser()

    parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')

    args = parser.parse_args()

    # Create NeoPixel object with appropriate configuration.

    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)

    # Intialize the library (must be called once before other functions).

    strip.begin()

    print ('Press Ctrl-C to quit.')

    if not args.clear:

        print('Use "-c" argument to clear LEDs on exit')

    try:

        while True:

            print ('Color wipe animations.')

            colorWipe(strip, Color(255, 0, 0))  # Red wipe

            colorWipe(strip, Color(0, 255, 0))  # Blue wipe

            colorWipe(strip, Color(0, 0, 255))  # Green wipe

            print ('Theater chase animations.')

            theaterChase(strip, Color(127, 127, 127))  # White theater chase

            theaterChase(strip, Color(127,   0,   0))  # Red theater chase

            theaterChase(strip, Color(  0,   0, 127))  # Blue theater chase

            print ('Rainbow animations.')

            rainbow(strip)

            rainbowCycle(strip)

            theaterChaseRainbow(strip)

    except KeyboardInterrupt:

        if args.clear:

            colorWipe(strip, Color(0,0,0), 10)

Get started with Python using an IDE like Thonny IDE. You can use any Python Interpreter you like, as Thonny IDE is one of many. Thonny IDE can be accessed through the Application Menu under the Programming submenu. Then, copy the above code inside Thonny Python Editor and save it as strandtest.py on your desktop. Proceed by clicking the large green Run button. See what happens when you do that in the image below.

With that, you should see vibrant hues coming from your LED strip. If individual LEDs on your WS2812B LED Strip aren't lighting up, but the others are, open the Python script, locate the variable labeled LED COUNT, and raise its value till it's in line with the number of LEDs on your strip. The script can be saved and re-run by clicking the Run button. To accommodate the enormous quantity of WS2812B LED Strip, I set this variable to 150. In the next image, you can see a long WS2812B strip that has been wired to an external power source and is controlled by the modified Python script.

Basic Code for WS2812B LED Tape

Now you can check if your Device is properly constructed and functioning with the help of the above strandtest.py script. Moreover, the resulting illumination is just breathtaking. Maker may be left wanting more, though. This is of special importance to the readability of the code, which facilitates its adaptation to specific tasks. This section will show you how to control the WS2812B strip with a few basic Python programs easily modified to suit your needs.

To get started, look at OneStripNeopixels.py, a very basic WS2812B Control Script.

import time

import board

import neopixel

#Initialise, a strips variable, provide the GPIO Data Pin

# utilized and the amount of LED Nodes on the strip and brightness (0 to 1 value)

pixels1 = neopixel.NeoPixel(board.D18, 55, brightness=1)

#Also, create an arbitrary count variable

x=0

pixels1.fill((0, 220, 0))

#LED Node 10 and the color Blue were selected

pixels1[10] = (0, 20, 255)

#Showing a different color

time.sleep(4)

#Below will loop until variable x has a value of 35

while x<35:

    pixels1[x] = (255, 0, 0)

    pixels1[x-5] = (255, 0, 100)

    pixels1[x-10] = (0, 0, 255)

    #Add 1 to the counter

    x=x+1

    #Add a small time pause which will translate to 'smoothly' changing color

    time.sleep(0.05)

#Below section is the same process as the above loop, just in reverse

while x>-15:

    pixels1[x] = (255, 0, 0)

    pixels1[x+5] = (255, 0, 100)

    pixels1[x+10] = (0, 255, 0)

    x=x-1

    time.sleep(0.05)

#Add a brief time delay to appreciate what has happened    

time.sleep(4)

#Complete the script by returning all the LEDs to the off

pixels1.fill((0, 0, 0))

The Python script has been thoroughly commented on, so you should have no trouble following along. The script in the previous paragraph includes readily apparent dials and switches. You'll learn the fundamentals of making a captivating LED Pattern, including how to adjust the number of LED Nodes, the brightness of the LED strips, whether to illuminate the entire board or just a section of it and how to illuminate individual LEDs. Each Node color can be customized by entering a corresponding Red, Blue, or Green numeric value. A number can have any value between zero and 255. The term "RGB Color Code" is commonly used to describe this. While experimenting with different hues can be a lot of fun, the best method to find the precise shade you need is to use a website that lists RGB color codes. Choose any color on this site, and you'll get its corresponding RGB color code in three numbers. After you've located the three-digit color code, you can easily enter it into the Python program.

You can copy and paste the script into Thonny IDE and run it. Once you've saved the file, you can press the run button to activate the script. Below are some screenshots displaying the output.

Control Several LED Strips at Once

Next is to hook up a few different LED Strips to the Pi 4 SBC and run a Python script to manage everything. Hardware-wise, I've replicated the procedure described in Hardware Configuration for Small, fewer than 30 Nodes long WS2812B, adding a second, similarly-sized WS2812B LED Strip.

I wired an additional WS2812B strip of lights up to the GPIO in the manner described below. The Raspberry Pi's other 5V Pin was connected to the red power line. The Raspberry Pi's White Ground Wire was attached to the board's second Ground Port. In this case, GPIO 21 received the green data wire. Check out the diagram of the wired components below; using two WS2812B LED strips of varying density is fine.

Using Thonny IDE as previously, run the python script titled TwoStripsNeopixels.py to control these two WS2812B Strips in a no-frills fashion. Look at this thoroughly documented Python script down here.

#include all necessary packages to get LEDs to work with Raspberry Pi

import time

import board

import neopixel

#Initialise two strips variables, provide the GPIO Data Pin

# utilized and the amount of LED Nodes and brightness (0 to 1 value)

pixels1 = neopixel.NeoPixel(board.D18, 30, brightness=1)

pixels2 = neopixel.NeoPixel(board.D21, 6, brightness=1)

#Focusing on a particular strip, use the command Fill to make it all a single color

#based on decimal code R, G, B. Number can be anything from 255 - 0. Use an RGB Colour

#Code Chart Website to quickly identify a desired fill color.

pixels1.fill((0, 255, 0))

pixels2.fill((0, 0, 255))

#Sleep for one second, and then code repeats for different color combinations. Light changes

#Could happen instead in response to certain buttons being pressed or due to threshold values

time.sleep(1.5)

pixels1.fill((200, 200, 0))

pixels2.fill((0, 200, 200))

time.sleep(1.5)

pixels1.fill((50, 70, 215))

pixels2.fill((215, 50, 70))

time.sleep(1.5)

pixels1.fill((0, 0, 0))

pixels2.fill((0, 0, 0))

Note that a Pi 4Computer has four Data Wire locations that can control individual WS2812B LED Strips, provided the corresponding Python script is updated correctly. The pinouts are numbered as follows: GPIO18, GPIO21, GPIO12, and GPIO10. With some tweaking and development of this technique, you can use a single Raspberry Pi as a standalone controller for four individually addressable WS2812B strips.

Ensure the right number of LED Nodes has been assigned to both LED WS2812B Strips before running the script. Once the script is ready to be executed, click the Thonny IDE's large green Run button. Both strands will suddenly come to life, each filled with a unique color. In the picture below, you can see this in action.

Conclusion

In this tutorial, we looked at connecting a WS2812B led strip to a Raspberry Pi. We also programmed the LEDs to blink in various patterns and colors using Python. You may now explore with your raspberry pi and these led strips to create patterns or whatever you like. Next, we'll look at connecting a Pi 4 to a sharp infrared distance measurement sensor.

Interface 7-Segment Display with Raspberry Pi 4

Thank you for being here for today's tutorial of our in-depth Raspberry Pi programming tutorial. The previous tutorial taught us how to install a PIR sensor on a Raspberry Pi 4 to create a motion detector. However, this tutorial will teach you how to connect a single seven-segment display to a Raspberry Pi 4. In the following sections, we will show you how to connect a Raspberry Pi to a 4-digit Seven-Segment Display Module so that the time can be shown on it.

Seven-segment displays are a simple type of Display that use eight light-emitting diodes to show off decimal numbers. It's common to find it in gadgets like digital clocks, calculators, and electronic meters that show numbers. Raspberry Pi, built around an ARM chip, is widely acknowledged as an excellent Development Platform. Its strong processing power can do amazing things in the hands of electronics enthusiasts and students. If we can figure out how to have it talk to the outside world and process data via an output, then we'll have a real chance of accomplishing all this. We analyze the data by viewing it on an LCD screen or other Display. Numerous sensors can detect specific parameters in the physical world and convert them to the digital world. It would never make sense to utilize a PI LCD panel to display a minimal quantity of information. Here, a 7-Segment or 16x2-Alphanumeric LCD panel is the preferred method of presentation.

There are few uses for a 7-segment display that don't need an LCD panel, even though a 16x2 LCD is preferable in most. If all you need to do is show some numbers, then an LCD, which has the downside of having a small character size, is excessive. Compared to a regular LCD screen, seven segments have the upper hand in dim environments and can be seen from wider angles. Let's get started.

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

Components

  • Jumper wires

  • Seven segment display

  • 1KΩresistors

  • Breadboard

The 7-Segment and 4-Digit Display Modules

The seven segments of a 7 Segment Display are each lit up by an individual LED to show the digits. To show the number 5, for example, you would make the glow pins for segments a, f, g, c, and d on the 7-segment high. This particular 7-segment display is a Common Cathode version, although there is also a Common Anode version.

One 7-Segment Display Interfacing with Pi 4

The wiring diagram for connecting a 7-segment display to a Raspberry Pi is shown below. Here, 7-Segment Common Cathode has been utilized.

So, we'll simulate an 8-bit PORT on PI using its eight GPIO pins. Here, GPIO12 is the Most Significant Bit (MSB), while GPIO13 is the Least Significant Bit (LSB) (Most Significant Bit).

If we wish to show the number 1, we must activate both segments B and C. We must supply voltage to GPIO6 and GPIO16 to power segments B and C. Accordingly, the hexadecimal value of "PORT" is "06," and the byte value of "PORT" is "0b00000110." If we raise both pins to their highest positions, the number "1" will be shown.

The value for every displayable digit has been recorded and saved in a Character String with the label 'DISPLAY .'We have then used the Function 'PORT' to call those values one at a time and display the relevant digit.

Explanation of the Code

Once everything is wired up according to the schematic, we can power up the PI and begin using PYTHON to write the program. Below is a function that allows us to program the GPIO pins on the PI, and we'll go over the few commands we'll be using in the PYTHON program to do so. We are also changing the name of the GPIO pins in the hardware from "GPIO" to "IO," which will be used throughout the code.

import RPi.GPIO as IO

The general-purpose input/output (GPIO) pins we need to use may be occupied with other tasks. If that's the case, the program's execution will be interrupted by warnings. The below command instructs the PI to continue running the software regardless of the warnings.

IO.setwarnings(False)

Pin numbers on the board and pin functions can be used to refer to PI's GPIOs. This GPIO5 is similar to the one labeled "PIN 29" on the board. Here we specify whether the number 29 or the number 5 will stand in for the pin.

IO.setmode (IO.BCM)

To use the LCD's data and control pins, we have assigned those functions to eight of the GPIO pins.

IO.setup(13,IO.OUT)

IO.setup(6,IO.OUT)

IO.setup(16,IO.OUT)

IO.setup(20,IO.OUT)

IO.setup(21,IO.OUT)

IO.setup(19,IO.OUT)

IO.setup(26,IO.OUT)

IO.setup(12,IO.OUT)

If the condition between the brackets evaluates to true, the looped statements will be run once. The value of PIN13 would be HIGH if and only if bit0 of the 8-bit 'pin' is true. There are eight 'if else' conditions, one for each of bits 0 through 7, so that each LED in the seven-segment Display can be set to either the High or Low state, depending on the value of the corresponding bit.

if(pin&0x01 == 0x01):

   IO.output(13,1)

else:

   IO.output(13,0)

As x increases from 0 to 9, the loop will be run 10 times for each command.

for x in range(10):

The following command can create an infinite loop, with which the statements included within the loop will be run repeatedly.

While 1:

All other commands and functions have been commented on in the following code.

Single 7-segment Display complete code

import RPi.GPIO as IO            # calling for the header file, which helps us use GPIO's of PI

import time                              # calling for time to provide delays in the program

DISPLAY = [0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x67]            # string of characters storing PORT values for each digit.

IO.setwarnings(False)            # do not show any warnings.

IO.setmode (IO.BCM)           # programming the GPIO by BCM pin numbers. (like PIN29 as‘GPIO5’)

IO.setup(13,IO.OUT)             # initialize GPIO Pins as outputs

IO.setup(6,IO.OUT)

IO.setup(16,IO.OUT)

IO.setup(20,IO.OUT)

IO.setup(21,IO.OUT)

IO.setup(19,IO.OUT)

IO.setup(26,IO.OUT)

IO.setup(12,IO.OUT)

def PORT(pin):                    # assigning GPIO logic by taking the 'pin' value

    if(pin&0x01 == 0x01):

        IO.output(13,1)            # if  bit0 of 8bit 'pin' is true, pull PIN13 high

    else:

        IO.output(13,0)            # if  bit0 of 8bit 'pin' is false, pull PIN13 low

    if(pin&0x02 == 0x02):

        IO.output(6,1)             # if  bit1 of 8bit 'pin' is true, pull PIN6 high

    else:

        IO.output(6,0)            #if  bit1 of 8bit 'pin' is false, pull PIN6 low

    if(pin&0x04 == 0x04):

        IO.output(16,1)

    else:

        IO.output(16,0)

    if(pin&0x08 == 0x08):

        IO.output(20,1)

    else:

        IO.output(20,0)   

    if(pin&0x10 == 0x10):

        IO.output(21,1)

    else:

        IO.output(21,0)

    if(pin&0x20 == 0x20):

        IO.output(19,1)

    else:

        IO.output(19,0)

    if(pin&0x40 == 0x40):

        IO.output(26,1)

    else:

        IO.output(26,0)

    if(pin&0x80 == 0x80):

        IO.output(12,1)            # if  bit7 of 8bit 'pin' is true, pull PIN12 high

    else:

        IO.output(12,0)            # if  bit7 of 8bit 'pin' is false, pull PIN12 low

While 1:

    for x in range(10):            # execute the loop ten times incrementing x value from zero to nine

        pin = DISPLAY[x]        # assigning value to 'pin' for each digit

        PORT(pin);                  # showing each digit on display 

        time.sleep(1)

Output

The process of displaying a single number character on a 7-segment display is complete. However, we'd need more than a single 7-segment display to express information with more than one digit. Therefore, we will use a 4-digit seven-segment display circuit for this session.

Four individual Seven-Segment Displays have been linked up here. For a 4-digit 7-segment display, we know that each module will have 10 pins, so there will be 40 pins total. Soldering that many pins onto a dot board would be a hassle for anyone; thus, I recommend that anyone using a 7-segment display do so by purchasing a module or creating their PCB. See below for a diagram of the relevant connections:

In the preceding diagrams, we can see that the A-lines of all four displays are linked together as one A, and the same is true for B, C.... up until DP, which is essential for understanding how the 4-digit seven-segment module functions. Put another way, if trigger A is activated, the state of all 4 A's should be high.

Nonetheless, this never occurs. The four extra pins labeled D0 through D3 (D0, D1, D2, and D3) let us select which of the four displays is driven high. As an illustration, if I want my output to appear solely on the second Display, I would set D1 to high and leave D0, D2, and D3 at low. Using pins D0–D3 and A–DP, we can easily choose which displays should be on and which characters should be shown.

Using a Pi 4  to interface with a 4-digit, 7-segment display module

Let's check the many options for interfacing this 4-digit seven-segment Display with the Raspberry Pi. As can be seen in the diagram below, there are 16 pins on the 7-segment module. Even if your module's resources are limited, it will provide at least the following.

  • Segmented pins, either 7 or 8 segments (pins 1 to 8)

  • Pin holder to the ground (here pin 11)

  • A 4-digit code to unlock the door (pins 13 to 16)

See below for the wiring diagram of a digital clock built with a Raspberry Pi and a 4-digit Seven-segment display module:

You can also use the following table to ensure your connections are correct and follow the diagrams.

Locating the module's pins is the first step in making electrical connections. Identifying the Raspberry Pi's GPIO pins can be tricky; I've included an image to help.

Raspberry Pi programming

Here, RPi is programmed in the Python programming language. The Raspberry Pi can be programmed in a wide variety of ways. Since Python 3 has become the de facto standard, we've opted to use that version as our integrated development environment (IDE). At the bottom of this guide, you'll find the whole Python code.

We'll go over the PYTHON instructions we'll be using for this project: first, we'll import the library's GPIO file; next, using the below function, we'll be able to program the Pi 4's GPIO pins. We are also changing the name of the GPIO pins in the hardware from "GPIO" to "IO," which will be used throughout the code. We've brought in time and DateTime to get the current time from Rasp Pi.

import RPi.GPIO as GPIO

import time, DateTime

The GPIO pins we're trying to use are already being used for something else. The program's execution will be interrupted with warnings if this is the case. The PI will be instructed to disregard the errors and continue with the software using the below command.

IO.setwarnings(False)

The physical pin number and the corresponding function number can refer to PI's GPIOs. As with 'PIN 29,' GPIO5 is a physical component on the circuit board. In this case, we specify whether the number "29" or "5" will stand in for the pin. GPIO. In BCM notation, GPIO5 pin 29 will be represented by a 5.

IO.setmode (GPIO.BCM)

As is customary, we'll start by setting the pins to their default values; in this case, both the segment and digit pins will be used as outputs. In our code, we organize the segment pins into arrays and set their values to zero by declaring them to be GPIO.OUT.

segment8 = (26,19,13,6,5,11,9,10)

for segment in segment8:

    GPIO.setup(segment, GPIO.OUT)

    GPIO.output(segment, 0)

We do the same thing with the digital pins, but we set them to output and set them to zero by default.

#Digit 1

    GPIO.setup(7, GPIO.OUT)

    GPIO.output(7, 0) #Off initially

    #Digit 2

    GPIO.setup(8, GPIO.OUT)

    GPIO.output(8, 0) #Off initially

    #Digit 3

    GPIO.setup(25, GPIO.OUT)

    GPIO.output(25, 0) #Off initially

    #Digit 4

    GPIO.setup(24, GPIO.OUT)

    GPIO.output(24, 0) #Off initially

Numbers on a seven-segment display must be formed into arrays. To show a single digit, we need to toggle the on/off status of all but the dot pin of the 7-segment Display. For the numeral 5, for instance, we can use this setup:

For all alphabets and numerals, there is an equivalent sequence number. You can write on your own or utilize the handy table provided.

Using this information, we can create arrays for each digit in our Python code, as demonstrated below.

null = [0,0,0,0,0,0,0]

zero = [1,1,1,1,1,1,0]

one = [0,1,1,0,0,0,0]

two = [1,1,0,1,1,0,1]

three = [1,1,1,1,0,0,1]

four = [0,1,1,0,0,1,1]

five = [1,0,1,1,0,1,1]

six = [1,0,1,1,1,1,1]

seven = [1,1,1,0,0,0,0]

eight = [1,1,1,1,1,1,1]

nine = [1,1,1,1,0,1,1]

Let's bypass the function in the code that would otherwise be executed before entering the while loop and begin displaying characters on our 7-segment Display. If you hook up a Raspberry Pi to the internet, it will read the current time and divide it into four separate variables. For instance, when the time is 10.45, the values assigned to h1 and h2 will be 1 and 0, while m1 and m2 will be 4 and 5, respectively.

now = DateTime.DateTime.now()

    hour = now.hour

    minute = now.minute

    h1 = hour/10

    h2 = hour % 10

    m1 = minute /10

    m2 = minute % 10

    print (h1,h2,m1,m2)

These four numbers will be displayed on one of our four digits. The lines below can be used to convert a variable's value to a decimal. Here, we show the value in variables on the 7-segment Display by using the function print segment (variable) with the digit 1 set to the highest possible value. You may be asking why we turn off this digit and why there's a delay after that.

GPIO.output(7, 1) #Turn on Digit One

print_segment (h1) #Print h1 on segment

time.sleep(delay_time)

GPIO.output(7, 0) #Turn off Digit One

This is because the user will only be able to see the full four-digit number if all four digits are shown at once, and we all know that this isn't possible.

How, then, can we simultaneously show all four digits? With luck, our MPU is considerably quicker than the human eye. Therefore we offer one number at a time but exceptionally quickly. The MPU and segment display are given 2ms (variable delay time) to process each digit before we go on to the next. A human being cannot detect this 2ms lag; therefore, it appears as though all four digits illuminate simultaneously.

Understanding how to use print segment(variable) is the final puzzle piece. Arrays that have been declared outside of this function are used within it. As a result, the value of any variable passed to this function must be inside the range (0-9) so that the character variable can use in a meaningful comparison. Here, we check the variable against the value 1. The same is true for all comparisons with numbers between zero and nine. Assigning each value from the arrays to the appropriate segment pins is what we do if a match is found.

def print_segment(character):

    if character == 1:

        for i in range(7):

            GPIO.output(segment8[i], one[i])

Show the time on a 4-digit 7-segment display.

Use the provided schematic and code to connect your components and set up your Raspberry Pi. Once you've finished setting everything up, you can open the software and check the 7-segment Display to see the time. However, before doing this, you should check a few things.

  • If you want to be sure your Raspberry Pi isn't stuck in the past, you should update its time.

  • If you want to utilize a 7-segment display on your Raspberry Pi, you'll need to plug it into an adapter rather than a computer's USB connection because of the large amount of current it consumes.

Complete code

import RPi.GPIO as GPIO

import time, DateTime

now = datetime.datetime.now()

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

 #GPIO ports for the 7seg pins

segment8 =  (26,19,13,6,5,11,9,10)

for segment in segment8:

    GPIO.setup(segment, GPIO.OUT)

    GPIO.output(segment, 0)

    #Digit 1

    GPIO.setup(7, GPIO.OUT)

    GPIO.output(7, 0) #Off initially

    #Digit 2

    GPIO.setup(8, GPIO.OUT)

    GPIO.output(8, 0) #Off initially

    #Digit 3

    GPIO.setup(25, GPIO.OUT)

    GPIO.output(25, 0) #Off initially

    #Digit 4

    GPIO.setup(24, GPIO.OUT)

    GPIO.output(24, 0) #Off initially

null = [0,0,0,0,0,0,0]

zero = [1,1,1,1,1,1,0]

one = [0,1,1,0,0,0,0]

two = [1,1,0,1,1,0,1]

three = [1,1,1,1,0,0,1]

four = [0,1,1,0,0,1,1]

five = [1,0,1,1,0,1,1]

six = [1,0,1,1,1,1,1]

seven = [1,1,1,0,0,0,0]

eight = [1,1,1,1,1,1,1]

nine = [1,1,1,1,0,1,1]

def print_segment(charector):

    if charector == 1:

        for i in range(7):

            GPIO.output(segment8[i], one[i])

    if charector == 2:

        for i in range(7):

            GPIO.output(segment8[i], two[i])

    if charector == 3:

        for i in range(7):

            GPIO.output(segment8[i], three[i])

    if charector == 4:

        for i in range(7):

            GPIO.output(segment8[i], four[i])

    if charector == 5:

        for i in range(7):

            GPIO.output(segment8[i], five[i])

    if charector == 6:

        for i in range(7):

            GPIO.output(segment8[i], six[i])

    if charector == 7:

        for i in range(7):

            GPIO.output(segment8[i], seven[i])

    if charector == 8:

        for i in range(7):

            GPIO.output(segment8[i], eight[i])

    if charector == 9:

        for i in range(7):

            GPIO.output(segment8[i], nine[i])

    if charector == 0:

        for i in range(7):

            GPIO.output(segment8[i], zero[i])               

    return;

while 1:

    now = DateTime.DateTime.now()

    hour = now.hour

    minute = now.minute

    h1 = hour/10

    h2 = hour % 10

    m1 = minute /10

    m2 = minute % 10

    print (h1,h2,m1,m2)

    delay_time = 0.001 #delay to create the virtual effect

    GPIO.output(7, 1) #Turn on Digit One

    print_segment (h1) #Print h1 on segment

    time.sleep(delay_time)

    GPIO.output(7, 0) #Turn off Digit One

    GPIO.output(8, 1) #Turn on Digit One

    print_segment (h2) #Print h1 on segment

    GPIO.output(10, 1) #Display point On

    time.sleep(delay_time)

    GPIO.output(10, 0) #Display point Off

    GPIO.output(8, 0) #Turn off Digit One

    GPIO.output(25, 1) #Turn on Digit One

    print_segment (m1) #Print h1 on segment

    time.sleep(delay_time)

    GPIO.output(25, 0) #Turn off Digit One

    GPIO.output(24, 1) #Turn on Digit One

    print_segment (m2) #Print h1 on segment

    time.sleep(delay_time)

    GPIO.output(24, 0) #Turn off Digit One

    #time.sleep(1)

Output

A similar section should appear below if everything is functioning as it should.

7-segment Display limitations

Typically, only 16 hexadecimal digits can be shown on a seven-segment display. Some show the digits 0-9, whereas others can show more. Seven-segment displays can only show a maximum of 16 values due to a lack of input leads. However, LED technology does allow for more than this. Even with the help of integrated circuit technology, the possible permutations of the seven parts on the screen are very few.

Conclusion

This guide taught us how to connect a 7-segment screen to a Raspberry Pi 4. The seven-segment Display, which we learned is employed in digital timers, clocks, and other electrical gadgets, are a cheap, basic electrical circuit and reliable module. Seven-segment displays can either be "common-anode" (where the common point is the power input) or "common-cathode" (where the common end is grounded). After that, we coded some python scripts to show numbers on a single seven-segment model and the time across four such screens. Next, we'll see how to use a Raspberry Pi 4 as the basis for a low-power Bitcoin miner.

Interface RFID Module RC522 with Raspberry Pi 4

We're glad you could join us for another lesson in our comprehensive Raspberry Pi programming guide. I will show you how to install and connect the RFID card chip to your Raspberry Pi through step-by-step instructions.

Modern security systems would only be complete using radio frequency (RFID) devices. To control who can enter a facility or which rooms they can access, RFID chips and card readers are employed. The RFID card's unique identification number can be read wirelessly with a wall-mounted RFID reader. A door will only unlock and allow entry if the RFID card's unique identification number matches a list of approved cards.

It's fun to tinker with this circuit, and it may be used in many other applications, from opening locks to taking attendance. The MFRC522 microcontroller underpins the RFID RC522, a cheap RFID (Radio-frequency identification) reader/writer. The RFID tags can connect with this microcontroller using an electromagnetic field it generates at 13.56MHz and sends to them via the SPI protocol. If you want to use your RFID RC522 with tags, you must ensure that they are 13.56MHz compatible. We'll walk you through the wiring of the RC522 and the creation of Python programs to communicate with the chip, allowing you to read and write RFID tags. Adding a 16x2 LCD to the Raspberry Pi is a simple extension of this tutorial, and it can be helpful if you need to show the user some information or provide a visual prompt.

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

Components

  • Raspberry Pi

  • Micro SD Card

  • Power Supply

  • RC522 RFID Reader

  • Breadboard

  • Breadboard Wire

What is an RFID RC522

An RFID reader reads the tag's data when a Rfid card is attached to a specific object. An RFID tag communicates with a reader via radio waves.

In theory, RFID is comparable to bar codes because it uses radio frequency identification. While a reader's line of sight to the RFID tag is preferable, it is not required to be directly scanned by the reader. You can only read an RFID tag up to three feet away from the reader. The RFID tech quickly scans many objects, making it possible to identify a specific product rapidly and effortlessly, even if it is sandwiched between several other things.

Explained: the functioning of rfid readers and writers

Major components of Cards and tags include an integrated circuit (IC) that stores the unique identification value and a copper that acts as the antenna.

Inside the Rfid reader is another copper wire coil. This coil produces a magnetic field when current flows through it. Magnetic flux creates a current inside the wire coil when the card is brought close to the reader. This current can power the card's internal integrated circuit. The reader then takes in the card's serial number. A card reader will send the card's serial number to a central processing unit (CPU) like a Raspberry Pi for further processing.

Assembling the RFID RC522

When you buy an RFID RC522 Reader, you may discover that 90% of them do not have the header pins pre-installed. Due to a lack of pins, you'll have to solder them yourself; however, this is a relatively easy task, even for amateurs. Assuming the header pins that came with your RC522 are too large, you may snap them in half to reduce them to a single column of eight.

Start by inserting the header pins into the RC522 from the top. The circuit may be easily placed on top of the connector pins by inserting the large side of the pins onto a breadboard. The breadboard's secure holding of the pins will make soldering them to the RFID circuit much simpler.

Solder each pin individually by carefully heating your soldering iron and applying it to the pins. Remember that heating the junction slightly before to solder application increases the solder's adhesion and decreases the likelihood of generating a cold joint. When using solder, we advise you to be conservative. When you've finished soldering the header pins onto your RFID circuit, you'll be ready to move on with the guide.

Wiring the RFID RC522

There are eight different connectors on the RFID RC522. Except for the IRQ, we need to connect all these to the GPIO pins on our Raspberry Pi.

This guide shows how to connect an RFID RC522 to a Breadboard and then to the Raspberry Pi's GPIO Pins, although you could also wire the components straight to the Pi.

Simply connecting 7 of the Raspberry Pi's GPIO pins to the RFID RC522 reader is all needed to get it up and to run. Refer to the GPIO pin locations detailed in our tutorial and the table below when deciding how to wire your RC522.

  • SDA connects to Pin 24.

  • SCK connects to Pin 23.

  • MOSI connects to Pin 19.

  • MISO connects to Pin 21.

  • GND connects to Pin 6.

  • RST connects to Pin 22.

  • 3.3v connects to Pin 1.

Setting up Raspbian for the RFID RC522

We need to adjust the Raspberry Pi's settings before we can use the RFID RC522. Inconveniently, our RFID reader circuit relies on the Raspberry Pi's SPI (Serial Peripheral Interface), which is disabled by default. Worry not, though, as it is easy to restore this interface; follow our instructions below to set up your RPi and Raspbian to use the SPI port. Launch the raspi-config utility by opening a terminal and typing the following command.

sudo raspi-config

A menu of choices will appear when you use this tool. You may read up on all of these options in the raspi-config documentation. Choose "5 Interfacing Options" using the arrow keys. Select this choice, and then hit the Enter key. Once "P4 SPI" is selected in the next screen, press Enter once more to confirm your selection. To continue, use the arrow keys to choose "Yes" and then press Enter when prompted to confirm that you want to activate the SPI Interface. For the raspi-config utility to finish enabling SPI, you'll have to be patient for a while.

The raspi-config tool's success in enabling the SPI interface will be shown by the display of the message "The SPI interface is enabled." Activating the SPI Interface requires a full reboot of the Raspberry Pi. Press Enter, and then ESC, to return to the terminal. If you want to restart the RPi, enter the following Unix instruction into the terminal.

sudo reboot

It is time to verify that Raspberry Pi has been activated now that it has rebooted. Checking if spi bcm2835 is available is as simple as running the following command.

lsmod | grep spi

If you get spi bcm2835, you're good to go with the rest of the tutorial. If you tried the preceding command and it didn't work, try the following three things. If the SPI component is not enabled, we can manually modify the boot config file by issuing the following code to our RPi.

sudo nano /boot/config.txt

You can use CTRL + W to search the configuration file for "dtparam=spi=on" If you think you have discovered it, look if it has a number in front of it. If there is, delete it because it disables the code. If you cannot find the line, add "dtparam=spi=on" to the very end of the file. To commit your modifications, use CTRL + X, followed by Y and Enter. You can double-check that the module has been activated by restarting your Raspberry Pi, as in Step 5.

Getting Python ready for the RFID RC522

After connecting our RFID circuit to the RPi, we can turn it on and start writing Python scripts to communicate with the chip. You'll learn how to read and write information to RFID chips by composing scripts like the ones we'll provide. These will serve as the foundation for future RFID RC522 tutorials and provide you with a fundamental understanding of how data is handled. The Raspberry Pi must be brought up to date with the most recent software versions before we can begin programming. Get the latest version of Raspbian for your Pi by running these two commands.

sudo apt update

sudo apt upgrade

Installing the python3-dev, python-pip, and git packages is the last thing to do before moving forward. To get your RFID reader set up with this guide, type the following command into your Raspberry Pi's terminal.

sudo apt install python3-dev python3-pip

Now that we have python "pip" installed on our Raspberry Pi, we can install the spidev Python library. An integral part of this guide, the spidev library allows the RPi to communicate with the RFID via the SPI. Run the following command to get spidev set up on your Raspberry Pi via pip. It's important to remember that we're using sudo to guarantee that the package gets installed for everyone's usage, not just the logged-in user.

sudo pip3 install spidev

After getting the spidev library up and running on our Raspberry Pi, we'll move on to setting up the MFRC522 library with pip. Two files, in particular, are used by us, both of which are part of the MFRC522 library:

This library, MFRC522.py, implements the RC522 interface for communicating with RFIDs via Raspberry Pi's SPI port.

Simplifying the MFRC522.py file so that you only need to work with a small subset of its many functions, SimpleMFRC522.py is a significant time saver.

Enter this command into your terminal to have pip setup the MFRC522 library on your Pi 4:

sudo pip3 install mfrc522

Now that the library has been transferred to the Pi, we can start writing code for the RFID RC522. First, we'll explore how to use the RC522 to program your RFID cards. Move on to the following part, where we will write our first Python code.

Writing with the RFID RC522

In this first Python script, we'll go over the steps needed to send information from the RC522 to RFID tags. This is made more accessible by the SimpleMFRC522 script, but we'll still break down the code's individual components for you. To begin, let's create a directory to hold the scripts we'll be using. Create the "pi-RFID" folder by using the following command.

mkdir ~/pi-rfid

To get started, navigate to the folder you just cloned and create the Write.py script in Python.

cd ~/pi-RFID

sudo nano Write.py

Add the following blocks of code to this file. This code prompts you for some text, which it then uses to update the RFID Tag.

#!/usr/bin/env python

import RPi.GPIO as GPIO

from mfrc522 import SimpleMFRC522

The very first line of the code snippet instructs the terminal to use Python rather than another scripting language like Bash to parse and run the file. To guarantee that the GPIO Pins are reset when the script terminates, we must first import the RPi.GPIO package contains all the necessary functions for communicating with the GPIO Pins. The second import is our SimpleMFRC522 library, which will be used to communicate with the RFID RC522. Compared to the standard MFRC522 library, it dramatically simplifies working with the chip.

reader = SimpleMFRC522()

In this line, we make a new instance of the SimpleMFRC522 object, use its setup function, and save the result in our readers variable.

try:

        text = input('New data:')

        print("Now place your tag to write")

        reader.write(text)

        print("Written")

We enclose the following section of code with a try statement to ensure that any unforeseen problems are handled, and the code is cleaned up correctly. Python is whitespace sensitive; it uses tabs to distinguish between code sections, so keep them after trying. In this case, the second line reads a command-line input and stores it in a text variable using Python 3's input function.

The third line makes advantage of print() to prompt the user to set the RFID tag onto the reader. After that, on line 4, we utilize our scanner object to instruct the RFID Circuit to write the text field's contents to a certain sector of the RFID tag. On line 5, after successfully writing to the RFID tag, we call print() once more to inform the user.

finally:

        GPIO.cleanup()

The script will terminate in the last two lines of code. The finally statement always follows the try statement. Thus the GPIO.cleanup() method is called after each iteration of the try block. These lines are essential because improper cleanup can disrupt the functionality of other programs. Upon completion, your script should be like the example given below.

The file can be saved by pressing CTRL Plus X, Y, then ENTER once you've double-checked the code and are convinced it's correct. Now that the script is written, we need to put it through some testing. Get an RFID tag ready before running the script for testing. When you're ready, open the terminal on your Raspberry Pi and enter the following command.

sudo python3 Write.py

In this situation, we're just going to type in "any word" because it's easy to remember and short. Press the Enter key when you have finished writing and are ready to send. After that, your RFID Tag can be placed directly above your RFID circuit. It will immediately update the tag with fresh information when it does. You'd see the word "Written" on the command prompt if it worked. Now that you have your Write.py script completed, we can move on to explaining how to read information from the RFID RC522.

Reading with the RFID RC522

We have successfully programmed our RC522 to print to RFID tags and can now move on to writing a script to retrieve the data from the tags. First, we'll make sure we're in the correct location by switching directories, and then we'll use nano to start drafting the Read.py script.

cd ~/pi-rfid

sudo nano Read.py

Incorporate the following code into this document. When an RFID tag is placed in the RFID reader, the script will wait until the tag's data has been read before displaying the results.

This file's first line of code instructs the operating system on how to proceed when the user clicks the "Run" button. If you don't specify that it's a Python file, it'll try to run it like any other script. An initial RPi.GPIO import is made. Importing this library ensures that the Raspberry Pi's GPIO pins are cleaned up after script termination, as it contains all the necessary functions. SimpleMFRC522 is the second import. With the assistance functions included in this script, reading and writing to an RFID RC522 is a breeze, whereas, with them, the scripts would quickly grow to be manageable.

This line is crucial because it invokes SimpleMFRC522's creation method, which returns an object that is subsequently stored in our reader variable.

try:

        id, text = reader.read()

        print(id)

        print(text)

The following code section will be encapsulated in a try block to allow us to handle any unforeseen errors gracefully. Because Python is sensitive to whitespace, you must use the 'tabs' as displayed following try:

In this scenario, the second line of this code block initiates a call on our scanner object, instructing the circuits to begin scanning any Rfid card that is positioned on top of the reader. On the third and forth lines, we use print() to display the data we gleaned from the RFID Chip; this includes the tag's unique identifier and any text it may consist of.

finally:

        GPIO.cleanup()

The script ends with the last two lines of code. No of what happens inside the try block, the final statement is always executed afterward. No matter what, the GPIO.cleanup() code will be executed thanks to this try statement. It's vitally important, as not doing so can disrupt the proper operation of other scripts that rely on the GPIO. Your completed Read.py script for the RFID RC522 should resemble the example below.

When you've double-checked your code and are satisfied with it, press Ctrl + X, then Y, and finally ENTER to save the file. The time has come to put our completed Read.py script to the test. Get ready to test the script by picking up any of the RFID tags. If you're all set, enter this command into the terminal on your Raspberry Pi.

sudo python3 Read.py

Now that the script is active, you can set your RFID Tag atop your RFID circuit. When the RFID tag is placed on top, the Python program will immediately begin reading the information from the tag and display the results on the screen. What a finished product might look like is shown below as an illustration.

To test whether your Raspberry Pi is properly connected on the RFID RC522 Circuit, run the Read.py script and see if it returns any data that matches the text you wrote to the card in the Write.py script.

Conclusion

Connecting an RC522 RFID module to a Pi 4 makes reading MIFARE chips and cards is now possible. This might be very useful in security systems and other applications where identifying an item or person is required without the user having to physically interact with the device by pressing buttons, switching, or activating any sensors. Eventually, you should be able to use this to decipher the UID encoded on your MIFARE tags. You should know that these cards can be duplicated and assigned a new unique identifier (UID) if you plan on employing this technique in a security system. To ensure the safety of your system, you must ensure that no one learns your UID or gains remote access to your devices. The contactless tags are convenient because they can be attached to a keychain, and the cards are convenient because they can be carried in a wallet. Both things can be concealed inside others to give them a hidden identifier that the Pi can access. With the help of our Pi 4-powered RFID attendance systems guide, you can learn how to set up your RFID Reader/Writer for use in checking attendance. Our exploration of the RFID chip and the scripts above will continue in subsequent guides. A door security system is one of the fantastic DIY Pi ideas we'll look into. The next lesson will teach you how to connect a 16x2 LCD screen to a Raspberry Pi 4.

IoT based Web Controlled Home Automation using Raspberry Pi 4

Greetings, and welcome to today's tutorial. In the last tutorial, we learned how to construct a system for tallying individuals using Raspberry Pi, astute subtraction, and blob tracking. We demonstrated the total number of building entrances and exits. Feature computation and HOG theory were also discussed. The tests proved that a device based on the raspberry pi could effectively function as a people counting station. One of the many benefits of the Pi 4 is its internet connectivity, which is especially useful for home automation projects due to its low price and ease of use. We're going to see if we can use a web page's buttons to manage our air conditioner today. With this Internet of Things (IoT) based home automation, you can command your home gadgets from the comfort of your couch. The user can access this web server from any gadget capable of loading HTML apps, such as a smartphone, tablet, computer, etc.

Where To Buy?
No.ComponentsDistributorLink To Buy
1BreadboardAmazonBuy Now
2DiodesAmazonBuy Now
3Jumper WiresAmazonBuy Now
4LEDsAmazonBuy Now
5ResistorAmazonBuy Now
6TransistorAmazonBuy Now
7Raspberry Pi 4AmazonBuy Now

Components

The needs of this project can be broken down into two broad classes: hardware and software.

Hardware Requirement

  • Raspberry Pi 4

  • Memory card 8 or 16GB running Raspbian Jessie

  • 5v Relays

  • 2n222 transistors

  • Diodes

  • Jumper Wires

  • Connection Blocks

  • LEDs to test.

  • AC lamp to Test

  • Breadboard and jumper cables

  • 220 or 100 ohms resistor

Software Requirement

We'll be using the WebIOPi framework, notepad++ on your PC, and FileZilla to transfer files (particularly web app files) from your computer to the raspberry pi and the Raspbian operating system.

The Raspberry Pi Setup Process

As a good habit, I constantly update the Raspberry Pi before using it for the first time. In this project phase, we will handle the web-to-raspberry-pi connection by upgrading the Pi and setting up the WebIOPi framework. The python Flask framework provides a potentially more straightforward alternative, but getting your hands dirty and looking at how things operate makes DIY appealing. When you get to that point, the fun of DIY begins. Use the updated commands below to upgrade your Raspberry Pi and restart the RPi.

sudo apt-get update

sudo apt-get upgrade

sudo reboot

After this is finished, we can set up the webIOPi framework. Using, verify that you are in your home directory.

cd ~

To download the files from the google page, type wget.

wget http://sourceforge.net/projects/webiopi/files/WebIOPi-0.7.1.tar.gz

Then, once the download is complete, unzip the file and enter the directory;

tar xvzf WebIOPi-0.7.1.tar.gz

cd WebIOPi-0.7.1/

Unfortunately, I could not locate a version of WebIOPi that is compatible with the Pi 4; thus, we have to download a patch before proceeding with the setup. Run the instructions below from within the WebIOPi directory to apply the patch.

wget https://raw.githubusercontent.com/doublebind/raspi/master/webiopi-pi2bplus.patch

patch -p1 -i webiopi-pi2bplus.patch

Once we have those things, we can begin the WebIOPi setup installation process by using the;

sudo ./setup.sh

Just click "Yes" when prompted to install more components during setup. Upon completion, restart your Pi.

sudo reboot

Verify the WebIOPi Setup

Before diving into the schematics and programs, we should power on the Raspberry Pi and ensure our WebIOPi installation is functioning as expected. Execute the command below;

sudo webiopi -d -c /etc/webiopi/config

After running the above command on the pi, open a web browser and navigate to http://raspberrypi.mshome.net:8000 (or HTTP;//thepi'sIPaddress:8000) on the computer that is attached to the pi. When logging in, you'll be asked for a username and password.

Username is webiopi

Password is raspberry

You may permanently disable this login if you no longer need it. Still, it's important to keep unauthorized users from taking control of your home's appliances and Internet of Things (IoT) components. After you've logged in, go to the GPIO header link.

Make GPIO 17 an output; we'll use it to power an LED in this Test.

Following this, attach the led to the Pi 4 as depicted in the schematics.

When you're ready to activate or deactivate the LED, return to the web page where you made the connection and select the pin 11 button. This allows us to use WebIOPi to manage the Raspberry Pi's GPIO pins. If the Test is successful, we can return to the console and exit the program by pressing CTRL + C. Please let me know in the comments if this arrangement has any problems. Once the pilot is finished, we can begin the actual project.

Developing a Web-Based Home-Control application for the Raspberry Pi

In this section, we will alter the WebIOPi service's standard setup and inject our code to be executed on demand. FileZilla or another FTP/SCP copy program will be the first tool we install on our computer. You'll agree that using the terminal to write code on the Pi is a stressful experience, so having access to Filezilla or another SCP program will be helpful. Let's make a project directory in which all our web scripts will be stored before we begin writing the HTML, CSS, and javascript programs for this Internet - of - things Home automated Web app and transferring them to the RPi.

First, make sure you're in your home directory using; next, create the folder; finally, open the newly constructed folder and make an HTML folder inside it.

cd ~

mkdir webapp

cd webapp

mkdir HTML

Make subfolders inside the HTML folder for scripts, CSS, and graphics.

mkdir html/css

mkdir html/img

mkdir html/scripts

Now that we have our files prepared, we can start coding on the computer and transfer our work to the Pi using Filezilla.

The JavaScript Code

Writing the javascript will be our first order of business. An easy-to-use script for interacting with the WebIOPi server. Our four-button web app will only use two relays in the demonstration, and we only intend to control four GPIO pins for this project.


 webiopi().ready(function() {

                        webiopi().setFunction(17,"out");

                        webiopi().setFunction(18,"out");

                        webiopi().setFunction(22,"out");

                        webiopi().setFunction(23,"out");

                                                var content, button;

                        content = $("#content");

                                                button = webiopi().createGPIOButton(17," Relay 1");

                        content.append(button);

                                                button = webiopi().createGPIOButton(18,"Relay 2");

                        content.append(button);

                                                button = webiopi().createGPIOButton(22,"Relay 3");

                        content.append(button);

                                                button = webiopi().createGPIOButton(23,"Relay 4");

                        content.append(button);

                                });

Once the WebIOPi is ready, the preceding code is executed. To help you understand JavaScript, we've explained below:

  • webiopi().ready(function()

All this tells our system to make this function and call it once the webiopi is set.

  • webiopi().setFunction(23,"out")

We can instruct the WebIOPi program to use GPIO23 for output. Four buttons are now available, but you may add more if necessary.

  • var content, button

With this line, we're instructing the system to make a new variable called content into a button.

  • content = $("#content")

We will continue using the content variable in our HTML and CSS. As a result, the WebIOPi framework generates everything connected to #content when it is mentioned.

  • button = webiopi().createGPIOButton(17,"Relay 1")

WebIOPi can make several distinct types of push buttons. This code instructs the WebIOPi program to generate a GPIO key that operates on the GPIO pin identified as "Relay 1" above. The other ones are the same, too.

  • content.append(button)

Add this code to the button's existing HTML or external code. New buttons can be made that are identical to this one in every respect. This is especially helpful while coding or writing CSS.

If you made your JS files the same way I did, you can save them and then move them with Filezilla to webapp/HTML/scripts after you've finished making them. Now we can move on to developing the CSS.

The CSS Code:

With the aid of CSS, our Internet of Things (IoT) Rpi 4 home automation website now looks fantastic. So that the website will look like the one in the picture below, I built a custom style sheet called smarthome.css.

I don't want to paste the entire CSS script here, so I'll use a subset for the explanation. If you want to learn CSS, all you have to do is read the code. You can skip this and use our CSS code if you want to.

The first section of the script, displayed below, represents the web application's main stylesheet.

 body {

         background-color:#ffffff;

         background-image:URL('/img/smart.png');

         background-repeat:no-repeat;

         background-position:center;

         background-size:cover;

         font: bold 18px/25px Arial, sans-serif;

         color:LightGray;

     }

The above code, which I hope needs no explanation, begins by setting the background colour to white (#ffffff), adds a background image to the document from the specified folder (remember the one we created earlier? ), makes sure the picture doesn't duplicate by setting the background-repeat to no-repeat, and finally tells the CSS to center the background. Next, we adjust the background's text size, font, and colour.

After finishing the main content, we styled the buttons with CSS.

button {

         display: block;

         position: relative;

         margin: 10px;

         padding: 0 10px;

         text-align: center;

         text-decoration: none;

         width: 130px;

         height: 40px;

         font: bold 18px/25px Arial, sans-serif;  color: black;

         text-shadow: 1px 1px 1px rgba(255,255,255, .22);

         -WebKit-border-radius: 30px;

          -Moz-border-radius: 30px;

          border-radius: 30px;

}

Everything else in the script is similarly optimized for readability and brevity. You can play with them and see what happens; this kind of learning is known as "learning by doing," I believe. However, CSS's strengths lie in its simplicity, and its rules are written in plain English. The button's text shadow and button shadow are two of the few supplementary features found in the block's other section. To top it all off, pressing the button triggers a subtle transition effect, making it look polished and lifelike. To guarantee optimal page performance on all browsers, these are defined independently for WebKit, firefox, opera, etc.

The following code snippet notifies the WebIOPi service that it is receiving data as input.

input[type="range"] {

                                                display: block;

                                                width: 160px;

                                                height: 45px;

                        }

Providing feedback on when a button is pressed will be the last element we want to implement. As a result, the screen's colour scheme and button hues provide a quick indicator of progress. To accomplish this, the following line of code is added to each button's HTML.

                        #gpio17.LOW {

                                                background-color: Gray;

                                                color: Black;

                        }

                        #gpio17.HIGH {

                                                background-color: Red;

                                                color: LightGray;

                        }

The code snippets up top alter the button's color depending on the user's selection. The button's background is gray when it is inactive (at LOW) and red when it is active (at HIGH). Now that we have our CSS under control let's save it as smarthome.css, upload it to our raspberry pi's styles folder using FileZilla (or another SCP client of your choosing), and fix the remaining HTML code.

HTML Code

The HTML code unifies the style sheets and java scripts.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta name="mobile-web-app-capable" content="yes">

        <meta name="viewport" content = "height = device-height, width = device-width, user-scalable = no" />

        <title>Smart Home</title>

        <script type="text/javascript" src="/webiopi.js"></script>

        <script type="text/javascript" src="/scripts/smarthome.js"></script>

        <link rel="stylesheet" type="text/CSS" href="/styles/smarthome.css">

        <link rel="shortcut icon" sizes="196x196" href="/img/smart.png" />

</head>

<body>

                        </br>

                        </br>

                        <div id="content" align="center"></div>

                        </br>

                        </br>

                        </br>

                        <p align="center">Push button; receive bacon</p>

                        </br>

                        </br>

</body>

</html>

The head tag contains several crucial elements.

<meta name="mobile-web-app-capable" content="yes"> 

The code line above makes it possible to add the web app to the mobile device's home screen when using Chrome or Safari. You can access this function using the Chrome menu. This makes it so the app may be quickly launched on any mobile device or desktop computer.

The following line of code provides a measure of responsiveness for the web app. Because of this, it can take up the entire display of any gadget on which it is run.

<meta name="viewport" content = "height = device-height, width = device-width, user-scalable = no" /> 

The web page's title is defined in the following line of code.

<title>Smart Home</title>

The following four lines of code all connect the Html file to multiple resources it requires to function as intended.

        <script type="text/javascript" src="/webiopi.js"></script>

        <script type="text/javascript" src="/scripts/smarthome.js"></script>

        <link rel="stylesheet" type="text/CSS" href="/styles/smarthome.css">

        <link rel="shortcut icon" sizes="196x196" href="/img/smart.png" />

The first line above directly connects to the WebIOPi framework JavaScript, which is stored in the server's root directory. This method must be invoked whenever WebIOPi is used.

The second line tells the HTML document where to find our jQuery script, and the third tells where to get our style sheet. The last line prepares an icon for the mobile desktop, which can be useful if we use the website as an app or a favicon.

To ensure that our HTML code displays whatever is contained in the JavaScript file, we include break tags in the body portion of the code. The definition of our button's content was made previously in the JavaScript code, and its id="content" should bring that to mind.

<div id="content" align="center"></div>

Everybody is familiar with the routine of saving an Html file as index.html and then transferring it to the Pi's HTML folder via Filezilla.

Modifications to the WebIOPi Server for Use in Automated Household Tasks

Before we can begin sketching out circuit diagrams and running tests on our web app, we need to make a few adjustments to the webiopi service's configuration file, instructing it to look for configuration information in our HTML folder rather than the default location.

Edit the configuration by executing the following commands as root:

sudo nano /etc/webiopi/config

Find the section of the configuration file labelled "HTTP" and look for the line that begins with "#" Modify the directory where HTML and resources are stored by default with doc-root.

Remove the # comments from anything below it, and if your folder is organized like mine, set the doc-root to the location of your project file.

doc-root = /home/pi/webapp/html

Lastly, save your work and exit. If you already have another server installed on the Pi utilizing port 8000, you may easily change it. If not, let's stop saving and call it a day.

It's worth noting that the WebIOPi service password can be changed using the command;

sudo webiopi-passwd

A new login name and password will be required. Getting rid of this entirely is possible, but safety comes first.

Finally, issue the following command to start the WebIOPi service.

sudo /etc/init.d/webiopi start

If you want to see how the server is doing, you can do so by;

sudo /etc/init.d/webiopi status

That's why there's a way to halt its execution:

sudo /etc/init.d/webiopi stop

Setup WebIOPi to start automatically with;

sudo update-RC.d webiopi defaults

To do the opposite and prevent it from starting up automatically, use the following;

sudo update-RC.d webiopi remove

Schematic and Explanation of a Circuit

Now that we have everything set up, we can begin developing the schematics for our Web-controlled home appliance.

Whereas I could not procure relay modules, which in my experience, make electronics projects simpler for do-it-yourselfers. So, I'm going to draw some diagrams for regular, single-relay, 5V-powered standalone devices.

Join the components as seen in the fritzing diagram. It's important to remember that your Relay's COM, NO (usually open), and NC (typically Close) contacts could be on opposite sides. Please verify this with a millimetre.

Relays Underlying Operating Principles

Relays can be found anywhere that electricity is being switched, from a simple traffic light controller to a high-voltage switchyard. Relays, in the broadest sense, are equivalent to any other switch. They can connect or disconnect a circuit and are frequently employed to activate or deactivate an electrical load. However, this is a comprehensive statement; there are many other relays, and each Relay behaves slightly differently depending on the task at hand; as the electromechanical Relay is one of the most widely used relays, we will devote more space to discussing it here. In spite of variations in design, all relays work according to the same fundamental concept, so let's dive into the nuts and bolts of relays and talk about how they function.

So, what exactly is Relay?

A relay is called an electromechanical switch that may either establish or rupture an electrical connection. A relay is like a mechanical switch, except that it is activated and deactivated by an electronic signal rather than by physically flipping a switch. It comprises a flexible movable mechanical portion controlled electrically through an electromagnet. Once again, this Relay operating concept is suitable exclusively for electromechanical relays.

A common and widely used relay consists of electromagnets typically employed as a switch. However, there are many kinds of relays, each with its purpose. When a signal is received on one side of the device, it controls the switching activity on the other, much like the dictionary definition of Relay. That's right, a relay is an electromechanical switch that can open and close circuits. This device's primary function is to establish or sever contact with the aid of a signal to turn it ON or OFF automatically and without human intervention. Its primary use is to allow a low-power signal to exert control over a circuit with a high power consumption. Typically, the high-voltage circuit is controlled by a direct current (DC) signal.

How the Relay is Built and Functions

The following diagram depicts the internal structure and design of a Relay.

A coil of copper wire is wound around a core, which is then placed inside a housing. When the coil is electrified, it attracts the movable armature, which is supported by a spring or stand and has a metal contact attached to one end. This assembly is positioned over the core. In most cases, the movable armature is a shared connection point for the motor's internal components and the other wiring harness. The usually closed (NC) pin is linked to the common terminal, while the ordinarily opened (NO) pin is not used in operation. By connecting the armature to the usually open contact whenever the coil is activated, current can flow uninterruptedly through the armature. When the power is turned off, it returns to its starting position.

The picture below shows a schematic of the Relay's circuit in its most basic form.

Relay Teardown: An Inside Look

In the images below, you can see the main components of an electromechanical relay—an electromagnet, a flexible armature, contacts, a yoke, and a spring/frame/stand. They have been thoughtfully placed into a relay.

The workings of a Relay's mechanical components have been outlined below.

  1. Electromagnet

An electromagnet is crucial to the operation of a relay. This metal lacks magnetic properties but can be transformed into a magnet when exposed to an electrical current. It is healthy knowledge that a conductor takes on the magnetic characteristics of the current flowing through it. Thus, a metal can operate as a magnet and attract magnetic objects within its range when wound with a conductive material and powered by an adequate power source.

  1. Movable Armature

A moveable armature is just one piece of metal that can rotate or stand on its own. It facilitates connection-making and -breaking with the contacts attached to it.

  1. Contacts

Internal conductors are the wires that run through a device and hook up to its terminals.

  1. Yoke

It's a tiny metal piece attached to a core that attracts and retains the armature whenever the coil is activated.

  1. Spring (optional)

While some relays can function without a spring, those that do have one attach it to the armature at one end to prevent any snagging or binding. One can use a metal "stand" in place of a spring.

Mechanism of Action of a Relay

Let's examine the differences between a relay's normally closed and normally open states. 

Relay's NORMALLY CLOSED state

If no current flows through the core, there will be no magnetic field, and the device will not be a magnet. As a result, it is unable to draw in the flexible framework. So, the ordinarily closed position of the armature is the starting point (NC).

Relay in NORMALLY OPENED state

When a high enough voltage is supplied to the core, it begins to have a strong magnetic field around itself, allowing it to function as a magnet. The magnetic field produced by the core attracts the movable armature whenever it comes within its field of influence, changing the armature's location. As it has been wired to a normally open relay pin, any external circuits attached to it will no longer operate in the same way.

It is important to connect the relay pins correctly so that the external circuit can do its job. When a coil is powered, the armature is drawn toward it, revealing the switching action; when the power is cut, the coil loses its magnetic property, and the armature returns to its original location. The animation provided below shows the Relay in action.

Transistor functions in the circuit

There is nothing complicated about a transistor, yet there is a lot going on inside it. Okay, so first, we'll tackle the easy stuff. An electronic transistor is a small component that can switch between two functions. It's a switch that can also act as an amplifier.

An amplifier is a device that takes in a little electric current and outputs a significantly larger electric current (called an output current). It can be thought of as a current booster. One of the earliest applications for transistors, this is particularly helpful in devices like hearing aids. A hearing aid contains a microscopic microphone that converts ambient sound into electrical signals. These are then amplified by a transistor and used to power a miniature loudspeaker, which reproduces the ambient noise at a much higher volume.

It is possible to use a transistor as a switch. A transistor is a device that allows for the passage of one electrical current to induce a much larger current to flow through the next part of the device. What this means is that a relatively small current can activate a much larger one. All computer chips function in this general way. As an illustration, a memory chip may have as many as a billion individually controllable transistors. Due to the fact that each transistor can exist in either of two states, it is capable of storing either a zero or a one. A chip's ability to hold billions of zeroes and ones, as well as almost as many regular numbers and letters, is made possible by its billions of transistors.

Diode functions in the circuit

Diodes can range in size from what's shown in the image up top. They feature a cylindrical body that is usually black with a stripe at one end and certain leads that protrude so that we may plug it into a circuit. The opposite terminal is called the cathode and is opposite the anode.

A diode is an electrical component that restricts current flow in one direction.

To illustrate, picture a swing valve fitted in a water line. The water pressure inside the pipe will force open the swing gate, allowing the water to flow uninterrupted. In contrast, the gate will be forced shut, and water flow will stop if the river alters its course. As a result, there is only one direction for water to flow.

Very much like a diode, which we also employ to alter the current flow through a circuit, it allows us to switch it on and off at will.

We have now animated this process using electron flow, in which electrons move from negative to positive. However, traditional flow, positive to negative, is the norm in electronics engineering. It's usually best to start with the conventional current because it's more familiar to most people, but feel free to use either one; we'll assume you're aware of the difference.

It's important to remember that the light-emitted diode will only light up properly if the diode is connected to the circuit in the correct orientation when adding it to a simple Light emitted diode circuit like the one shown above. Only one direction of current can travel through it. Accordingly, its conductive or insulating properties are determined by the orientation in which it is mounted.

So that it can conduct electricity, you must join the black end to the neutral and the striped end to the positive. The forward bias is the condition in which current can flow. If we invert the diode, it will become an insulator and stop the passage of electricity. The term for this is "the reverse bias."

Exactly how would a diode function?

You probably know that electricity is the transfer of electrons between atoms that are not bound. Because of its high number of unpaired electrons, copper is widely used for electrical wiring. Since rubber is an insulator—its electrons are kept very securely, so they cannot flow between atoms—it is used to wrap around the copper wires for our protection.

In a simplified form of a metal conducting atom, the nucleus is at the center, and the electrons are housed in a series of shells around it. It takes a specific amount of energy for an electron to be absorbed into each shell, and each shell has a max number of electrons it can hold. Those electrons that are furthest from the nucleus are the most energetic. Conductors have between one and three electrons in their outermost "valence" shell.

The nucleus acts as a magnet, keeping the electrons in place. However, there is yet another layer, the conduction band. If an electron gets here, it can leave its atom and travel to another. Because the valence shell and conduction band of a metal atom overlap, the electron can move quickly and easily between the two.

The insulator has a tightly packed outer layer. No free space for electrons to occupy. Because of the strong attraction between the nucleus and the electrons and the great distance between the nucleus and the conduction band, the electrons are trapped inside the nucleus and cannot leave. Because of this, electricity is unable to travel through it.

Of course, a semiconductor is also a different type of material. A semiconductor might be silicon, for instance. This material behaves as an insulator because it has one more electron than is necessary in its outermost shell to be a conductor. However, with enough external energy, a few valence electrons can generate enough momentum to hop across to the conduction band, where they can finally break free. Consequently, this substance can perform the roles of both an insulator and a conductor.

Due to the lack of free electrons in pure silicon, engineers must add a small number of materials (called "doping") to the silicon to alter its electrical properties.

This process gives rise to P-type and N-type doping, respectively. The diode itself is a combination of these doped materials.

Two leads connect the anode and cathode to various thin plates inside the diode. P-Type doped silicon is on the anode side of these plates, and the cathode side is N-Type doped silicon—an insulating and protective resin that coats the entire structure.

Consider the material to be pure silicon before it has been doped. There are four silicon atoms surrounding each one. Because silicon atoms need eight electrons to fill their valence shells but only have four available, they share one with their neighbours. Covalent bonding describes this type of interaction.

Phosphorus, an N-type element, can be substituted for a number of silicon atoms in a compound semiconductor. Phosphorus has a 5-electron valence shell because of this. This extra electron isn't needed because particles are sharing them to reach the magic number of 8. This means there's an extra electrons in the material, and it's free to go wherever it wants.

In P-type doping, a substance like aluminum is introduced. Due to its limited valence electron pool of 3, this atom is unable to share an electron with any of its four neighbours. An electron-sized void is therefore made available.

We now have silicon with either too many or too few electrons, depending on the doping method.

Upon joining, the two substances forge a p-n junction. This is a depletion region, and it forms at the intersection. Here, some of the surplus electrons on the N-type side migrate over to fill the vacancies on the P-type side. By moving in this direction, electrons and holes will accumulate on either side of a barrier. Holes are thought to be positively charged since they are the opposite of electrons, which are negatively charged. The resulting accumulation produces two distinct regions, one slightly negatively charged and the other slightly positively charged. This forms an electric field that blocks the path of any more electrons. In regular diodes, the voltage drop over this area is only 0.7V.

By applying a voltage across the diode with the P-Type anode linked to the positive and the N-Type cathode attached to the negative, a forward bias is established, and current can flow. The electrons can't get over the 0.7V barrier unless the voltage source is higher.

We can achieve this by connecting the positive terminal of the power supply to the cathode of an N-type device and the negative terminal to the anode of a P-type device. The diode functions as a conductor to block current because the barrier expands as holes are drawn toward the negative and electrons are drawn toward the positive.

Resistor functions in the circuit

A resistor is a two-terminal, non-active electrical component that reduces the amount of current in electric and electronic circuits. A certain amount can lower the current by strategically placing a resistor in a circuit. From the outside, most resistors will appear identical. But if you crack it open, you'll find a ceramic rod used for insulation within, with copper wire covering the rest of the structure. Those copper twists are crucial to the resistance. When copper is sliced thinner, resistance rises because electrons have more difficulty penetrating the material. We now know that electrons can move more freely through some conductors than insulators.

George Ohm investigated the correlation between resistor size and material thickness. His proof showed that an object's resistance (R) grows in proportion to its length. Because of this, the resistance offered by the lengthier and thin wires is greater. However, wire thickness has a negative effect on resistance.

Once everything is hooked up, you can start your server by browsing to the IP address of your RPi and entering the port you chose earlier (as mentioned in the previous section), entering your password and username and seeing a page that looks like the one below.

All it takes is a few clicks of your mouse to operate four AC home appliances from afar. This can be controlled from a mobile device (phone, tablet, etc.) and expanded with additional switches and relays. Thank you all for reading to the end.

Conclusion

This guide showed us how to set up a web-based control system for our home automation system based on the Raspberry Pi 4. We have learned how to utilize the WebIOPi API to manage, debug, and use raspberry Pi's GPIO, sensors, and adapters from an internet browser or any application. We have also implemented JavaScript, CSS, and HTML code for the web application. For those who thrive on difficulty, feel free to build upon this base and add whatever demanding module you can think of to the project. The following tutorial will teach you how to use a Raspberry Pi 4 to create a Line Follower robot that can navigate obstacles and drive itself.

Social Distancing Detector with OpenCV in Raspberry Pi 4

During the era of Covid-19, social distancing has proven to be an efficient method of reducing the spread of contagious viruses. It is recommended that people avoid close contact as much as possible because of the potential for disease transmission. Many public spaces, including workplaces, banks, bus terminals, train stations, etc., struggle with the issue of keeping a safe distance.

The previous guide covered the steps necessary to connect the PCF8591 ADC/DAC Analog Digital Converter Module to a Raspberry Pi 4. On our Terminal, we saw the results displayed as integers. We dug deeper into the topic, figuring out exactly how the ADC produces its output signals. In this article, however, we will use OpenCV and a Raspberry Pi to create a system that can detect when people are trying to avoid eye contact with one another. We will employ the YOLO version 3 Object Recognition Algorithm's weights to implement the Deep Neural Networks component. Compared to other controllers, the Raspberry Pi always comes out as the best option for image processing tasks. Previous efforts utilizing Raspberry Pi for advanced image processing included a face recognition application.


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

Components 

  • Raspberry Pi 4

Only a Raspberry pi 4 having OpenCV pre-installed will do for this purpose. Digital image processing is handled with OpenCV. Digital Image Processing is often used for people counting, facial identification, and detecting objects in images.

YOLO

The savvy YOLO (You Only Look Once) Convolution neural networks (CNN) in real-time Object Detection are invaluable. The most recent version of YOLO, YOLOv3, is a fast and accurate object identification algorithm that can identify eighty distinct types of objects in both still and moving media. The algorithm first runs a unique neural net over the entire image before breaking it up into areas and computing border boxes and probability for each. The YOLO base model has a 45 fps real-time frame rate for processing photos. Compared to other detection approaches, such as SSD and R-CNN, the YOLO model is superior.

In the past, computers relied on input devices like keyboards and mice; today, they can also analyze data from visual sources like photos and videos. Computer Vision is a computer's (or a machine's) capacity to read and interpret graphic data. Computing vision has advanced to the point that it can now evaluate the nature of people and objects and even read their emotions. This is feasible because of deep learning and artificial intelligence, which allow an algorithm to learn from examples like recognizing relevant features in an unlabeled image. The technology has matured to the point where it can be employed in critical infrastructure protection, hotel management, and online banking payment portals.

OpenCV is the most widely used computer vision library. It is a free and open-source Intel cross-platform library that may be used with any OS, including Windows, Mac OS X, and Linux. This will make it possible for OpenCV to function on a mobile device like a Pi, which will have a wide range of applications. Let's dive in, then.

Setup of OpenCV on a Raspberry Pi 4

OpenCV and its prerequisites won't run without updating the Raspberry Pi to the latest version. To install the most recent software for your Raspberry Pi, type in the following commands:

sudo apt-get update

Then, use the scripts below to set up the prerequisites on your RPi so you can install OpenCV.

sudo apt-get install libhdf5-dev -y 

sudo apt-get install libhdf5-serial-dev –y 

sudo apt-get install libatlas-base-dev –y 

sudo apt-get install libjasper-dev -y 

sudo apt-get install libqtgui4 –y

sudo apt-get install libqt4-test –y

Finally, run the following lines to install OpenCV on your Raspberry Pi.

pip3 install OpenCV-contrib-python==4.1.0.25

Setting up Opencv using Cmake

OpenCV's installation on a Raspberry Pi can be nerve-wracking because it takes a long time, and there's a good possibility you'll make a mistake. Given my own experiences with this, I've tried to make this lesson as straightforward and helpful as possible so that you won't have to go through the same things I did. Even though OpenCV 4.0.1 had been out for three months when I started writing this lesson, I decided to use the older version (4.0.0) because of some issues with compiling the newer version.

This approach involves retrieving OpenCV's source package and compiling it on a Raspberry Pi with the help of CMake. Installing OpenCV in a virtual environment allows users to run many versions of Python and OpenCV on the same computer. But I'm not going to do that since I'd rather keep this essay brief and because I don't anticipate that it will be required any time soon.

Step 1: Before we get started, let's ensure that our system is up to date by executing the command below:

sudo apt-get update && sudo apt-get upgrade

If there are updated packages, they should be downloaded and installed automatically. There is a 15-20 minute wait time for the process to complete.

Step 2: We must now update the apt-get package to download CMake.

sudo apt-get update

Step 3: When we've finished updating apt-get, we can use the following command to retrieve the CMake package and put it in place on our machine.

sudo apt-get install build-essential cmake unzip pkg-config

When installing CMake, your screen should look similar to the one below.

Step 4: Then, use the following command to set up Python 3's development headers:

sudo apt-get install python3-dev

Since it was pre-installed on mine, the screen looks like this.

Step 5: The following action would be to obtain the OpenCV archive from GitHub. Here's the command you may use to replicate the effect:

wget -O opencv.zip https://github.com/opencv/opencv/archive/4.0.0.zip

You can see that we are collecting version 4.0.0 right now.

Step 6: The OpenCV contrib contains various python pre-built packages that will make our development efforts more efficient. Therefore, let's also download that with the command that is identical to the one shown below.

wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.0.0.zip

The "OpenCV-4.0.0" and "OpenCV-contrib-4.0.0" zip files should now be in your home directory. If you need to know for sure, you may always go ahead and check it out.

Step 7: Let's extract OpenCV-4.0.0 from its.zip archive with the following command.

unzip opencv.zip

Step 8: Extraction of OpenCV contrib-4.0.0 via the command line is identical.

unzip opencv_contrib.zip

Step 9: OpenCV cannot function without NumPy. Follow the command below to begin the installation.

pip install numpy

Step 10: In our new setup, the home directory would now contain two folders: OpenCV-4.0.0 and OpenCV contrib-4.0.0. Next, we'll make a new directory inside OpenCV-4.0.0 named "build" to perform the actual compilation of the Opencv library. The steps needed to achieve the same result are detailed below.

cd~/opencv

mkdir build

cd build

Step 11: OpenCV's CMake process must now be initiated. In this section, we specify the requirements for compiling OpenCV. Verify that "/OpenCV-4.0.0/build" is in your path. Then, paste the lines below into the Terminal.

cmake -D CMAKE_BUILD_TYPE=RELEASE \

    -D CMAKE_INSTALL_PREFIX=/usr/local \

    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.0.0/modules \

    -D ENABLE_NEON=ON \

    -D ENABLE_VFPV3=ON \

    -D BUILD_TESTS=OFF \

    -D WITH_TBB=OFF \

    -D INSTALL_PYTHON_EXAMPLES=OFF \

    -D BUILD_EXAMPLES=OFF ..

Hopefully, the configuration will proceed without a hitch, and you'll see "Configuring done" and "Generating done" in the output.

If you encounter an issue during this procedure, check to see if the correct path was entered and if the "OpenCV-4.0.0" and "OpenCV contrib-4.0.0" directories exist in the root directory path.

Step 12: This is the most comprehensive process that needs to be completed. Using the following command, you can compile OpenCV, but only if you are in the "/OpenCV-4.0.0/build" directory.

Make –j4

Using this method, you may initiate the OpenCV compilation process and view the status in percentage terms as it unfolds. After three to four hours, you will see a completed build screen.

The command "make -j4" utilizes all four processor cores when compiling OpenCV. Some people may feel impatient waiting for a 99% success rate, but eventually, it will be worth it.

After waiting an hour, I had to cancel the process and rebuild it with "make -j1," which did the trick. It is advisable first to use make j4 since that will utilize all four of pi's cores, and then use make j1, as make j4 will complete most of the compilation.

Step 13: If you are at this point, congratulations. You have made it through the entire procedure with flying colors. The final action is to run the following command to install libopecv.

sudo apt-get install libopencv-dev python-OpenCV

Step 14: Finally, a little python script can be run to verify that the library was successfully installed. Try "import cv2" in Python, as demonstrated below. You shouldn't get any error message when you do this.

Completing the Raspberry Pi Software Installation of Necessary Additional Packages

Let's get the necessary packages set up on the Raspberry Pi before we begin writing the code for the social distance detector.

Installing imutils

utils are designed to simplify the use of OpenCV for standard image processing tasks like translating, rotating, resizing, skeletonizing, and presenting pictures via Matplotlib. If you want to get the imutils, type in the following command:

pip3 install imutils

A Breakdown of the Program

The complete code may be found at the bottom of the page. In this section, we'll walk you through the most crucial parts of the code so you can understand it better. All the necessary libraries for this project should be imported at the beginning of the code.

import numpy as np

import cv2

import imutils

import os

import time

Distances between objects or points in a video frame can be determined with the Check() function. The two things in the picture are represented by the a and b points. The Euclidean distance is determined using these two positions as the starting and ending points.

def Check(a,  b):

    dist = ((a[0] - b[0]) ** 2 + 550 / ((a[1] + b[1]) / 2) * (a[1] - b[1]) ** 2) ** 0.5

    calibration = (a[1] + b[1]) / 2     

    if 0 < dist < 0.25 * calibration:

        return True

    else:

        return False

The YOLO weights, configuration file, and COCO names file all have specific locations that can be set in the setup function. The os.path module is everything you need to do ordinary things with pathnames. The os.path.join() sub-module intelligently combines two or more path components. cv2.dnn.read The net is reloaded with the saved weights using the netfromdarknet() function. Once the weights have been loaded, the network layers can be extracted using the getLayerNames model.

def Setup(yolo):

    global neural_net, ln, LABELS

    weights = os.path.sep.join([yolo, "yolov3.weights"])

    config = os.path.sep.join([yolo, "yolov3.cfg"])

    labelsPath = os.path.sep.join([yolo, "coco.names"])

    LABELS = open(labelsPath).read().strip().split("\n") 

    neural_net = cv2.dnn.readNetFromDarknet(config, weights)

    ln = neural_net.getLayerNames()

    ln = [ln[i[0] - 1] for i in neural_net.getUnconnectedOutLayers()]

In the image processing section, we extract a still image from the video and analyze it to find the distance between the people in the crowd. The function's first two lines specify an empty string for both the width and height of the video frame. To process many images simultaneously, we utilized the cv2.dnn.blobFromImage() method in the following line. The blob function adjusts a frame's Mean, Scale, and Channel.

(H, W) = (None, None)

    frame = image.copy()

    if W is None or H is None:

        (H, W) = frame.shape[:2]

    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)

    neural_net.setInput(blob)

    starttime = time.time()

    layerOutputs = neural_net.forward(ln)

YOLO's layer outputs are numerical values. With these numbers, we may determine which objects belong to which classes with greater precision. To identify persons, we iterate over all layerOutputs and assign the "person" class label to each. Each detection generates a bounding box whose output includes the coordinates of the detection's center on X and Y as well as its width and height.

            scores = detection[5:]

            maxi_class = np.argmax(scores)

            confidence = scores[maxi_class]

            if LABELS[maxi_class] == "person":

                if confidence > 0.5:

                    box = detection[0:4] * np.array([W, H, W, H])

                    (centerX, centerY, width, height) = box.astype("int")

                    x = int(centerX - (width / 2))

                    y = int(centerY - (height / 2))

                    outline.append([x, y, int(width), int(height)])

                    confidences.append(float(confidence))

Then, determine how far apart the middle of the active box is from the centers of all other boxes. If the rectangles overlap only a little, set the value to "true."

for i in range(len(center)):

            for j in range(len(center)):

                close = Check(center[i], center[j])

                if close:

                    pairs.append([center[i], center[j]])

                    status[i] = True

                    status[j] = True

        index = 0

In the following lines, we'll use the model's box dimensions to create a square around the individual and evaluate whether or not they are in a secure area. If there is little space between the boxes, the box's color will be red; otherwise, it will be green.

            (x, y) = (outline[i][0], outline[i][1])

            (w, h) = (outline[i][2], outline[i][3])

            if status[index] == True:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 150), 2)

            elif status[index] == False:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

Now we're inside the iteration function, where we're reading each film frame and analyzing it to determine how far apart the people are.

ret, frame = cap.read()

    if not ret:

        break

    current_img = frame.copy()

    current_img = imutils.resize(current_img, width=480)

    video = current_img.shape

    frameno += 1

    if(frameno%2 == 0 or frameno == 1):

        Setup(yolo)

        ImageProcess(current_img)

        Frame = processedImg

In the following lines, we'll utilize the opname-defined cv2.VideoWriter() function to save the output video to the provided place.

if create is None:

            fourcc = cv2.VideoWriter_fourcc(*'XVID')

            create = cv2.VideoWriter(opname, fourcc, 30, (Frame.shape[1], Frame.shape[0]), True)

    create.write(Frame)

Testing the program

When satisfied with your code, launch a terminal on your Pi and go to the directory where you kept it. The following folder structure is recommended for storing the code, Yolo framework, and demonstration video.

The yoloV3 directory is downloadable from the;

https://pjreddie.com/media/files/yolov3.weights

videos from:

https://www.pexels.com/search/videos/pedestrians/

Finally, paste the Python scripts provided below into the same folder as the one displayed above. The following command must be run once you've entered the project directory:

python3 detector.py

I applied this code to a sample video I found on pexels, and the results were interesting. The frame rate was terrible, and the film played back in almost 11 minutes.

Changing line 98 from cv2.VideoCapture(input) to cv2.VideoCapture(0) allows you to test the code without needing a video. Follow these steps to utilize OpenCV on a Raspberry Pi to identify inappropriate social distances.

Complete code

import numpy as np

import cv2

import imutils

import os

import time

def Check(a,  b):

    dist = ((a[0] - b[0]) ** 2 + 550 / ((a[1] + b[1]) / 2) * (a[1] - b[1]) ** 2) ** 0.5

    calibration = (a[1] + b[1]) / 2       

    if 0 < dist < 0.25 * calibration:

        return True

    else:

        return False

def Setup(yolo):

    global net, ln, LABELS

    weights = os.path.sep.join([yolo, "yolov3.weights"])

    config = os.path.sep.join([yolo, "yolov3.cfg"])

    labelsPath = os.path.sep.join([yolo, "coco.names"])

    LABELS = open(labelsPath).read().strip().split("\n")  

    net = cv2.dnn.readNetFromDarknet(config, weights)

    ln = net.getLayerNames()

    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

def ImageProcess(image):

    global processedImg

    (H, W) = (None, None)

    frame = image.copy()

    if W is None or H is None:

        (H, W) = frame.shape[:2]

    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)

    net.setInput(blob)

    starttime = time.time()

    layerOutputs = net.forward(ln)

    stoptime = time.time()

    print("Video is Getting Processed at {:.4f} seconds per frame".format((stoptime-starttime))) 

    confidences = []

    outline = []

    for output in layerOutputs:

        for detection in output:

            scores = detection[5:]

            maxi_class = np.argmax(scores)

            confidence = scores[maxi_class]

            if LABELS[maxi_class] == "person":

                if confidence > 0.5:

                    box = detection[0:4] * np.array([W, H, W, H])

                    (centerX, centerY, width, height) = box.astype("int")

                    x = int(centerX - (width / 2))

                    y = int(centerY - (height / 2))

                    outline.append([x, y, int(width), int(height)])

                    confidences.append(float(confidence))

    box_line = cv2.dnn.NMSBoxes(outline, confidences, 0.5, 0.3)

    if len(box_line) > 0:

        flat_box = box_line.flatten()

        pairs = []

        center = []

        status = [] 

        for i in flat_box:

            (x, y) = (outline[i][0], outline[i][1])

            (w, h) = (outline[i][2], outline[i][3])

            center.append([int(x + w / 2), int(y + h / 2)])

            status.append(False)

        for i in range(len(center)):

            for j in range(len(center)):

                close = Check(center[i], center[j])

                if close:

                    pairs.append([center[i], center[j]])

                    status[i] = True

                    status[j] = True

        index = 0

        for i in flat_box:

            (x, y) = (outline[i][0], outline[i][1])

            (w, h) = (outline[i][2], outline[i][3])

            if status[index] == True:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 150), 2)

            elif status[index] == False:

                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

            index += 1

        for h in pairs:

            cv2.line(frame, tuple(h[0]), tuple(h[1]), (0, 0, 255), 2)

    processedImg = frame.copy()

create = None

frameno = 0

filename = "newVideo.mp4"

yolo = "yolov3/"

opname = "output2.avi"

cap = cv2.VideoCapture(filename)

time1 = time.time()

while(True):

    ret, frame = cap.read()

    if not ret:

        break

    current_img = frame.copy()

    current_img = imutils.resize(current_img, width=480)

    video = current_img.shape

    frameno += 1

    if(frameno%2 == 0 or frameno == 1):

        Setup(yolo)

        ImageProcess(current_img)

        Frame = processedImg

        cv2.imshow("Image", Frame)

        if create is None:

            fourcc = cv2.VideoWriter_fourcc(*'XVID')

            create = cv2.VideoWriter(opname, fourcc, 30, (Frame.shape[1], Frame.shape[0]), True)

    create.write(Frame)

    if cv2.waitKey(1) & 0xFF == ord('s'):

        break

time2 = time.time()

print("Completed. Total Time Taken: {} minutes".format((time2-time1)/60))

cap.release()

cv2.destroyAllWindows()

Why is Social Distancing Detection helpful?

  1. Convincing Workers

Since 41% of workers won't return to their desks until they feel comfortable, installing social distancing detection is an excellent approach to reassure them that the situation has been rectified. People without fevers can still be contagious; hence this solution is preferable to thermal imaging cameras.

  1. Space Utilization

Using the detection program, you can find out which places in the workplace are the most popular. As a result, you'll have all the information you need to implement the best precautions.

  1. The Practice of Keeping Tabs and Taking Measures

The software can also be connected to security video systems outside the workplace, such as in a factory where workers are frequently close to one another. To be able to keep an eye on the office atmosphere and single out those whose personal space is too close to others.

  1. Tracking the Queues

Queue monitoring is a valuable addition to security cameras for businesses in retail, healthcare, and other sectors, where waiting in line is unnecessary. As a result, the cameras will be able to monitor and recognize whether or not people are following the social distance requirements. The system can be configured to function with automatic barricades and digital billboards to provide real-time alerts and health and security information.

Consequences of Isolation

The adverse effects of social isolation include the following:

  • Its efficacy decreases when mosquitoes, infected food or water, or other vectors are predominantly responsible for spreading disease.

  • If a person isn't used to being in a social setting, they may become lonely and depressed.

  • Productivity drops, and other benefits of interacting with other people are lost.

Conclusion

This tutorial showed us how to build a social distance detection system. This technology makes use of AI and deep learning to analyze visual data. Incorporating computer vision allows for accurate distance calculations between people. A red box will appear around any group that violates the minimum acceptable threshold value. The system's designers used previously shot footage of a busy roadway to build their algorithm. The system can determine an approximation of the distance between individuals. In social interactions, there are two types of space between people: the "Safe" and "Unsafe" distances. In addition, it shows labels according to item detection and classification. The classifier may be utilized to create real-time applications and put into practice live video streams. During pandemics, this technology can be combined with CCTV to keep an eye on the public. Since it is practical to conduct such screening of the mass population, they are routinely implemented in high-traffic areas such as airports, bus terminals, markets, streets, shopping mall entrances, campuses, and even workplaces and restaurants. Keeping an eye on the distance between two people allows us to ensure sufficient space is maintained between them.

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.

    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.

    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.

          Interactive Voice Response System With Raspberry Pi 4 & SIM800L

          A low-literate audience can nevertheless have their voices heard and their questions answered by using an IVR system, as has been proven time and time again. However, achieving such aims in a development setting calls for a cheap system that welcomes input from various parties. RASP-IVR is an inexpensive IVR system that operates on a PI 4 and a local Global System for Mobile Communications modem. RASP-IVR was designed as an open-source, community-driven solution. It's unusual to find a customer-focused company that still uses human operators rather than an interactive voice response system. Credit card companies typically have IVR systems that can be used to make payments or file fraud reports. Airlines use elaborate IVR systems to schedule flights and check their current status. To facilitate medication refills, pharmacies implement interactive voice response systems. Furthermore, IVRs are widely used for forwarding calls to other extensions and providing directory assistance.

          Enterprises of all sizes have adopted IVR technology due to its cost savings over using actual, flesh-and-blood staff. The number of callers who desire to speak with a human indicates an IVR system's success. As the percentage drops, the system becomes more efficient. Of course, some IVRs will never let you bypass the system and talk to a human being. However, that's frowned upon even by IVR advocates. As most people know, Raspberry Pi is a development board that packs a fair amount of processing power into a little package (about the size of a palm). When coupled with python's adaptability, this might lead to the creation of a wide variety of useful but diminutive devices. I recently had to construct an interactive voice response system using a Raspberry Pi, which essentially entails dialing phone numbers, sending messages, and receiving DTMF inputs from the recipient when they pick up the phone.

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

          Components

          • Pi 4

          • SIM800L GSM Module

          • 2G SIM Card (Airtel)

          • Aux Cable

          • LM2596 Buck Converter Module

          • USB to TTL Converter

          • 12V 2A Adapter

          • Perf Board

          • Berg Sticks

          • Connecting wires

          • Soldering Kit

          Interactive voice response and its Operation

          Computer and phone systems can be integrated into various ways, and IVR systems are one such way (CTI). Key tones are the most common way a phone can exchange data with a computer. Dual-tone multi-frequency frequency is what you get. A telephone's number pad emits a low and high-frequency tone. A "1" can be generated in a 697-Hz tone or a 1209-Hz tone, both of which are recognized by the PSTN as the numeral 1. For a computer to interpret the DTMF frequency produced by a phone, specialized hardware known as a telephony circuit or telephony board is required. Using a telephony board to connect a computer to a phone line and some low-cost IVR software, it is possible to create a rudimentary IVR system. The IVR program lets you record messages and menu items that callers can navigate using their phone keypads.

          Speech-recognition software is a part of more sophisticated IVR systems, enabling callers to interact with computers via voice commands. The technology behind speech recognition is now advanced enough to comprehend things like full names and long series of digits. Text-to-speech software can be used on the receiving end to fully automate a firm's outgoing telephone calls. To better serve customers, computers may now generate personalized text to answer their inquiries, such as financial statements or flight times, and have an automatic voice read to them. Voice extendable mark-up language is a popular foundation for many cutting-edge interactive voice response systems today.

          RASP-IVR: A Comprehensive Approach to Interactive Voice Response

          The "RASP-IVR" moniker comes from the fact that it was created on the inexpensive Linux-based single-board computer known as a raspberry pi. The operating system is built on RASPBX, with several additions and modifications to improve compatibility for interactive voice response (IVR) use. Model 4 Raspberry Pi and GSM mobile phone modem make up the system. An Asterisk server is connected to the GSM modem via an interface. FreePBX is a web-based interface for managing an Asterisk server, allowing users to set up and modify IVR menus and VoIP settings. Using open-source libraries, we've written scripts to bring RASPBX's functionality for Voice over IP (VoIP), short messaging service, and localized SIP transfers to a broader.

          Depending on the situation, the Asterisk domain server can route the incoming GSM call over a local or worldwide VoIP network. The VoIP communications can be directed to different extensions based on the client's dial input. They can be answered from any desktop or mobile device with a domestic SIP account and a SIP client like Zoiper. Furthermore, the VoIP conversation can be routed to third-party platforms like Twillio to use their cloud-based solutions like speech-to-text engines or cloud-based storage. In contrast, RASP-IVR requires no external resources, making it ideal for collaborative innovation or limited rollouts.

          Why use GSM Module and not just the API to make phone calls?

          The cost of using an API to make phone calls from a Raspberry Pi can add up quickly. You can use python and Raspberry Pi to make inexpensive phone calls using several different service providers, including Twilio. These solutions are fantastic; however, the price has two significant drawbacks. Almost wherever you go, you'll be charged by the minute, which goes for both outgoing and incoming communications. You might not think this is significant, but if you make more than a hundred calls daily, you'll soon realize how much it costs. The second issue is buying and managing a different cellphone number from which to make these calls. You cannot use an existing number because these are all made up, and depending on your area, you may have to pay more to get a number that works in your nation.

          How can I make inexpensive phone calls with a Raspberry Pi 4?

          After researching the rates of several API-based telephone conversation services, it became evident that the cheapest option is to use a Gsm technology like SIM800L with Pi to place calls through a network service provider like Airtel. To that aim, we'll connect a SIM800L module to a Raspberry Pi so we can send text messages and make phone calls automatically.

          Which GSM module should we use with my Raspberry Pi 4 to do IVR calls?

          As 5G and the IoT become increasingly popular, numerous innovative new GSM modules have been released that are compatible with 5G networks while using less energy. But I had the bright notion of employing a ubiquitous and inexpensive commodity to purchase at any nearby hobby store. So, we put the popular SIM800L and the Ai-thinking A9 through their paces. Even when just powered by my laptop's USB port, the artificial intelligent-thinker A9 Gsm modem proved completely reliable and responsive right from the get-go. However, the primary issue was that the in-line voice input interface did not operate very well, and the artificial intelligent Thinker A9 Gsm modem did not enable DTMF recognition. So, I switched to the SIM800L Global System for Mobile communications Modem, a power-hungry beast that, if fed enough juice, proved ideal for this task. There is no need for expensive external DTMF hardware because it has both in-line audio for playing automated voice and built-in DTMF detection. 

          What kind of SIM card works with the SIM800L?

          The SIM800L is only compatible with 2G networks, not 3G or 4G. Only Airtel and BSNL provide 2G services in this area. Therefore, get an Airtel SIM card or use one we already have. After purchasing a new Airtel subscriber identity module, card, I activated it on my cell phone and began using it with my SIM800L. 

          A SIM800L-Based interactive voice response System's Typical Circuit Diagram

          Complete schematics for a Raspberry Pi-based telephone and message system are provided below. It's clear how simple it is to draw connections between ideas.

          Powering the SIM800L Module

          The method by which the SIM800L module is supplied with electricity is crucial here. Within a voltage range of 3.7V to 4.2V, the SIM800L chip functioned. The optimum working voltage is close to 4V. For the SIM800L module, we needed to reduce the adapter's 12V 2A output to 4V; thus, we utilized an LM2596 Buck converter. Thicker, shorter wires are preferable when linking the buck component to the SIM800L so that the module can easily handle the high current. When powered, if the element detects improper power connections, it will reset and send invalid data through the serial port. You'll need a 12V 2A adapter to power the SIM800L module, and you should use bulky wires just to carry a lot of current without causing too much resistance. Connecting a fully loaded Lithium battery across the SIM800L module's Vcc and Ground pins should resolve any power difficulties.

          SIM800L-to-Raspberry Pi Serial Data Transfer

          Those unfamiliar with the jargon of electronics engineering know that "AT Commands" are what we use to talk to the SIM800L module. Calling, texting, and keypress detection are just a few of the many functions that may be accomplished with AT commands. This tutorial will use Py from RPi to transmit these AT instructions to the Global System for Mobile Communications SIM800L module. Connecting the SIM800L module's Rx and Tx pins to the Raspberry Pi's USB port required a universal serial bus to TTL converter.

          Audio transmission from the Pi 4 to the SIM800L component

          Through its MIC+ and microphone- pins, the SIM800L component supports mic input. Any audio information sent to these pins after the call has been placed will play on the call recipient's phone. In our scenario, we have to play recorded audio from the Rpi; however, these go pins are primarily designed to connect a microphone. To hear it on the GSM component, we must convert our audio output from the RPi through the 3.5mm port, known as line-out audio, to mic-level audio. You might construct a line-to-mic converter circuit to complete this task professionally. Still, I connected the two devices and set the volume level on the Raspberry Pi to barely two decibels. I had no trouble getting it to function this way.

          I assembled the entire circuit on the perf board, ensuring the voltage connectors got enough lead to offer low-resistance contact. This is how my board appears after soldering. Since the LM2596 is an adjustable buck converter, ensure you use the onboard trim pot to set the voltage output to 4 Volts before using it. Anything above 4.2 volts can permanently damage the SIM800L component.

          Simply turn on the circuit and attach the Cell phone card when you get here. Once more, confirm that the SIM card is inserted correctly and that the antenna is securely fastened. If all is done correctly, you should see the SIM800L board's inbuilt led flashing once every three seconds. As a result, the SIM800L module may create a network using our SIM card. This guarantees the appropriate Operation of our powering circuit. Now that the board is connected, we can build our Python code without an RPi.

          Making Calls and Sending SMS on a Pi 4 with a SIM800L Component

          You may find the entire Python script for the RPi interactive voice response system at the end of this tutorial. Due to the size of the code, it is not practical to detail every step. It is incorporated with comments and procedures to do reading and comprehending the code easier. Importing the necessary header files allows us to launch the program. We used the serial module to enable the serial connection between the Raspberry Pi and SIM800L components. The pygame software is employed to play audio, in this case, audio files. We also have the time component to cause delays, so that's something. You don't need to install anything new because the Buster OS comes pre-installed with all three packages.

          import serial #for serial communication with GSM SIM800L

          import time

          import pygame #to play music

          def SIM800 (Command)

          Using this method, an AT command can be sent from a PI computer to a SIM800L device and then received in return. All AT commands transmitted to SIM800L must be written in ASCII and conclude with the character "rn." Before sending them to SIM800L, this method appends the character "rn" to all our AT instructions and transforms them into the ASCII character set. Once the response has been read, it decodes the ASCII data so we may utilize them in our code.

          def SIM800(command):

              AT_command = command + "\r\n"

              ser.write(str(AT_command).encode('ascii'))

              time.sleep(1)

              if ser.inWaiting() > 0:

                  echo = ser.readline() #waste the echo

                  response_byte = ser.readline()

                  response_str = response_byte.decode('ascii')

                  return (response_str)

              else:

                  return ("ERROR")

          def wait_for_SIM800()

          This function is quite similar to the one before, except instead of sending a value to the SIM800 component, it just awaits a response from the SIM800L module. As a result, it returns the answer when it receives one.

          def wait_for_SIM800():

              echo = ser.readline()  # waste the echo

              response_byte = ser.readline()

              response_str = response_byte.decode('ascii')

              return (response_str)

          def Init_GSM()

          The GSM modem is ready for interactive voice response operations after being initialized. Before sending particular AT instructions to the Gsm modem to activate the message and DTMF receiver modes, it sends an "AT" to check for the module and waits for an "OK" response. In addition, it turns off all alerts so that we won't be distracted throughout a call by texting notifications.

          def Init_GSM():

              if "OK" in SIM800("AT"):

                  if ("OK" in (SIM800("AT+CLCC=1"))) and ("OK" in (SIM800("AT+DDET=1"))) and ("OK" in (SIM800("AT+CNMI =0,0,0,0,0"))) and ("OK" in (SIM800("AT+CMGF=1"))) and ("OK" in (SIM800("AT+CSMP=17,167,0,0"))):  # enble DTMF / disable notifications

                      print("SIM800 Module -> Active and Ready")

              else:

                  print("------->ERROR -> SIM800 Module not found")

          def play_wav (file_name)

          After answering the call, the following method is employed to play the audio files. We have recorded audio files like "cancel.wav," "confirm.wav," and "intro.wav" stored. Following the user's keyboard answer, we must play every one of these files. We can use the play audio function to play any audio file of our choosing. Assume that your Python script is stored within the same folder as these audio files.

          def play_wav(file_name):

              pygame.mixer.init(8000)

              pygame.mixer.music.load(file_name)

              pygame.mixer.music.play()

              #while pygame.mixer.music.get_busy() == True:

                  #continue

          def Call_response_for (phone_number)

          The software's most crucial feature is this one. It obtains the mobile number that has to be called and offers the callback for that session. Any response, such as NOT REACHABLE, CALL REJECTED, CONFIRMED, CANCELED, etc., can be given in return. The function calls a specified phone number using AT instructions and then plays recorded audio. The system then listens for the caller's DTMF reply and, depending on that reaction, plays the relevant recorded voice before informing us of the caller's choice. The method will also respond with that information if the caller declines the call or cannot be reached.

          def Call_response_for (phone_number):

              AT_call = "ATD" + phone_number + ";"

              response = "NONE"

              time.sleep(1)

              ser.flushInput() #clear serial data in buffer if any

              if ("OK" in (SIM800(AT_call))) and (",2," in (wait_for_SIM800())) and (",3," in (wait_for_SIM800())):

                  print("RINGING...->", phone_number)

                  call_status = wait_for_SIM800()

                  if "1,0,0,0,0" in call_status:

                      print("**ANSWERED**")

                      ser.flushInput()

                      play_wav("intro.wav")

                      time.sleep(0.5)

                      dtmf_response = "start_over"

                      while dtmf_response == "start_over":

                          play_wav("press_request.wav")

                          time.sleep(1)

                          dtmf_response = wait_for_SIM800()

                          if "+DTMF: 1" in dtmf_response:

                              play_wav("confirmed.wav")

                              response = "CONFIRMED"

                              hang = SIM800("ATH")

                              break

                          if "+DTMF: 2" in dtmf_response:

                              play_wav("canceled.wav")

                              response = "CANCELED"

                              hang = SIM800("ATH")

                              break

                          if "+DTMF: 9" in dtmf_response:

                              play_wav("callback_response.wav")

                              response = "REQ_CALLBACK"

                              hang = SIM800("ATH")

                              break

                          if "+DTMF: 0" in dtmf_response:

                              dtmf_response = "start_over"

                              continue

                          if "+DTMF: " in dtmf_response:

                              play_wav("invalid_input.wav")

                              dtmf_response = "start_over"

                              continue

                          else:

                              response = "REJECTED_AFTER_ANSWERING"

                              break

                  else:

                      #print("REJECTED")

                      response = "CALL_REJECTED"

                      hang = SIM800("ATH")

                      time.sleep(1)

                      #ser.flushInput()

              else:

                  #print("NOT_REACHABLE")

                  response = "NOT_REACHABLE"

                  hang = SIM800("ATH")

                  time.sleep(1)

                  #ser.flushInput()

              ser.flushInput()

              return (response)

          def send_message (message, recipient) 

          The send message method in this program enables us to send messages in addition to making calls and receiving responses. The message is sent after it receives both the text and the participant's mobile number.

          def send_message(message, recipient):

              ser.write(b'AT+CMGS="' + recipient.encode() + b'"\r')

              time.sleep(0.5)

              ser.write(message.encode() + b"\r")

              time.sleep(0.5)

              ser.write(bytes([26]))

              time.sleep(0.5)

              print ("Message sent to customer")

              time.sleep(2)

              ser.flushInput()  # clear serial data in buffer if any

          def incoming_call()

          The very last method I created for this project allows you to figure out who is calling by their phone number. Some people might attempt to call back to this line because this SIM card will make calls to new persons. If so, you can use this function to see which line is making the call, send them a message, or create a follow-up call if necessary.

          def incoming_call():

              while ser.in_waiting: #if I have something in the serial monitor

                  print ("%%Wait got something in the buffer")

                  ser.flushInput()

                  response = SIM800("ATH") #cut the incoming call

                  if "+CLCC" in response:

                      cus_phone = response[21:31]

                      print("%%Incoming Phone call detect from ->", cus_phone)

                      return (cus_phone)

                  else:

                      print("Nope its something else")

                      return "0"

              return "0"

          It's time to create the main program, in which we will employ all of these functions to accomplish something nice now that all of them have been defined. The customer id and phone number are now being hard-coded for demonstration purposes, but you can obtain them using a Shopify API request or retrieve them from a spreadsheet as needed. For testing purposes, we use the customer's identity, "AISHA," and phone number, "9877XXXXXX."

          cus_name = "Aisha"

          cus_phone = "968837XXXX"

          We will begin a serial conversation with a 15-second delay at 9600 baud speeds within the main endless while loop block. Considering that various SIM800L components may operate at a different baud rate, ensure that you enter the correct COM folder and baud rate in this field.

          ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=15)  # timeout affects call duration and waiting for response currently 30sec

          print("Established communication with", ser.name)

          After making the call and getting the necessary reply from the consumer, we will send the recipient a text based on their response. For instance, if the answer is validated, we can send a message about it. Likewise, we can alter the message if the client provides a different reply.

          response = Call_response_for(cus_phone) #place a call and get response from customer

          print ("Response from customer => ", response)

          if response == "CONFIRMED":

              text_message = "Hi " + cus_name + ". Your booking has been confirmed.Thank you. -Circuitdigest"

              send_message(text_message, cus_phone)

          if response == "CANCELED":  # if the response was to cancel

              text_message = "Hi " + cus_name +. "Sorry that you have decided to cancel your booking. If you canceled by mistake, kindly contact us by phone. -Circuitdigest"

              send_message(text_message, cus_phone)

          if ((response == "CALL_REJECTED") or (response == "REJECTED_AFTER_ANSWERING")):  # if the response was rejected

              text_message = "Hi " + cus_name + ". We from circuitdigest.com have been trying to reach you, to confirm your 

              booking. You will receive another call within a few minutes, and we kindly request you answer it. Thank you"

              send_message(text_message, cus_phone)

          Testing our interactive voice response system on the Pi

          Just double-check the connectors and turn on the GSM component board and RPi. Make that the appropriate COM port is listed in the code before running the application; in my instance, it was "/dev/ttyUSB0." After that, check that the sound is set to atrioventricular ( av ) node jack by right-clicking on the loudspeaker icon and that the audio level is low.

          Simply alter the contact number and client name in the following step to your liking, or modify the program to retrieve the information from an excel spreadsheet or cloud Application programming interface, and our automated interactive voice response is ready to go.

          The application will dial the specified number and listen for DTMF responses. Additionally, it will play relevant sound clips and transmit a text message dependent on the recipient's response. Below are a few sample messages that I obtained on my cellphone.

          The audio tracks and texts can easily be changed to meet your application's needs. I hope the assignment was enjoyable for you and that you learned something.

          RASP-IVR application

          1. Call routing within a company is among the most popular uses of an interactive voice response system. Previously, you would employ a switchboard controller or receptionist to answer all callers and direct callers to the appropriate line. When answering customer calls, an interactive voice response system is beneficial. A caller may be given a menu of choices and inquiries about the system's type of call. If possible, the system will respond to the more typical inquiries while referring the less common questions to qualified experts.

          2. Interactive voice response systems are excellent for getting detailed, current info from databases—for instance, movie times. On a significant database, the weekly movie lists are updated. The cinema theater's website can also be filled with information from these databases. When making a call to the cinema, the caller can use the keypad or voice instructions to search the database for movie timings. The same technology can be used to check account balances, evaluate the latest credit card payments, check flight times, refill medicines at a pharmacy, plan auto maintenance, and register for university classes. The list is endless.

          3. Interactive voice response systems are helpful for sales as well. A sales department can create an interactive voice response order form, enabling callers to complete it on their phone's keyboard. When the form is finished, the computer can send a copy to a sales team representative through fax or email. The sales department could also use the IVR as a virtual flyer that highlights the characteristics of a good or service and offers customers the chance to speak with a live agent at any time.

          4. Marketing teams and election pollsters can use the interactive voice response systems' outgoing call functions. A political campaign may send a voicemail message with a phone-in survey for voters to complete. An advertiser may determine whether a buyer is interested in his goods or services. They might press a key to speak with a sales representative if interested in the advertiser's computerized pitch.

          5. Electronic alert systems may also be combined with interactive voice response systems. Let's assume that your company has worldwide workers working from home. Worker contact details, such as home phone numbers, mobile phone numbers, fax numbers, pager numbers, email addresses, etc., can be coded into the interactive voice response system. The IVR prog will use every form of contact until a connection is established if a call has to be directed to that worker.

          6. Transcribing health records is an intriguing application of interactive voice response technology. Currently, doctors record their patient notes and submit the audio to a service that performs medical transcription. However, a doctor may contact the interactive voice response system, record his notes, and have a filed transcript emailed to their office thanks to advanced speech recognition software.

          7. The creators have been collaborating with a few Rwandan health industry partners. The developers want to create solutions that will expand the coverage and reach of the partners' already-existing face-to-face operations. Interactive voice response can extend services to clients who cannot travel to existing facilities. Interestingly, one non-partner frequently visits remote communities and considers the interactive voice response as a tool for drawing people to these outreach efforts. By providing automated processes that operate outside of regular business hours or by gathering and analyzing customer data, the IVR can lessen the employees' workload. One partner will use this function to computerize donor-sponsor reports. In the opinion of one of the partners, the interactive voice response is a small step towards a more significant switch from hard copies to soft copies. Before conversing with a counselor, the web service might pull up the patient's EHR using information gathered by the IVR synchronized with the hard copy to soft copy system and the interactive voice response. After the call, a text message is sent to the customer, and another is sent to the dispatch center that is most convenient for the client.

          Advantages of RASP-IVR

          Using its speech and texting platforms, the RASP-interactive voice response system opens the door to creating unique apps that can assist with contextually relevant difficulties. Features including automated call rerouting, user-selected content, caller audio content recording, text message-based engagement, data collecting, and tailored resources that can be accessed on caller ID are all made possible by the RASP-Interactive voice response system.

          We acknowledge, however, that interactive voice response-based solutions, like all technology, must be developed to enhance current human development efforts. The following are IVR-based systems' benefits, although certain limitations are covered below.

          • A voice-only system is more appealing to people with limited literacy

           than texting or internet-based apps. 

          • To use an IVR system, users just dial a number on their readily available cell phone, as they would with any other service.

          • I am using a mobile phone to get entry to discreet and stigma-free services like psychological counseling, and family planning might be advantageous.

          • Interactive voice response systems can reconnect dropped calls thanks to caller ID and track many simultaneous activities from the same telephone.

          • Finally, the speech signal is informative, providing estimations of the speaker's age, body weight, sexuality, anxiety, and other health indicators.

           

          Interactive voice response development Obstacles

          Some drawbacks exist, though, which must be weighed against the advantages. Since the interactive voice response system is language-dependent, the prompts must be recorded in users' native tongues. Interactive voice response ern systems are constrained by emerging communities' cultural and social conventions, even though the telephone interface is familiar.

          Users more accustomed to interpersonal communication may resist automated data inquiries and exchanges. To that end, one of the partners believes that in-person demonstrations of the IVR system to clients will provide the most positive results.

          Another barrier we discovered for people with few resources was the lack of phone access. Due to fluctuating electricity prices and supply, charging a phone is not always possible. In many cases, people will use various telephones, or multiple people will use the same phone. It's possible that follow-up calls and texts won't be received.

          In addition, having a shared phone line can raise questions and suspicions about who is calling. Finally, there are several ways in which users' privacy could be compromised by IVR technologies, from the storage and transmission of data to the reporting of such data to the difficulty of preventing one user from accessing the information of another.

          The existing system demands developer-side programming expertise that a CBO might not have access to. The dongle's inability to talk to the Raspberry Pi occasionally resulted from a hardware malfunction. The network failed in some cases. When making a mobile-to-mobile call, one internet provider did not forward the touch-tone signals.

          Unfortunately, the system can only handle a single call at a time, making it unsuitable for deployments with a high rate of incoming calls. Our co-operators who expect low call volumes can benefit from the RASP-IVR. A shift to a more scalable approach would be justifiable if volume increased.

          Conclusion

          Through this tutorial, we have gained a thorough understanding of IVRs and their inner workings. We proceeded to assemble our own Raspberry Pi 4 IVR with a handful of components and some test audio samples. We have investigated the mechanism behind this system and spoken about some of the primary uses for the IVR system. We also had a look at some of the advantages and disadvantages of using it. The following tutorial will teach you how to connect a USB barcode scanner to a Raspberry Pi so that you can read 2D barcodes.

          How to Build a Raspberry Pi FM Transmitter

          Throughout our lives, we've relied on Radio and tv stations to keep us engaged. While we're on the subject of contradictions, it's also fair to say that these Stations can become tedious at times due to the RJ rambling on about nothing or annoying advertisements, and this may have left you wondering why you can't own a Radio station to broadcast your data over short distances.

          Almost any electronics technician uses coils and other hardware to make an FM transmitter, although the tuning process is time-consuming and difficult. Setting up your FM station and going live in your neighborhood shouldn't take more than 30 minutes using an RPi. If you use the right antenna, you must be able to transmit to your school or community within 50 meters. Wow, that's interesting! So, let's get started right now.

          Caution: This project is an education project and should not be abused in any way that might harm or inconvenience anyone. Interfering with neighboring FM frequencies is illegal, so please exercise caution when using this feature. In the event of any mishaps, we take no responsibility for them.

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

          Components

          • Raspberry Pi

          • Internet connection

          • Microphone

          • An enthusiastic RJ

          Pre-requisites

          Your RPi should already be running an os and be able to establish a network connection. If you haven't done so already, go through the instructions on how to use a raspberry pi.

          A virtual server such as VNC, or a putty terminal window, is assumed to be accessible to you at all times. For the sake of this tutorial, we will run the program on RPi using the putty terminal session.

          Frequency Modulation: What is it?

          A method or procedure known as FM involves changing the carrier signal frequencies to match the frequencies of the modulated signal to encode information on a specific signal. Since data must be conveyed after being transformed into an electrical signal, a modulation signal is simply that.

          A carrier's signal is transformed by an original signal in the modulation technique, which uses a methodology similar to amplitude modulation. On the other hand, FM maintains or maintains a steady signal loudness.

          Why is FM necessary?

          Fm is primarily used to decrease noise as well as the size of antennae, respectively. We know that a bigger antenna is required to send reduced frequency signals, whereas a smaller one is necessary to broadcast high-frequency signals.

          Therefore, the sound signals are transformed into high-frequency radio waves and broadcast using the FM technique. Once more, the demodulation circuit on the receiver's side converts the high-frequency radio transmission frequency into the original understandable audio signal.

          There is little interference since different signals are transmitted over a specific channel using separate wavelengths. So many folks can converse simultaneously and unhindered in a large metropolis.

          FM transmission using coils

          The construction of a long-range FM transmitter has long been on my bucket list of cool things. I've been so intrigued by some of the transmitter's uses, particularly since I was a kid, and spent much of my time fantasizing about how awesome it would be to have a few of the technology and technologies used in espionage movies. So lately, while reviewing one of my residence automation projects by using RPi and the motion package library, I felt it would be cool to add audio to the deliverable and stream live, so in addition to the multimedia feedback provided by the RPi, I could also get sound feedback out from area under monitoring. Even while this FM transmitter would not let me hear distantly (a range exceeding 10 kilometers), it will at least enable me to maintain an "ear" on events while I am about the property; then, after building it, I would have accomplished a few of the objectives that the younger me had set out to attain. It took me a few days ago, but I eventually got the motivation to make one, and I'll show you how to do it in today's post.

          To avoid violation of policies of some countries, this experiment is being conducted solely for educational and scientific purposes. Keep the FM transmission at a low range and make sure it is built in compliance with applicable laws of one’s nation and therefore does not induce a disruption to others. This is essential. For any mishaps, I take no responsibility.

          How do FM transmitters work

          Using the concepts of the modulated signal, an FM transmitter can transmit the audio it receives from its input. Most FM transmitters are constructed in the manner depicted in the diagram below.

          An amplification is frequently included in the transmitters because the transmission power of audio input is relatively low. This is done by utilizing an oscillator component to produce the carrier signal, which is then combined with an audio stream to generate a modulated signal that can be transmitted. When it comes to communicating, the low-impedance modulation signal is fed via a power amplifier to get to the antenna.

          FM broadcast circuit

          The electrical component should be connected as illustrated in the following FM transmitter diagram.

          In this photo, you can see the prototype version of the FM radio transmitter.

          The first transistors amplify the mic's output signals to a level suitable for transmission because the mic's output waveform is typically modest. In addition to amplification, the transmitter must also modulate. After that, the boosted audio signal is combined with the desired transmission carrier frequency to create a final signal. Because there is no visible output to identify the precise frequency where the transmitters are working, you may need to modify the FM transceiver radio well within the frequency range stated above to get the transmission frequency. This carrier signal can be differed using a 20pF capacitor attached to the inductor. The traditional spectral range of this specific design would be between 88MegaHeartz and 108MegaHertz. Once the carrier signal has modulated the audio signal, it is sent to the antenna, where it is received.

          The resistors and capacitors used aren't set in stone, so you can experiment with them to get the best performance out of the transmitters.

          Several other uses for this design aren't mentioned above, such as baby monitors or school address systems. Before constructing any of those practical items, please remember to check your local laws.

          How Pi 4 works as a transmitter 

          How can RPi, a board designed to serve as a development platform for microprocessors, do all of this? What if I don't need extra hardware to use the board as an FM station?

          To prevent interference problems, each CPU will have a synchronized digital device. A signal known as a Spread-spectrum system clock, or SSCS is responsible for this Electromagnetic interference suppression. This frequency ranges from 1 MegaHeartz to 250 MegaHeartz, which fortunately fits well within the FM spectrum. We can make the Pi become an FM broadcaster by developing some code that uses the spread-spectrum clock frequency to modulate the frequencies. The Rpi Pi's GPIO pin 4 is where the frequency modulation will be sent. To use this pin as an antenna, we need a piece of standard wire attached to it no longer than 20 cm in length.

          Getting the pi 4 readies for programming

          Otherwise, read on for instructions on accessing your pi through the Command window if you haven't already done so. Boot Raspberry Pi with an HDMI connection to a display and an input device once you've installed a new operating system.

          Link your Raspberry to the network by searching for a network option on the Raspberry desktop. Then go to the raspberry menu, click raspberry settings, and activate the SSH connection afterward. On your Windows or MAC computer, reconnect your computer to the same network as your Raspberry Pi so that both devices may communicate with each other on the local area network. You're ready to begin now that you've had Putty installed and running. Enter the Raspberry Pi's Internet protocol address and press enter. If you don't know your PI's Internet address, go to the admin side of your router and see if it's 192.168.43.XXX or something similar. An open command prompt will appear and ask for your login and passcode if all is done correctly. The default login and passcode are pi and Raspberry, respectively. Press Enter to see the next screen after entering it.

          Convert Pi 4 into an FM station

          GitHub provides the code needed to turn the Raspberry into a radio station. This page can be cloned directly into Raspberry; the application can be compiled and launched if you understand how to do so. Just follow the instructions below, and you'll be transmitting your audio files in no time.

          Step 1:

          Set up a new directory for our software files and put them there. Create a new guide by typing 'mkdir RPI FM' inside the command prompt, and then enter the folder using the word 'cd.'

          mkdir PI_FM

          cd PI_FM

          Step 2: 

          We must now copy the application from GitHub and place it in the folder we just made. Since we've previously moved inside the folder, we can run the following command below to complete the task.

          sudo git clone https://github.com/markondej/fm_transmitter

          Step 3:

          We'll need a C compiler and other tools to run the C program we just acquired. GCC and G++ are the tools for this code, and the software for compiling them is termed make. To obtain compilers, enter the code shown below. Once the file is downloaded, your display will appear like the one below.

          sudo apt-get install GCC g++ make

          Step 4:

          Compiling the code is now a cinch. You can do this by going into the folder using the change directory 'cd' FM transmitter and then compiling the script with root user 'sudo make .'The screen below should appear once your code has been successfully compiled.

          cd fm_transmitter

          sudo make

          Step 5:

          Launching the system is the last step. The intensity for which we would like to transmit, and the identity of the audio recording we would like to play must be specified when the program is launched. Star wars.wav is the default sound file that will be retrieved together with the code. We'll play the Movie Theme song at a 100megahertz frequency for testing purposes. The launch line's syntactic structure is:

          sudo ./fm_transmitter [-f frequency] [-r] filename

          The channel will be 100 MegaHeartz long because we need to play the movie file at that frequency.

          sudo ./fm_transmitter -f 100  -r star_wars.wav

          Test the Pi 4 FM transmitter

          After you have started the application and you see the playback message as seen above, we may link an antenna to a Gpio 4 of Raspberry, I use a standard connecting wire, and it works perfectly for me.

          Take a Radio, then set it to 100MegaHeartz channel, and you'll be able to listen to the movie music being aired. After making sure it works, you may switch out the movie theme with any other music or audio recording you choose and broadcast it with the same instructions as in step 5.

          Transmitting live sound

          While playing pre-recorded audio clips is entertaining, using this Pi 4 FM broadcast live audio would be much more enticing. With the help of the same tool, this is also possible. Just plug a mic into the Raspberry Pi's USB connection and modify the startup command-line interface. For additional information on this, please visit the GitHub homepage. Use the comment section of the forums if you run into any issues getting this to function.

          Applications of FM

          When it comes to frequency modulation uses, radio transmission dominates the list. Due to its higher signal-to-noise ratios, it provides a significant advantage in a radio broadcast. That is, there is little radio wave interference as a result. This is the fundamental justification for why so most radio stations choose to transmit music via FM.

          Furthermore, many of its applications can be found in telematics, geophysical prospecting, EEG, various radio technologies, music creation, and devices used for broadcasting video. Fm offers a significant benefit over all other modulations in a radio broadcast. It will resist radio wave disruptions far better than an equally powerful modulation amplitude (AM) signal because it has a higher signal-to-noise ratio. The majority of music is aired through FM radio for this important reason.

          • Radio transmission frequently uses pulse modulation technology. Each radio broadcast station has its frequency range, and all broadcaster station signals are sent over the same transmission system. We can adjust the Radio's tuning to link it to a specific radio channel.

          • Our pc connections also employ pulse modulation technology.

          • The pulse modulation method is employed in magnetic storage tape recording systems.

          • Radio Detecting And Range (RADAR) systems employ the pulse modulation approach.

          • Multimedia content communications, including voice/video broadcasts, also use pulse modulation technology. Most of the time, the sound is delivered over FM, and occasionally, the film is as well.

          • The modulated signal generates an electrical impulse for usage in electronic instruments.

          • The monitoring system also makes use of FM technology.

          • Audio is synthesized by using the FM technology in pc sound adapters.

          • Military communication systems like Walkie-Talkies employ pulse modulation technology.

          • Additionally, Bluetooth and Zigbee communications technology utilize the FM method.

          • The Broadcasting method is also employed in ambulance systems.

          • The satellite radio technology uses FM technology.

          • Due to its low electronic noise, this FM method is employed in two-way radio transmission.

          Benefits of FM

          • Low noise distortion

          • A smaller antenna is needed for pulse modulation equipment.

          • The pulse modulation platform's can be built to consume little power. This is a significant benefit of the modulation technique.

          • The pulse modulation process is more efficient because the signal's amplitude is always consistent.

          Drawbacks of FM

          • The frequencies modulation circuit has many intricate parts.

          • A carrier wave is required for the frequency modulation process.

          • Amplification modulation is appropriate for long transmission lines, while FM is not.

          Conclusion

          In this article, we have learned how to create a radio station using a raspberry pi 4 with a few very simple steps. We have broadcasted a Star Wars movie theme through this system, and now you can try many other forms of data to broadcast, including video and live sound using a mic to get more familiar with the system. The next tutorial will teach us how to build a temperature log.

          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