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.

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.

        Stop Motion Movie System using Raspberry Pi 4

        Thank you for joining us for yet another session of this series on Raspberry Pi programming. In the previous tutorial, we built a motion sensor-based security system with an alarm. Additionally, we discovered how to use Twilio to notify the administrator whenever an alarm is triggered. However, in this tutorial, we'll learn how to build a stop motion film system using raspberry pi 4.

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

        What you will make

        With a Raspberry Pi, Py, and a pi-camera module to capture images, you can create a stop-motion animated video. In addition, we'll learn about the various kinds of stop motion systems and their advantages and disadvantages.

        The possibilities are endless when it comes to using LEGO to create animations!

        What will you learn?

        Using your RPi to build a stop motion machine, you'll discover:

        • How to install and utilize the picamera module on the RPi

        • This article explains how to take photos with the Picamera library.

        • RPi GPIO Pushbutton Connection

        • Operate the picamera by pressing the GPIO pushbutton

        • How to use avconv to create a video clip from the command prompt

        Prerequisites

        Hardware

        • Raspberry Pi 4

        • Breadboard

        • Jumper wires

        • Button

        Software

        It is recommended that FFmpeg comes preconfigured on the most recent release of Raspbian. If you don't have it, launch the terminal then type:

        sudo apt-get update

        sudo apt-get upgrade

        sudo apt install FFmpeg

        What is stop-motion?

        Inanimate things are given life through the use of a sequence of still images in the stop-motion cinematography technique. Items inside the frame are shifted slightly between every picture to create the illusion of movement when stitched together.

        You don't need expensive gadgets or Graphics to get started in stop motion. That, in my opinion, is the most intriguing aspect of it.

        If you've ever wanted to learn how to make a stop-motion video, you've come to the right place. 

        Types of stop-motion

        1. Object-Motion

        Product Animation can also be referred to as the frame-by-frame movement of things. You're free to use any items around you to tell stories in this environment.

        1. Claymation

        Changing clay items in each frame is a key part of the claymation process. We've seen a lot of clever and artistic figures on the big screen thanks to wires and clay.

        1. Pixilation Stop Motion

        Making folks move! It is rarely utilized. For an artist to relocate just a little each frame, and the number of images you would need, you'll need a lot of patience and possibly a lot of money, if you're hiring them to do so.

        The degree of freedom and precision with which they can move is also an important consideration. However, if done correctly, this kind can seem cool, but it can also make you feel a little dizzy at times.

        1. Cutout Animation

        One can do so much with cuts in cutout motion because of this. two-dimensional scraps of paper may appear lifeless, yet you may color & slice them to show a depth of detail.

        It's a lot of fun to play about with a cartoon style, but it also gives you a lot more control over the final product because you can add your graphics and details. However, what about the obvious drawback? I find the task of slicing and dicing hundreds of pieces daunting.

        1. Puppet Animation

        Having puppets can be a fun and creative way to tell stories, but they can also be a pain in the neck if you're dealing with a lot of cords. However, this may be a challenge for professional stop motion filmmakers who are not the greatest choice to work with at first. These puppets are of a more traditional design.

        When animators use the term "puppet" to describe their wire-based clay character, they are referring to claymation as a whole. Puppets based on the marionette style are becoming less popular.

        1. Silhouette Stop Motion

        Position the items or performers behind a white sheet and light their shadows on the sheet with a backlight. Simple, low-cost methods exist for creating eye-catching animations of silhouettes.

        How long does it take to make a stop-motion video?

        The duration takes to create a stop-motion video is entirely dependent on the scale and nature of your project. Testing out 15- and 30-second movies should only take an hour or two. Because of the complexity of the scenes and the usage of claymation, stop-motion projects can take days to complete.

        Connect the camera to the raspberry pi.

        You must first attach the camera to the Pi before it can begin rebooting.

        Next to Ethernet, find the camera port. Take a look at the top.

        The blue side of the strip should face the Ethernet port when it is inserted into the connector. Push that tab downward while keeping the ribbon in place.

        Try out the camera

        Use the app menu to bring up a command prompt. The following command should be typed into the terminal:

        libcamera-hello

        If all goes well, you'll see a sneak peek of what's to come. What matters is that it's not upside-down; you can fix it afterward. To close the preview, hit Ctrl + C.

        For storing an image on your computer, run the command below:

        libcamera-jpeg -o test.jpg

        To examine what files are in your root folder, type ls in the command line and you'll see test.jpg among the results.

        Files and folders will be displayed in the taskbar's file manager icon. Preview the image by double-clicking test.jpg.

        There is no default way to make Python Picamera work with Raspbian newest version.

        To make use of the camera module, one must activate the camera's legacy mode.

        The command below must be entered into a command window:

        sudo raspi-config

        When you get to Interface Options, hit 'Enter' on your keyboard to save your changes.

        Ensure that the 'Legacy Camera option is selected then tap the 'Return' key.

        Select Yes using the pointer keys and hit the 'Return' key.

        Repeat the process of pressing 'Return' to verify.

        Click on Finish with your mouse cursor buttons.

        To restart, simply press the 'Return' key.

        Py IDLE can be accessed from the menu bar.

        While in the menu, click Files and then New Window to launch a Python code editor.

        Paste the code below paying attention to the capitalization with care into the newly opened window.

        from picamera import PiCamera

        from time import sleep

        camera = PiCamera()

        camera.start_preview()

        sleep(3)

        camera.capture('/home/pi/Desktop/image.jpg')

        camera.stop_preview()

        Using the File menu, choose Save Animated film.

        Use the F5 key to start your program.

        You should be able to locate image.jpg on your desktop. It's as simple as clicking it twice to bring up a larger version of the image.

        It's possible to fix an upside-down photo by either repositioning your picamera with a camera stand or by telling Python to turn the picture. Adding the following lines will accomplish this.

        camera.rotation = 180

        Once the camera is set to PiCamera(), the following is the result:

        from picamera import PiCamera

        from time import sleep

        camera = PiCamera()

        camera.rotation = 180

        camera.start_preview()

        sleep(3)

        camera.capture('/home/pi/Desktop/image.jpg')

        camera.stop_preview()

        A fresh photo with the proper orientation will be created when the file is re-run. Do not remove these lines of code from your program when making the subsequent modifications.

        Connect a physical button to a raspberry pi

        Hook the Raspberry Pi to the pushbutton as illustrated in the following diagram with a breadboard and jumper wires:

        Pushbutton may be imported at the beginning of the program, attached to pin17, and the sleep line can be changed to use the pushbutton as a trigger in the following way:

        from picamera import PiCamera

        from time import sleep

        from gpiozero import Button

        button = Button(17)

        camera = PiCamera()

        camera.start_preview()

        button.wait_for_press()

        camera.capture('/home/pi/image.jpg')

        camera.stop_preview()

        It's time to get to work!

        Soon as the new preview has begun, press the pushbutton on the Pi to take a picture.

        If you go back to the folder, you will find your image.jpg there now. Double-click to see the image once more.

        Take a picture with Raspberry Pi 4

        For a self-portrait, you'll need to include a delay so that you can get into position before the camera board takes a picture of you. Modifying your code is one way to accomplish this.

        Before taking a picture, put in a line of code that tells the program to take a little snooze.

        camera.start_preview()

        button.wait_for_press()

        sleep(3)

        camera.capture('/home/pi/Desktop/image.jpg')

        camera.stop_preview()

        It's time to get to work.

        Try taking a selfie by pressing the button. Keep the camera steady at all times! It's best if it's already mounted somewhere.

        Inspect the photo in the folder once more if necessary. You can snap a second selfie by running the application again.

        Things to consider for making a stop motion animation

        1. You must have a steady pi-camera!

        This is made easier with the aid of a well-designed setup.  To avoid blurry photos due to camera shaking, you will most likely want to use a tripod or place your camera on a flat surface.

        1. Keep your hands away from the pi-camera

        If you don't press the push button every time, your stop-motion movie will appear the best. To get the camera to snap a picture, use a wireless trigger.

        1. Shoot manually

        Maintain your shutter speed, ISO, aperture, and white balance same for every photo you shoot. There are no "auto" settings here. You have the option of selecting and locking the app's configurations first. As long as your preferences remain consistent throughout all of your photos, you're good to go. The configurations will adapt automatically as you keep moving the items, which may cause flickering from image to image if you leave them on auto.

        1. Make sure you have proper lighting.

        It's ideal to shoot indoors because it's easier to regulate and shields us from the ever-changing light. Remember to keep an eye out for windows if you're getting more involved. Try using a basic lighting setup, where you can easily see your items and the light isn't moving too much. In some cases, some flickering can be visible when you're outside of the frame. Other times the flickering works well with animation, but only if it does so in a way that doesn't disrupt the flow of the project.

        1. Frame Rate

        You do not get extremely technical with this in the beginning, but you'll need to understand how many frames you'll have to shoot to achieve the series you desire. One sec of the film is typically made up of 12 images or frames. If your video is longer than a few secs, you risk seeming like a stop motion animation.

        1. Audio

        When you're filming your muted stop motion movie, you can come up with creative ways to incorporate your sound later. 

        Stop-motion video

        The next step is to experiment with creating a stop motion video using a collection of still photos that you've captured with the picamera. Note that stills must be saved in their folder. Type "mkdir animation" in the command line.

        When the button is pushed, add a loop to your program so that photographs are taken continuously.

        camera.start_preview()

        frame = 1

        while True:

            try:

                button.wait_for_press()

                camera.capture('/home/pi/animation/frame%03d.jpg' % frame)

                frame += 1

            except KeyboardInterrupt:

                camera.stop_preview()

                break

        Since True can last indefinitely, you must be able to gently end it. If you use Ctrl + C to force it to end, the picamera preview will collapse and the loop will be terminated because it is using try-except.

        Files stored as "frame" with a three-digit number preceded by a leading zero (009,005.) are known as "frame" files because of the % 03d format. This makes it simple to arrange them in the proper sequence for the video.

        To capture each following frame, simply push the button a second time once you've finished rearranging the animation's main element.

        To kill the program, use Ctrl + C when all the images have been saved.

        Your image collection can be viewed in the folder by opening the animation directory.

        Create the video

        To initiate the process of creating the movie, go to the terminal.

        Start the movie rendering process by running the following command:

        FFmpeg -r 10 -i animation/frame%03d.jpg -qscale 2 animation.mp4

        Because FFmpeg and Py recognize the percent 03d formatting, the photographs are sent to the movie in the correct sequence.

        Use vlc to see your movie.

        vlc animation.mp4

        The renderer command can be edited to change the refresh rates. Try adjusting -r 10 to a different value.

        Modify the title of the rendered videos to prevent them from being overwritten. Modify animation.h264 to a different file to accomplish this.

        What's the point of making stop motion?

        Corporations benefit greatly from high-quality stop motion films, despite the effort and time it takes to produce them. One of these benefits is that consumers enjoy sharing these movies with friends, and their inspiring content can be associated with a company.  Adding this to a company's marketing strategy can help make its product extra popular and remembered.

        When it comes to spreading awareness and educating the public, stop motion films are widely posted on social media. It's important to come up with an original idea for your stop motion movie before you start looking for experienced animators.

        Stop Motion Movie's Advantages

        In the early days of filmmaking, stop motion was mostly employed to give animated characters the appearance of mobility. The cameras would be constantly started and stopped, and the multiple images would all be put together to tell a gripping story.

        It's not uncommon to see films employ this time-honored method as a tribute to the origins of animations. There's more, though. 

        1. Innovation

        In the recent resurgence of stop motion animations, strange and amazing props and procedures have been used to create these videos. Filmmakers have gone from generating stop motion with a large sheet of drawings, to constructing them with plasticine figures that need to be manually manipulated millimeters at a time, and to more esoteric props such as foodstuffs, domestic objects, and creatures.

        Using this technique, you can animate any object, even one that isn't capable of moving by itself. A stop-motion movie may be made with anything, thus the options are practically limitless.

        1. Animated Tutorials

        A wide range of material genres, from educational films to comedic commercials, is now being explored with stop motion animation.

        When it comes to creating marketing and instructional videos, stop motion animations is a popular choice due to their adaptability. An individual video can be created. 

        Although the film is about five minutes long, viewers are likely to stick with it because of its originality.  The sophisticated tactics employed captivate the audience. Once you start viewing this stop motion video, it's impossible to put it down till the finish.

        1. Improve the perception of your brand

        It's easy to remember simple but innovative animations like these. These movies can assist a company's image and later recall be more positive. Stop motion video can provoke thought and awe in viewers, prompting them to spread the creative message to their social networks and professional contacts.

        It is becoming increasingly common for organizations of all kinds to include stop-motion animations in their advertisements. 

        1. In education 

        Stop-motion films can have a positive impact on both education and business. Employees, customers, and students all benefit from using them to learn difficult concepts and methods more enjoyably. Stop motion filmmaking can liven up any subject matter, and pupils are more likely to retain what they've learned when it's done this way.

        Some subjects can be studied more effectively in this way as well. Using stop motion films, for instance, learners can see the entire course of an experiment involving a slow-occurring reaction in a short amount of time.

        Learners are given a stop motion assignment to work on as a group project in the classroom. Fast stop motion animation production requires a lot of teamwork, which improves interpersonal skills. Some learners would work on the models, while others might work on the backdrops and voiceovers, while yet others might concentrate on filming the scenes and directing the actors.

        1. Engage Customers and Employees

        The usage of stop motion movies can be utilized to explain product uses rapidly, even though the application of the device and the output may take a while. You can speed up the timeline as much as you want in stop motion animations!

        For safety and health demonstrations or original sales demonstrations, stop motion instructional films may also be utilized to effectively express complex concepts. Because of the videos' originality, viewers are more likely to pay attention and retain the content.

        1. Music Video

        Some incredibly creative music videos have lately been created using stop motion animations, which has recently seen a resurgence in popularity.  Even the human body could be a character in this film.

        Stop-motion animations have the potential to be extremely motivating. Sometimes, it's possible to achieve it by presenting things in a novel way, such as by stacking vegetables to appear like moving creatures. The sky's the limit when it comes to what you can dream up.

        1. Reaction-Inducing Video

        When it comes to creating a stop motion movie, it doesn't have to be complicated. If you don't have any of these things in your possession, you'll need to get them before you can begin filming. However, if you want to create a professional-level stop motion film, you'll need to enlist the help of an animation company.

        As a marketing tool, animated videos may be highly effective when they are created by a professional team. 

        1. Create an Intriguing idea

        The story of a motion-capture movie is crucial in attracting the attention of audiences, so it should be carefully planned out before production begins. It should be appropriate for the video's intended audience, brand image, and message. If you need assistance with this, consider working with an animation studio.

        Disadvantages

        But there are several drawbacks to the overall process of stop motion filmmaking, which are difficult to overcome. The time it takes to create even a min of footage is the most remarkable. The time it takes to get this film might range from a few days to many weeks, depending on the approach used.

        Additionally, the amount of time and work that is required to make a stop-motion movie might be enormous. This may necessitate the involvement of a large team. Although this is dependent on the sort of video, stop motion animating is now a fairly broad area of filmmaking, which can require many different talents and approaches.

        Conclusion

        Using the Raspberry Pi 4, you were able to create a stop-motion movie system. Various stop motion technologies were also covered, along with their advantages and disadvantages. After completing the system's basic functions and integrating additional components of your choice, you're ready to go on to the next phase of programming. Using raspberry pi 4 in the next article, we will build an LED cube.

        Smart Security System using Facial Recognition with Raspberry Pi 4

        Greeting, and welcome to the next tutorial of our raspberry programming tutorial. In the previous tutorial, we learned how to build a smart attendance system using an RFID card reader, which we used to sign in students in attendance in a class. When it comes to building a face-recognition program on a Raspberry Pi, this tutorial will show you how. Two Python programs will be used in the lesson, one of which is a Training program that analyzes a collection of photographs of a certain individual and generates a dataset. (YML File). The Recognizer application uses the YML script to detect a face and afterward utters the person's name when the face is detected.

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

        Components

        • Raspberry Pi
        • Breadboard
        • L293 or SN755410 motor driver chip
        • Jumper wires
        • DC motor
        • 5v power supply

        A growing number of us already use face recognition software without realizing it. Facial recognition is used in several applications, from basic Fb Tag suggestions to advanced security screening surveillance. Chinese schools employ facial recognition to track students' adherence and behaviour for the first time. Retail stores use face recognition to classify their clients and identify those who have a history of crime. There's no denying that this tech will be all over soon, especially with so many other developments in the works.

        How does facial recognition work?

        When it comes to facial recognition, biometric authentication goes well beyond simply being able to identify human faces in images or videos. An additional step is taken to identify the person's identity. A facial recognition software compares an image of a person's face to a database to see if the features match another person's. Since facial expressions and hair do not affect the technology's ability to identify matches, it has been built to do so.

        How can face recognition be used when it comes to smart security systems?

        The first thing you should do if you want to make your home "smart" is to focus on security. Your most prized possessions are housed at this location, and protecting them is a must. You can monitor your home security status from your computer or smartphone thanks to a smart security system when you're outdoors.

        Installing a system that is not wireless in your house and signing you up for professional monitoring was traditionally done by a security company. The plot has been rewritten. When setting up a smart home system, you can even do it yourself. In addition, your smart smartphone acts as a professional monitor, providing you with real-time information and notifications.

        Face recognition is the ability of a smart camera in your house to identify a person based on their face. Consequently, you will have to inform the algorithm what face goes with what name for face recognition to operate. Facial detection in security systems necessitates the creation of user accounts for family members, acquaintances, and others you want to be identified by the system. Your doors or the inside of your house will be alerted when they arrive.

        Face-recognition technology allows you to create specific warning conditions. For example, you can configure a camera to inform you when an intruder enters your home with a face the camera doesn't recognize.

        Astonishing advancements in smart tech have been made in recent years. Companies are increasingly offering automatic locks with face recognition. You may open your doors just by smiling at a face recognition system door lock. You could, however, use a passcode or a real key to open and close the smart door. You may also configure your smart house lock to email you an emergency warning if someone on the blacklist tries to unlock your smart security door.

        How to install OpenCV for Raspberry Pi 4.

        OpenCV, as previously stated, will be used to identify and recognize faces. So, before continuing, let's set up the OpenCV library. Your Pi 4 needs a 2A power adapter and an HDMI cable because we won't be able to access the Pi's screen through SSH. The OpenCV documentation is a good place to learn how image processing works, but I'm not going to go into it here.

        Installing OpenCV using pip

        pip is well-known for making it simple to add new libraries to the python language. In addition, there is a technique to install OpenCV on a Raspberry Pi via PIP, but it didn't work for me. We can't obtain complete control of the OpenCV library when using pip to install OpenCV; however, this might be worth a go if time is of the essence.

        Ensure pip is set up on your Raspberry Pi. Then, one by one, execute the lines of code listed below into your terminal.

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

        sudo apt-get install libqtwebkit4 libqt4-test

        sudo pip install opencv-contrib-python?

        How OpenCV Recognizes Face

        Facial recognition and face detection are not the same things, and this must be clarified before we proceed. When simply a user's face is detected using Face detection, the program has no clue who that person is. Only the face will be detected in facial recognition software, but the program will also recognize it. At this point, it's pretty evident that facial detection comes before facial recognition. To explain how OpenCV recognizes a person or other objects, I will have to go into detail.

        Essentially, a webcam feed is like a long series continuously updating still photos. And every image is nothing more than a jumble of pixels with varying values arranged in a specific order. So, how does a computer software identify a face among all of these random pixels? Trying to describe the underlying techniques is outside the scope of this post, but since we're utilizing the OpenCV library, facial recognition is a straightforward process that doesn't necessitate a deeper understanding of the underlying principles.

        Using Cascade Classifiers for Face Detection

        We can only recognize a person if we can see it. Detection of an item, including a face, Classifiers are a feature of OpenCV. They are pre-trained datasets that may be utilized to recognize a certain item, such as a face. Classifiers may also detect additional objects, such as the mouth, the eyebrows, the number plate of a vehicle, and smiles.

        Alternatively, OpenCV allows you to design your custom Classifier for detecting any objects in images by retraining the cascade classifier. For the sake of this tutorial, we'll be using the classifier named "haarcascade_frontalface_default.xml" to identify faces from the camera. We'll learn more about image classifiers and how to apply them in code in the following sections.

        Setup the raspberry pi camera

        For the face training and detection, we only need the pi camera, and to install this, insert the raspberry pi camera in the pi camera slot as shown below. Then go to your terminal, open the configuration window using "sudo raspi-config", and press enter. Navigate to the interface options and activate the pi camera module. Accept the changes and finish the setup. Then reboot your RPi.

        How to Setup the Necessary Software

        First, ensure pip is set up, and then install the following packages using it.

        Install dlib: Dlib is a set of libraries for building ML and data analysis programs in the real world. To get dlib up and running, type the following command into your terminal window.

        Pip install dlib

        If everything goes according to plan, you should see something similar after running this command.

        Install pillow: The Python Image Library, generally known as PIL, is a tool for opening, manipulating, and saving images in various formats. The following command will set up PIL for you.

        pip install pillow

        You should receive the message below once this app has been installed.

        Install face_recognition: The face recognition package is often the most straightforward tool for detecting and manipulating human faces. Face recognition will be made easier with the help of this library. Installing this library is as simple as running the provided code.

        Pip install face_recognition –no –cache-dir

        If all goes well, you should see something similar to the one shown below after the installed software. Due to its size, I used the "—no –cache-dir" command-line option to configure the package without keeping any of its cache files.

        Face Recognition Folders

        A script named "haarcascade_frontalface_default.xml" is for detecting faces using a Classifier. It will also build a "face-trainner.yml" file using the training script based on the photos found in the face images directory.

        Start the face images folder with a collection of face images.

        The face images folder indicated above should contain subdirectories with the names of each person to be identified and several sample photographs of them. Esther and x have been identified for this tutorial. As a result, I've just generated the two sub-directories shown below, each containing a single image.

        You must rename the directory and replace the photographs with the names of the people you are identifying. It appears that a minimum of five images for each individual is optimal. However, the more participants, the slower the software will run.

        Face trainer program

        Face Trainer.py is a Python software that may be used to train a new face. The purpose of the software is to access the face photographs folder and scan for faces. As soon as it detects a face, it crops it, turns it to grayscale, and saves it in a file named face-trainner.yml using the face recognition package we had previously loaded. The information in this script can be used to identify the faces later. In addition to the whole Trainer program provided at the conclusion, we'll go over some more critical lines.

        The first step is to import the necessary modules. The cv2 package is utilized to process photos. The NumPy library can be used for image conversion, the operating system package is used for directory navigation, and PIL will be used to process photos.

        import cv2

        import numpy as np

        import os

        from PIL import Image

        Ensure that the XML file in question is located in the project directory to avoid encountering an issue. The LBPH Facial recognizer is then constructed using the recognizer parameter.

        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

        recognizer = cv2.createLBPHFaceRecognizer()

        Face_Images = os.path.join(os.getcwd(), "Face_Images")

        In order to open all of the files ending in.jpg,.jpg, or .png within every subfolder in the face images folder, we must traverse the tree with for loops. In a variable named path, we record the path to every image, and in a variable named person name, we store the file location name (the name of the user who uploaded the images).

        For root, dirs, files in os.walk(Face_Images):

        for file in files: #check every directory in it

        if file.endswith("jpeg") or file.endswith("jpg") or file.endswith("png"):

        path = os.path.join(root, file)

        person_name = os.path.basename(root)

        As a result, in case the name of the person changes, we increase a variable named Face_ID that will allow us to have a unique Face_ID for each individual.

        if pev_person_name!=person_name:

        Face_ID=Face_ID+1 #If yes increment the ID count

        pev_person_name = person_name

        Because the BGR values may be ignored, grayscale photos are simpler for OpenCV to deal with than colourful ones. We transform the data to grayscale and afterwards lower the image size by 50% so that all the pictures are the same size. To avoid having your face cut out, place it in the centre of the photo. To get a numerical number for these photos, transform them into NumPy arrays. Afterwards, a classifier identifies a face in a photo and saves the results in variable named faces.

        Gery_Image = Image.open(path).convert("L")

        Crop_Image = Gery_Image.resize( (550,550) , Image.ANTIALIAS)

        Final_Image = np.array(Crop_Image, "uint8")

        faces = face_cascade.detectMultiScale(Final_Image, scaleFactor=1.5, minNeighbors=5)

        Our Area of Attention will be the portion of the image where the face may be found after being cropped. It will be utilized to train the face-recognition system in the ROI area. Every area of attention face must be appended to a variable named x train. We then feed the recognizer with our training data using the area of attention values and Face ID data. The information gathered will be archived.

        for (x,y,w,h) in faces:

        roi = Final_Image[y:y+h, x:x+w]

        x_train.append(roi)

        y_ID.append(Face_ID)

         

        recognizer.train(x_train, np.array(y_ID))

        recognizer.save("face-trainner.yml")

        You'll notice that the face-trainner.yml script is modified whenever you run this program. If you make any modifications to the photographs in the Face Images folder, ensure to recompile this code. Debugging purposes include printing out the Face ID, name of the path, name of a person, and NumPy arrays.

        Face recognition program

        We can begin using our trained data to identify people now that it has been prepared. We'll use a USB webcam or pi camera to feed video into the Face recognizer application, turning it into an image. Once we've found the faces in those images, we'll find similarities to all of our previously developed Face IDs. Finally, we output the identified person’s name in boxes around their face. Afterwards, the whole program is presented, and the explanation is below.

        Import the required module from the training program and use the classifier because we need to do more facial detection in this program.

        import cv2

        import numpy as np

        import os

        from time import sleep

        from PIL import Image

        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

        recognizer = cv2.createLBPHFaceRecognizer()

        The people listed in the folder should be entered in the variable named labels. Insist on performing each step in the same order. It is "Esther" and "Unknown" in my situation.

        labels = ["Esther", "Unknown"]

        We need the trainer file to detect faces, so we import it into our software.

        recognizer.load("face-trainner.yml")

        The camera provides the video stream. It's possible to access any second pi camera by replacing 0 with 1.

        cap = cv2.VideoCapture(0)

        In the next step, we separate the footage into images and transform it into grayscale, and afterwards, we search for a face in the photo. To save the area of attention grey image, we must first detect the face and then crop the image to remove them.

        ret, img = cap.read()

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)

        for (x, y, w, h) in faces:

        roi_gray = gray[y:y+h, x:x+w]

        id_, conf = recognizer.predict(roi_gray)

        It informs us how sure the program is in its ability to identify the person. We write the code below to get the person's name based on their Identification number. A square should be drawn around the user's head, written outside their name.

        if conf>=80:

        font = cv2.FONT_HERSHEY_SIMPLEX

        name = labels[id_]

        cv2.putText(img, name, (x,y), font, 1, (0,0,255), 2)

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

        We must playback and afterwards break the video stream we just evaluated, which is done by pressing a wait key.

        cv2.imshow('Preview',img)

        if cv2.waitKey(20) & 0xFF == ord('q'):

        break

        While running this application, ensure the Raspberry is linked to a display via HDMI. A display with your video stream and the name will appear when you open the application. There will be a box around the face identified in the video feed, and if your software recognizes the face, it displays that person’s name. As evidenced by the image below, we've trained our software to identify my face, which shows the recognition process in action.

        The face recognition code

        import cv2

        import numpy as np

        import os

        from PIL import Image

        labels = ["Esther", "Unknown"]

        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

        recognizer = cv2.createLBPHFaceRecognizer()

        recognizer.load("face-trainner.yml")

        cap = cv2.VideoCapture(0)

        while(True):

        ret, img = cap.read()

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) #Recog. faces

        for (x, y, w, h) in faces:

        roi_gray = gray[y:y+h, x:x+w]

        id_, conf = recognizer.predict(roi_gray)

        if conf>=80:

        font = cv2.FONT_HERSHEY_SIMPLEX

        name = labels[id_]

        cv2.putText(img, name, (x,y), font, 1, (0,0,255), 2)

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

        cv2.imshow('Preview',img)

        if cv2.waitKey(20) & 0xFF == ord('q'):

        break

        cap.release()

        cv2.destroyAllWindows()

        Face detection code

        import cv2

        import numpy as np

        import os

        from PIL import Image

        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

        recognizer = cv2.createLBPHFaceRecognizer()

         

        Face_ID = -1

        pev_person_name = ""

        y_ID = []

        x_train = []

        Face_Images = os.path.join(os.getcwd(), "Face_Images")

        print (Face_Images)

        for root, dirs, files in os.walk(Face_Images):

        for file in files:

        if file.endswith("jpeg") or file.endswith("jpg") or file.endswith("png"):

        path = os.path.join(root, file)

        person_name = os.path.basename(root)

        print(path, person_name)

        if pev_person_name!=person_name:

        Face_ID=Face_ID+1

        pev_person_name = person_name

        Gery_Image = Image.open(path).convert("L")

        Crop_Image = Gery_Image.resize( (550,550) , Image.ANTIALIAS)

        Final_Image = np.array(Crop_Image, "uint8")

        faces = face_cascade.detectMultiScale(Final_Image, scaleFactor=1.5, minNeighbors=5)

        print (Face_ID,faces)

        for (x,y,w,h) in faces:

        roi = Final_Image[y:y+h, x:x+w]

        x_train.append(roi)

        y_ID.append(Face_ID)

        recognizer.train(x_train, np.array(y_ID))

        recognizer.save("face-trainner.yml")

        DC motor circuit

        Since the "How to operate DC motor in Rpi 4" guide has covered the basics of controlling a DC motor, I won't provide much detail here. Please read this topic if you haven't already. Check all the wiring before using the batteries in your circuit, as outlined in the image above. Everything must be in place before connecting your breadboard's power lines to the battery wires.

        Testing

        To activate the motors, open the terminal because you'll use the Python code-writing program called Nano in this location. For those of you who aren't familiar with the command-line text editor known as Nano, I'll show you how to use some of its commands as we go.

        This code will activate the motor for two seconds, so try it out.

        import RPi.GPIO as GPIO

        from time import sleep

        GPIO.setmode(GPIO.BOARD)

        Motor1A = 16

        Motor1B = 18

        Motor1E = 22

        GPIO.setup(Motor1A,GPIO.OUT)

        GPIO.setup(Motor1B,GPIO.OUT)

        GPIO.setup(Motor1E,GPIO.OUT)

        print "Turning motor on"

        GPIO.output(Motor1A,GPIO.HIGH)

        GPIO.output(Motor1B,GPIO.LOW)

        GPIO.output(Motor1E,GPIO.HIGH)

        sleep(2)

        print "Stopping motor"

        GPIO.output(Motor1E,GPIO.LOW)

        GPIO.cleanup()

        The very first two lines of code tell Python whatever the program needs.

        The RPi.GPIO package is what the first line is looking for. The RPi GPIO pins are controlled by this module, which takes care of all the grunt work.

        It is necessary to delay the script for a few seconds to provide the package time to operate, therefore leaving a motor to run for a while.

        The method set mode is used to leverage the RPi's board numbers. We'll tell Python that the pins 16 through 22 correspond to the motors.

        Pin A is used to steer the L293D in one way, and pin B is used to direct it in the opposite direction. You can turn on the motor using an Enable pin, referred to as E, inside the test file.

        Finally, use GPIO.OUT to inform the RPi that all these are outputs.

        The RPi is ready to turn the motor after the software is set up. After a 2-second pause, some pins will be turned on and subsequently turned off, as seen in the code.

        Save and quit by hitting CTRL-X, and a confirmation notice appears at the bottom. To acknowledge, tap Y and Return. You can now run the program in the terminal and watch as the motor begins to spin up.

        sudo python motor.py

        If the motor doesn't move, check the cabling or power supply. The debug process might be a pain, but it's an important phase in learning new things!

        Now turn in the other direction.

        I'll teach you how to reverse a motor's rotation to spin in the opposite direction.

        There's no need to touch the wiring at this point; it's all Python. Create a new script called motorback.py to accomplish this. Using Nano, type the command:

        ./script

        Please type in the given program:

        import RPi.GPIO as GPIO

        from time import sleep

        GPIO.setmode(GPIO.BOARD)

        Motor1A = 16

        Motor1B = 18

        Motor1E = 22

        GPIO.setup(Motor1A,GPIO.OUT)

        GPIO.setup(Motor1B,GPIO.OUT)

        GPIO.setup(Motor1E,GPIO.OUT)

        print "Going forwards"

        GPIO.output(Motor1A,GPIO.HIGH)

        GPIO.output(Motor1B,GPIO.LOW)

        GPIO.output(Motor1E,GPIO.HIGH)

        sleep(2)

        print "Going backwards"

        GPIO.output(Motor1A,GPIO.LOW)

        GPIO.output(Motor1B,GPIO.HIGH)

        GPIO.output(Motor1E,GPIO.HIGH)

        sleep(2)

        print "Now stop"

        GPIO.output(Motor1E,GPIO.LOW)

        GPIO.cleanup()

        Save by pressing CTRL, then X, then Y, and finally Enter key.

        For reverse compatibility, we've set Motor1A low in the script.

        Programmers use the terms "high" and "low" to denote the state of being on or off, respectively.

        Motor1E will be turned off to halt the motor.

        Irrespective of what A is doing; the motor can be turned on or off using the Enable switch.

        Take a peek at the Truth Table to understand better what's going on.

        When Enabled, only two states allow the motor to move; A or B is high, and not both high at the same time.

        Putting it all together

        At this point, we have designed our face detection system and the dc motor control circuit; now, we will put the two systems to work together. When the user is verified, the dc motor should run to open the cd rom drive and close after a few seconds.

        In our verify code, we will copy the code below to spin the motor in one direction “open the door” when the user is verified. We will also increase the time to 5 seconds to simulate the door's time to open for the user to get through. This also allows the motor to spin long enough to open and close the cd room completely. I would also recommend putting a stopper on the cd room door so that it doesn't close all the war and get stuck.

        if conf>=80:

        font = cv2.FONT_HERSHEY_SIMPLEX

        name = labels[id_] #Get the name from the List using ID number

        cv2.putText(img, name, (x,y), font, 1, (0,0,255), 2)

        #place our motor code here

        GPIO.setmode(GPIO.BOARD)

        Motor1A = 16

        Motor1B = 18

        Motor1E = 22

         

        GPIO.setup(Motor1A,GPIO.OUT)

        GPIO.setup(Motor1B,GPIO.OUT)

        GPIO.setup(Motor1E,GPIO.OUT)

        Print("Openning")

        GPIO.output(Motor1A,GPIO.HIGH)

        GPIO.output(Motor1B,GPIO.LOW)

        GPIO.output(Motor1E,GPIO.HIGH)

        sleep(5)

        print("Closing")

        GPIO.output(Motor1A,GPIO.LOW)

        GPIO.output(Motor1B,GPIO.HIGH)

        GPIO.output(Motor1E,GPIO.HIGH)

        sleep(5)

        print("stop")

        GPIO.output(Motor1E,GPIO.LOW)

        GPIO.cleanup()

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

        Output

        The advantages of face recognition over alternative biometric verification methods for home security

        An individual's biometric identity can be verified by looking at various physical and behavioural characteristics, such as a person's fingerprint, keystrokes, facial characteristics, and voice. Face recognition seems to be the winner because of the precision, simplicity, and lack of contact detection.

        Face-recognition technology will continue and will get better over time. The tale has evolved, and your alternatives have grown due to smart tech.

        What are the advantages of employing Facial Recognition when it comes to smart home security?

        Using an RPi as a surveillance system means you can take it with you and use it wherever you need it.

        1. High accuracy rate

        For the most part, the face-recognition software employed in security systems can reliably assess whether or not the individual attempting entry matches your record of those authorized to enter. On the other hand, certain computer programs are more precise when it comes to identifying faces from diverse angles or different countries.

        Concerned users may be relieved to learn that some programs have the option of setting custom confidence criteria, which can significantly minimize the likelihood of the system giving false positives. Alternatively, 2-factor authentication can be used to secure your account.

        1. Automation

        When your smart security system discovers a match between a user and the list of persons you've given access to, it will instantly let them in. Answering the doorbell or allowing entry isn't necessary.

        1. Smart integration

        Face recognition solutions can be readily integrated into existing systems using an API.

        Cons of Facial Recognition

        1. Privacy of individuals and society as a whole is more at risk

        A major drawback of face recognition technology is that it puts people's privacy at risk. Having one's face collected and stored in an unidentified database does not sit well with the average person.

        Confidentiality is so important that several towns have prohibited law enforcement from using real-time face recognition monitoring. Rather than using live face recognition software, authorities can use records from privately-held security cameras in certain situations.

        1. can infringe on one's liberties

        Having your face captured and stored by face recognition software might make you feel monitored and assessed for your actions. It is a form of criminal profiling since the police can use face recognition to put everybody in their databases via a virtual crime lineup.

        1. It's possible to deceive modern technology.

        Face recognition technology can be affected by various other elements, including camera angle, illumination, and other aspects of a picture or video. Facial recognition software can be fooled by those who do disguises or alter their appearance.

        Conclusion

        This article walked us through creating a complete Smart Security System using a facial recognition program from the ground up. Our model can now recognize faces with the help of OpenCV image manipulation techniques. There are several ways to further your knowledge of supervised machine learning programming with raspberry pi 4, including adding an alarm to ring whenever an individual's face is not recognized or creating a database of known faces to act like a CCTV surveillance system. We'll design a security system with a motion detector and an alarm in the next session.

        Smart Attendance System using RFID with Raspberry Pi 4

        Greetings! This is the complete project of our Raspberry Pi 4 tutorials. In our previous tutorial, we learned to set up our raspberry pi as a virtual private network server. In this tutorial, we will design a smart attendance system using an RFID card reader, which we will use to sign in students in attendance in a class.

        First, we will design a database for our website, then we will design the RFID circuit for scanning the student cards and displaying present students on the webpage, and finally, we will design the website that we will use to display the attendees of a class.

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

        Components

        • RFID card kit
        • Breadboard
        • Jumper wires
        • Raspberry pi 4
        • I2C LCD screen

        Design a database in MySQL server

        Additionally, the Database server offers a DBMS that can be queried and connected to and can integrate with a wide range of platforms. High-volume production environments are no problem for this software. The server's connection, speed, and encryption make it a good choice for accessing the database.

        There are clients and servers for MySQL. This system contains a SQL server with many threads that support a wide range of back ends, utility programs, and application programming interfaces.

        We'll walk through the process of installing MySQL on the RPi in this part. The RFID kit's database resides on this server, and we'll utilize it to store the system's signed users.

        There are a few steps before we can begin installing MySQL on a Raspberry Pi. There are two ways to accomplish this.

        sudo apt update

        sudo apt upgrade

        Installing the server software is the next step.

        Here's how to get MySQL running on the RPi using the command below:

        sudo apt install MariaDB-server

        Having installed MySQL on the Raspberry Pi, we'll need to protect it by creating a passcode for the "root" account.

        If you don't specify a password for your MySQL server, you can access it without authentication.

        Using this command, you may begin safeguarding MySQL.

        sudo mysql_secure_installation

        Follow the on-screen instructions to set a passcode for the root account and safeguard your MySQL database.

        To ensure a more secured installation, select "Y" for all yes/no questions.

        Remove elements that make it easy for anyone to access the database.

        We may need that password to access the server and set up the database and user for applications like PHPMyAdmin.

        For now, you can use this command if you wish to access the Rpi's MySQL server and begin making database modifications.

        sudo MySQL –u root -p

        To access MySQL, you'll need to enter the root user's password, which you created in Step 3.

        Note: Typing text will not appear while typing, as it does in typical Linux password prompts.

        Create, edit, and remove databases with MYSQL commands now available. Additionally, you can create, edit, and delete users from inside this interface and provide them access to various databases.

        After typing "quit;" into MySQL's user interface, you can exit the command line by pressing the ESC key.

        Pressing CTRL + D will also exit the MYSQL command line.

        You may proceed to the next step now that you've successfully installed MySQL. In the next few sections, we'll discuss how to get the most out of our database.

        Creating database and user

        The command prompt program MySQL must be restarted before we can proceed with creating a username and database on the RPi.

        The MySQL command prompt can be accessed by typing the following command. After creating the "root" user, you will be asked for the password.

        To get things started, run the command to create a MySQL database.

        The code to create a database is "CREATE DATABASE", and then the name we like to give it.

        This database would be referred to as "rfidcardsdb" in this example.

        To get started, we'll need to create a MySQL user. The command below can be used to create this new user.

        "rfidreader" and "password" will be the username and password for this example. Take care to change these when making your own.

        create user “rfidreader" @localhost identified by "password."

        We can now offer the user full access to the database after it has been built.

        Thanks to this command, " "rfidreader" will now have access to all tables in our "rfidcardsdb" database.

        grant all on rfidcardsdb.* to "rfidreader" identified by "password."

        We have to flush the permission table to complete our database and user set up one last time. You cannot grant access to the database without flushing your privilege table.

        The command below can be used to accomplish this.

        Now we have our database configured, and now the next step is to set up our RFID circuit and begin authenticating users. Enter the “Exit” command to close the database configuration process.

        The RFID card circuit

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

        In theory, RFID is comparable to bar codes in that 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't read an RFID tag that is more than three feet away from the reader. To quickly scan a large number of objects, the RFID tech is used, and this makes it possible to identify a specific product rapidly and effortlessly, even if it is sandwiched between several other things.

        HOW RFID CARD READERS AND WRITERS WORK

        There are major parts to Cards and tags: an IC that holds the unique identifier value and a copper wire that serves as the antenna:

        Another coil of copper wire can be found inside the RFID card reader. When current passes through this coil, it generates a magnetic field. The magnetic flux from the reader creates a current within the wire coil whenever the card is swiped near the reader. This amount of current can power the inbuilt IC of the Card. The reader then reads the card's unique identifying number. For further processing, the card reader transmits the card's unique identification number to the controller or CPU, such as the Raspberry Pi.

        RFID card reader circuit

        Connect the reader to the Raspberry the following way:

        use the code spi bcm2835 to see if it is displayed in the terminal.

        lsmod | grep spi

        SPI must be enabled in the setup for spi bcm2835 to appear (see above). Make sure that RPi is running the most recent software.

        Make use of the python module.

        sudo apt-get install python

        The RFID RC522 can be interacted with using the Library SPI Py, found on your RPi.

        cd ~

        git clone https://github.com/lthiery/SPI-Py.git

        cd ~/SPI-Py

        sudo python setup.py install

        cd ~

        git clone https://github.com/pimylifeup/MFRC522-python.git

        To test if the system is functioning correctly, let's write a small program:

        cd ~/

        sudo nano test.py

        now copy the following the code into the editor

        import RPi.GPIO as GPIO

        import sys

        sys.path.append('/home/pi/MFRC522-python')

        from mfrc522 import SimpleMFRC522

        reader = SimpleMFRC522()

        print("Hold a tag near the reader")

        try:

        id, text = reader.read()

        print(id)

        print(text)

        finally:

        GPIO.cleanup()

        Register card

        Here we will write a short python code to register users whenever they swipe a new card on the RFID card reader. First, create a file named addcard.py.

        copy the following code.

        import pymysql

        import cv2

        from mfrc522 import SimpleMFRC522

        import RPi.GPIO as GPIO

        import drivers

        display = drivers.Lcd()

        display.lcd_display_string('Scan your', 1)

        display.lcd_display_string('card', 2)

        reader = SimpleMFRC522()

        reader = SimpleMFRC522()

        id, text = reader.read()

        display = drivers.Lcd()

        display.lcd_display_string('Type your name', 1)

        display.lcd_display_string('in the terminal', 2)

        user_id = input("user name?")

        # put serial_no uppercase just in case

        serial_no = '{}'.format(id)

        # open an sql session

        sql_con = pymysql.connect(host='localhost', user='rfidreader', passwd='password', db='rfidcardsdb')

        sqlcursor = sql_con.cursor()

        # first thing is to check if the card exist

        sql_request = 'SELECT card_id,user_id,serial_no,valid FROM cardtbl WHERE serial_no = "' + serial_no + '"'

        count = sqlcursor.execute(sql_request)

        if count > 0:

        print("Error! RFID card {} already in database".format(serial_no))

        display = drivers.Lcd()

        display.lcd_display_string('The card is', 1)

        display.lcd_display_string('already registered', 2)

        T = sqlcursor.fetchone()

        print(T)

        else:

        sql_insert = 'INSERT INTO cardtbl (serial_no,user_id,valid) ' + \

        'values("{}","{}","1")'.format(serial_no, user_id)

        count = sqlcursor.execute(sql_insert)

        if count > 0:

        sql_con.commit()

        # let's check it just in case

        count = sqlcursor.execute(sql_request)

        if count > 0:

        print("RFID card {} inserted to database".format(serial_no))

        T = sqlcursor.fetchone()

        print(T)

        display = drivers.Lcd()

        display.lcd_display_string('Congratulations', 1)

        display.lcd_display_string('You are registered', 2)

        GPIO.cleanup()

        The program starts by asking the user to scan the card.

        Then it connects to the database using the pymysql.connect function.

        If we enter our name successfully, the program inserts our details in the database, and a congratulations message is displayed to show that we are registered.

        Creating the main system

        Using the LCD command library, you can:

        1. Install git

        sudo apt install git

        1. Download and install the repo on your Raspberry Pi.

        cd /home/pi/

        git clone https://github.com/the-raspberry-pi-guy/lcd.git

        cd lcd/

        1. Then begin installation with the following

        sudo ./install.sh

        After installation is complete, try running one of the program files

        cd /home/pi/lcd/

        Next, we will install the mfrc522 library, which the RFID card reader uses. This will enable us to read the card number for authentication. We will use:

        Pip install mfrc522

        Next, we will import the RPI.GPIO library enables us to utilize the raspberry pi pins to power the RFID card and the LCD screen.

        Import RPi.GPIO

        We will also import the drivers for our LCD screen. The LCD screen used here is the I2C 16 * 2 LCD.

        Import drivers

        Then we will import DateTime for logging the time the user has swiped the card into the system.

        Import DateTime

        In order to read the card using the rfid card, we will use the following code:

        reader = SimpleMFRC522()

        display = drivers.Lcd()

        display.lcd_display_string('Hello Please', 1)

        display.lcd_display_string('Scan Your ID', 2)

        try:

        id, text = reader.read()

        print(id)

        display.lcd_clear()

        finally:

        GPIO.cleanup()

        The LCD is divided into two rows, 1 and 2. To display text in the first row, we use:

        Display.lcd_display_string(“string”,1)

        And 2 to display in the second row.

        After scanning the card, we will connect to the database we created earlier and search whether the scanned card is in the database or not.

        If the query is successful, we can display if the card is in the database; if not, we can proceed, then the user needs to register the card.

        If the user is registered, the system saves the logs, the username and the time the card was swapped in a text file located in the/var/www/html root directory of the apache server.

        Note that you will need to be a superuser to create the data.txt file in the apache root directory. For this, we will use the following command in the Html folder:

        Sudo touch data.txt

        Then we will have to change the access privileges of this data.txt file to use the program to write the log data. For this, we will use the following code:

        Sudo chmod 777 –R data.txt

        The next step will be to display this data on a webpage to simulate an online attendance register. The code for the RFID card can be found below.

        #! /usr/bin/env python

        # Import necessary libraries for communication and display use

        import RPi.GPIO as GPIO

        from mfrc522 import SimpleMFRC522

        import pymysql

        import drivers

        import os

        import numpy as np

        import datetime

        # read the card using the rfid card

        reader = SimpleMFRC522()

        display = drivers.Lcd()

        display.lcd_display_string('Hello Please', 1)

        display.lcd_display_string('Scan Your ID', 2)

        try:

        id, text = reader.read()

        print(id)

        display.lcd_clear()

        # Load the driver and set it to "display"

        # If you use something from the driver library use the "display." prefix first

        try:

        sql_con = pymysql.connect(host='localhost', user='rfidreader', passwd='password', db='rfidcardsdb')

        sqlcursor = sql_con.cursor()

        # first thing is to check if the card exist

        cardnumber = '{}'.format(id)

        sql_request = 'SELECT user_id FROM cardtbl WHERE serial_no = "' + cardnumber + '"'

        now = datetime.datetime.now()

        print("Current date and time: ")

        print(str(now))

        count = sqlcursor.execute(sql_request)

        if count > 0:

        print("already in database")

        T = sqlcursor.fetchone()

        print(T)

        for i in T:

        print(i)

        file = open("/var/www/html/data.txt","a")

        file.write(i +" Logged at "+ str(now) + "\n")

        file.close()

        display.lcd_display_string(i, 1)

        display.lcd_display_string('Logged In', 2)

        else:

        display.lcd_clear()

        display.lcd_display_string(“Please register”, 1)

        display.lcd_display_string(cardnumber,2)

        except KeyboardInterrupt:

        # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup

        print("Cleaning up!")

        display.lcd_clear()

        finally:

        GPIO.cleanup()

        Building the website

        Now we are going to design a simple website with Html that we are going to display the information of the attending students of a class, and to do this, we will have to install a local server in our raspberry pi.

        Installing Apache Web Server

        Web, database, and mail servers all run on various server software. Each of these programs can access and utilize files located on a physical server.

        A web server's main responsibility is to provide internet users access to various websites. It serves as a bridge between a server and a client machine to accomplish this. Each time a user makes a request, it retrieves data from the server and posts it to the web.

        A web server's largest issue is to simultaneously serve many web users, each of whom requests a separate page.

        For internet users, convert them to Html pages and offer them in the browser. Whenever you hear the term "webserver," consider the device in charge of ensuring successful communication in a network of computers.

        How Does Apache Work?

        Among its responsibilities is establishing a link between a server and a client's web browser (such as Chrome to send and receive data (client-server structure). As a result, the Apache software can be used on any platform, from Microsoft to Unix.

        Visitors to your website, such as those who wish to view your homepage or "About Us" page, request files from your server via their browser, and Apache returns the required files in a response (text, images, etc.).

        Using HTTP, the client and server exchange data with the Apache webserver, ensuring that the connection is safe and stable.

        Because of its open-source foundation, Apache promotes a great deal of customization. As a result, web developers and end-users can customize the source code to fit the needs of their respective websites.

        Additional server-side functionality can be enabled or disabled using Apache's numerous modules. Encryption, password authentication, and other capabilities are all available as Apache modules.

        Step 1

        To begin, use the following code to upgrade the Pi package list.

        sudo apt-get update

        sudo apt-get upgrade

        Step 2

        After that, set up the Apache2 package.

        sudo apt install apache2 -y

        That concludes our discussion. You can get your Raspberry Pi configured with a server in just two easy steps.

        Type the code below to see if the server is up and functioning.

        sudo service apache2 status

        You can now verify that Apache is operating by entering your Raspberry Pi's IP address into an internet browser and seeing a simple page like this.

        Use the following command in the console of your Raspberry Pi to discover your IP.

        hostname-i

        Only your home network and not the internet can access the server. You'll need to configure your router's port forwarding to allow this server to be accessed from any location. Our blog will not be discussing this topic.

        Setting up HTML page for editing.

        The standard web page on the Raspberry Pi, as depicted above, is nothing more than an HTML file. First, we will generate our first Html document and develop a website.

        Step 1

        Let's start by locating the Html document on the Raspbian system. You can do this by typing the following code in the command line.

        cd /var/www/html

        Step 2

        To see a complete listing of the items in this folder, run the following command.

        ls -al

        The root account possesses the index.html file; therefore, you'll see every file in the folder.

        As a result, to make changes to this file, you must first change the file's ownership to your own. The username "pi" is indeed the default for the Raspberry Pi.

        sudo chown pi: index.html

        To view the changes you've made, all you have to do is reload your browser after saving the file.

        Building your first HTML page

        Here, we'll begin to teach you the fundamentals of HTML.

        To begin a new page, edit the index.html file and remove everything inside it using the command below.

        sudo nano index.html

        Alternatively, we can use a code editor to open the index.html file and edit it. We will use VS code editor that you can easily install in raspberry pi using the preferences then recommended software button.

        HTML Tags

        You must first learn about HTML tags, which are a fundamental part of HTML. A web page's content can be formatted in various ways by using tags.

        There are often two tags used for this purpose: the opening and closing tags. The material inside these tags behaves according to what these tags say.

        The p> tag, for example, is used to add paragraphs of text to the website.

        <p>The engineering projects</p>

        Web pages can be made more user-friendly by using buttons, which can be activated anytime a user clicks on them.

        <button>Manual Refresh</button>

        <button>Sort By First Name</button>

        <button>Sort By last Name</button>

        The basic format of an HTML document

        A typical HTML document is organized as follows:

        Let us create the page that we will use in this project.

        <html>

        <head>

        </head>

        <body>

        <div id="pageDiv">

        <p> The engineering projects</p>

        <button type="button" id="refreshNames">Manual Refresh</button><br/>

        <button type="button" id="firstSort">Sort By First Name</button><br/>

        <button type="button" id="lastSort">Sort By Last Name</button>

        <div id="namesFromFile">

        </div>

        </div>

        </body>

        </html>

        <!DOCTYPE html>: HTML documents are identified by this tag. This does not necessitate the use of a closing tag.

        <html>: This tag ensures that the material inside will meet all of the requirements for HTML. There is a /html> tag at the end of this.

        </head>: It contains data about the website, but when you view it in a browser, you won't be able to see anything.

        A metadata tag in the head tag can be used to set default character encoding in your website, for instance. This has a /head> tag at the end of it.

        <head>

        <meta charset="utf-8">

        </head>

        Also, you can have a title tag inside the head tag. This tag sets the title of your web page and has a closing </title> tag.

        <head>

        <meta charset="utf-8">

        <title> My website </title>

        </head>

        <body>: The primary focus of the website page is included within this tag. Everything on a web page is usually contained within body tags once you've opened it. This has a /body> tag at the end of it. Many other tags can be found in this body tag, but we'll focus on the ones you need to get started with your first web page.

        We will go ahead and style our webpage using CSS with the lines of codes below;

        <head>

        <!--

        body {

        width:100%;

        background:#ccc;

        color:#000;

        text-align:left;

        margin:0

        ;padding:10px

        ;font:16px/18pxArial;

        }

        button {

        width:160px;

        margin:0 0 10px;}

        #pageDiv {

        width:160px;

        margin:20px auto;

        padding:20px;

        background:#ddd;

        color:#000;

        }

        #namesFromFile {

        margin:20px 0 0;

        padding:10px;

        background:#fff;

        color:#000;

        border:1px solid #000;

        border-radius:10px;

        }

        -->

        </style>

        </head>

        The style tags is a cascading style sheet syntax that lets developers style the webpages however they prefer.

        Adding images to your web page

        You can add images to your web page by using the <img> tag. It is also a void element and doesn’t have a closing tag. It takes the following format

        <img src="URL of image location">

        For example, let’s add an image of the Seeeduino XIAO

        <p>The Engineering projects</p>

        <img src="https://www.theengineeringprojects.com/wp-content/uploads/2022/04/TEP-Logo.png">

        Reload the browser to see the changes

        How to display the attendance list on the webpage

        This is the last step of this project, and we will implement a program that reads our data.txt file from the apache root directory and display it on the webpage that we designed. Since we already have our webpage up and running, we will use the javascript programming language to implement this function of displaying the log list on the webpage. All changes that we are about to implement will be done in the index.html file; therefore, open it in the visual studio code editor.

        Javascript – What is it?

        JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side scripts to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

        Advantage of javascript

        One of the major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad.

        How to use javascript with this program

        Well, javascript as mentioned earlier is a very easy to use language that simply requires us to put the script tags inside the html tags.

        <script> script program </script>

        <header>

        <script>

        Here goes our javascript program

        </script>

        </header>

        The javascript code first opens the data.txt file, then it reads all the contents form that file. Then it uses the xmlHttpRequest function to display the contents on the webpage. The buttons on the webpage activate different functions in the code.For instance manual refresh activates:

        function refreshNamesFromFile(){

        var namesNode=document.getElementById("namesFromFile");

        while(namesNode.firstChild)

        { namesNode.removeChild(namesNode.firstChild);

        }

        getNameFile();

        }

        This function reads the content of the data.txt

        The sort by buttons activate the sort function to sort the logged users either by first name or last name. The function that gets activated by these buttons is:

        function sortByName(e)

        { var i=0, el, sortEl=[], namesNode=document.getElementById("namesFromFile"), sortMethod, evt, evtSrc, oP;

        evt=e||event;

        evtSrc=evt.target||evt.srcElement;

        sortMethod=(evtSrc.id==="firstSort")?"first":"last";

        while(el=namesNode.getElementsByTagName("P").item(i++)){

        sortEl[i-1]=[el.innerHTML.split(" ")[0],el.innerHTML.split(" ")[1]];

        }

        sortEl.sort(function(a,b){

        var x=a[0].toLowerCase(), y=b[0].toLowerCase(), s=a[1].toLowerCase(), t=b[1].toLowerCase();

        if(sortMethod==="first"){

        return x<y?-1:x>y?1:s<t?-1:s>t?1:0;

        }

        else{

        return s<t?-1:s>t?1:x<y?-1:x>y?1:0;

        }

        });

        while(namesNode.firstChild){

        namesNode.removeChild(namesNode.firstChild);

        }

        for(i=0;i<sortEl.length;i++){

        oP=document.createElement("P");

        namesNode.appendChild(oP).appendChild(document.createTextNode(sortEl[i][0]+" "+sortEl[i][1]));

        namesNode.appendChild(document.createTextNode("\r\n"));

        //insert tests -> for style/format

        if(sortEl[i][0]==="John"){

        oP.style.color="#f00";

        }

        if(sortEl[i][0]==="Sue")

        { oP.style.color="#0c0";

        oP.style.fontWeight="bold";

        }

        }

        }

        Output

        With no logged-in users

        With one logged in user

        With two users logged in

        Sort by the first name

        Sort by last name

        Applications of RFID

        Benefits of Smart Attendance System

        Automated attendance systems are excessively time-consuming and sophisticated in the current environment. It is possible to strengthen company ethics and work culture by using an effective smart attendance management system. Employees will only have to complete the registration process once, and images get saved in the system's database. The automated attendance system uses a computerized real-time image of a person's face to identify them. The database is updated frequently, and its findings are accurate in a user interactive state because each employee's presence is recorded.

        Smart attendance systems have several advantages, including the following:

        Students in elementary, secondary, and postsecondary institutions can utilize this system to keep track of their attendance. It can also keep track of workers' schedules in the workplace. Instead of using a traditional method, it uses RFID tags on ID cards to quickly and securely track each person.

        What are the applications of a smart attendance system?

        Computerized smart attendance can be applied in many areas in our day today activities which include the following:

        1) Real-time tracking – Keeping track of staff attendance using mobile devices and desktops is possible.

        2)Decreased errors – A computerized attendance system can provide reliable information with minimal human intervention, reducing the likelihood of human error and freeing up staff time.

        3) Management of enormous data – It is possible to manage and organize enormous amounts of data precisely in the db.

        4) Improve authentications and security – A smart system has been implemented to protect the privacy and security of the user's data.

        5) Reports – Employee log-ins and log-outs can be tracked, attendance-based compensation calculated, the absent list may be viewed and required actions are taken, and employee personal information can be accessed.

        Conclusion

        This tutorial taught us to build a smart RFID card authentication project from scratch. We also learned how to set up an apache server and design a circuit for the RFID and the LCD screen. To increase your raspberry programming skills, you can proceed to building a more complex system with this code for example implementing face detection that automatically starts the authentication process once the student faces the camera or implement a student log out whenever the student leaves the system. In the following tutorial, we will learn how to build a smart security system using facial recognition.

        Taking a screenshot in Raspberry pi 4

        Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to how to print from a Raspberry pi. We also discussed some libraries to create a print server in our raspberry pi. We will learn how to take screenshots on Raspberry Pi using a few different methods in this lesson. We will also look at how to take snapshots on our Raspberry Pi using SSH remotely.

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

        Why should you read this article?

        This article will assist you when working with projects that require snapshots for documenting your work, sharing, or generating tutorials.

        So, let us begin.

        Screenshots are said to be the essential items on the internet today. And if you have seen these screenshots in tutorial videos or even used them in regular communication, you're already aware of how effective screenshots can be. They are quickly becoming a key internet currency for more efficient communication. Knowing how and when to utilize the correct ones will help you stand out from the crowd.

        Requirements

        • Raspberry Pi
        • MicroSD Card
        • Power Supply
        • Ethernet Cable

        Taking Screenshots Using Scrot

        In this case, we'll employ Scrot, a software program, to help with the PrintScreen procedure. This fantastic software program allows you to take screenshots using commands, shortcut keys, and enabled shortcuts.

        Features of Scrot

        • We could easily snap screen captures using scrot with no other tasks.
        • We could also improve the image quality of screen photos by using the -q option and a level of quality from 1 to 100. The quality level is currently at 75 by default.
        • It is straightforward to set up and use.
        • We may capture a particular window or even a rectangle portion of the display using the button.
        • Capable of retrieving all screen captures in a specific directory and storing all screen captures on a distant Computer or networked server.
        • Automatically monitor multiple desktop PCs while the administrator is away and prevent unauthorized behaviors.

        Scrot is already installed by default in the latest release of the Raspbian Operating system. In case you already have Scrot, you may skip this installation process. If you're not sure whether it's already installed, use the command below inside a pi Terminal window.

        If your Pi returns a "command not found" error, you must install it. Use the following command line to accomplish this:

        After installing it, you may test its functionality by using the scrot instruction again. If no errors occur, you are set to go on.

        Capturing a snapshot on a Raspberry Pi isn't difficult, especially if Scrot is installed. Here are a handful of options for completing the work.

        1. Using a Keyboard Hotkey

        If you have the Scrot installed on your Pi successfully, your default hotkey for taking screenshots will be the Print Screen key.

        You can try this quickly by pressing the Print Screen button and checking the /home/pi directory. If you find the screenshots taken, your keyboard hotkey (keyboard shortcut) is working correctly.

        In addition, screenshots and print screen pictures will be stored with the suffix _scrot attached to the end of their filename. For instance,

        1. Using Terminal Window

        This is easy as pie! Execute the following command on your Pi to snap a screenshot:

        That is all. It is that easy.

        Taking a Delayed Screenshot

        The following approach will not work unless you have the navigation closed and have to snap a screenshot without the menu. To get a perfect snapshot with no menu, you must wait a few seconds after taking the picture. You may then close your menu and allow the Scrot to initiate the image capture.

        To capture in this manner, send the following command to postpone the operation for five seconds.

        Other Scrot settings are as follows:

        • scrot -b : for taking a window's border.
        • scrot -e : To issue a command after taking a snapshot.
        • scrot -h : To bring up an additional assistance panel.
        • scrot -t : To generate a snapshot thumbnail.
        • scrot -u : To take a screenshot of the currently active tab.
        • scrot -v : Scrot's most recent version will be displayed.

        Changing Screenshot Saving Location

        You might need to give the images a unique name and directory on occasion. Add the correct root directory, followed by the individual title and filename extension, exactly after scrot.

        For instance, if you prefer to assign the title raspberryexpert to it and store it in the downloads directory, do the following command:

        Remember that the extension should always follow the file name .png.

        Mapping the Screenshot Command to a Hotkey

        If the capture command isn't already mapped as a hotkey, you'll have to map it by altering your Pi's config file, and it'll come in handy.

        It would be best if you defined a hotkey inside the lxde-pi-rc.xml script to use it. To proceed, use this syntax to open the script.

        We'll briefly demonstrate how to add the snapshot hotkey to the XML script. It would be best to locate the <keyboard> section and put the following lines directly below it.

        We will map the scrot function to the snapshot hotkeys on the keyboard by typing the above lines.

        Save the script by hitting CTRL X, Yes, and afterward ENTER key when you've successfully added those lines.

        Enter the command below to identify the new changes made.

        How to Take a Screenshot Remotely over SSH

        You may discover that taking snapshots on the raspberry is impractical in some situations. You'll need to use SSH to take the image here.

        When dealing with Ssh, you must first activate it, as is customary. You may get more information about this in our previous tutorials.

        Log in with the command below after you have enabled SSH:

        Now use the command below to snap an image.

        If you've previously installed the Scrot, skip line 2.

        Using the command below, you can snap as many snapshots as you like using varying names and afterward transferring them over to your desktop:

        Remember to change the syntax to reflect the correct username and Ip.

        Saving the Screenshot Directly on your Computer

        you can snap a screenshot and save it immediately to your Linux PC. However, if you regularly have to take snapshots, inputting the passcode each time you access the Rpi via SSH will be a tedious chore. So you can use publicly or privately keys to configure no passcode ssh in raspberry pi.

        To proceed, use the following command to install maim on raspberry pi.

        Return to your computer and use the command below to take a snapshot.

        We're utilizing the maim instead of other approaches since it's a more elegant method. It sends the image to stdout, allowing us to save it to our laptop via a simple URL redirect.

        Taking Screenshots Using Raspi2png

        Raspi2png is a screenshot software that you may use to take a screenshot. Use the code below for downloading and installing the scripts.

        After that, please place it in the /usr/local/bin directory.

        Enter the following command to capture a screenshot.

        Ensure to use your actual folder name rather than <directory_name> used.

        Taking Screenshots Using GNOME Tool

        Because we are using a GUI, this solution is relatively simple and easy to implement.

        First, use the following command to download the GNOME Snapshot tool.

        After it has been installed, go to the Raspberry navbar, select the menu, select Accessories, and finally, Screenshot.

        This opens the GNOME Picture window, where you can find three different taking options, as seen below.

        Choose the appropriate capture method and select Capture Image. If you pick the third choice, you will have to use a mouse to choose the location you wish to snip. If you use this option, you will not need a picture editor to resize the snapshot image. The first choice will record the entire screen, while the second will snip the active window.

        GNOME gives you two alternatives once you capture a screen. The first is to save the snapshot, and the other is to copy it to the clipboard. So select it based on your requirements.

        What are the Different Types of Screenshots to know?

        1. Screenshot

        It all begins with a simple screenshot. You don't need any additional programs or software to capture a basic screenshot. At this moment, this feature is built into almost all Raspberry Pi versions and Windows, Mac PCs, and cellphones.

        1. Screen capture

        It is the process of capturing all or a part of the active screen and converting it to a picture or video.

        While it may appear the same thing as a screenshot and a screen capture, they are not the same. A screenshot is simply a static picture. A desktop window capture is a process of collecting something on the screen, such as photographs or films.

        Assume you wish to save a whole spreadsheet. It's becoming a little more complicated now.

        Generally, you would be able to record whatever is on your window. Still, in case you need to snip anything beyond that, such as broad, horizontal spreadsheets or indefinitely lengthy website pages, you'll need to get a screen capture application designed for that purpose. Snagit includes Scrolling snapshot and Panorama Capture capabilities to snap all of the material you need in a single picture rather than stitching together many images.

        1. Animated GIF

        This is a GIF file containing a moving image. An animated succession of picture frames is exhibited.

        While gif Images aren't limited to screen material, they may be a proper (and underappreciated) method to express what's on your display.

        Instead of capturing multiple pictures to demonstrate a process to a person, you may create a single animated Version of what is going on on your computer. These animations have small file sizes, and they play automatically, making them quick and simple to publish on websites and in documents.

        1. Screencast

        This is making a video out of screen material to educate a program or sell a product by displaying functionality.

        If you want to go further than a simple snapshot or even gif Animation, they are a good option. If you have ever looked for help with a software program, you have come across a screencast.

        They display your screen and generally contain some commentary to make you understand what you are viewing.

        Screencasts can range from polished movies used among professional educators to fast recordings showing a coworker how to file a ticket to Information technology. The concept is all the same.

        Three reasons Why Screenshot tool is vital at work

        1. Communicate Effectively

        Using screenshots to communicate removes the guesswork from graphical presentations and saves time.

        The snapshot tool is ideal for capturing screenshots of graphical designs, new websites, or social media posts pending approval.

        1. Demonstrate to Save Time

        This is a must-have tool for anybody working in Information Technology, human resource, or supervisors training new workers. Choose screenshots over lengthy emails, or print screen pictures with instructions. A snapshot may save you a lot of time and improve team communication.

        Furthermore, by preserving the snapshot in Screencast-O-Matic, your staff will be able to retrieve your directions at any time via a shareable link.

        To avoid confusion, utilize screen captures to show. IT supervisors, for instance, can utilize images to teach their colleagues where to obtain computer upgrades. Take a snapshot of the system icon on your desktop, then use the Screen capture Editor to convert your screen capture into a graphical how-to instruction.

        Any image editing tool may be used to improve pictures. You may use the highlighting tool to draw attention to the location of the icons.

        1. Problem Solve and Share

        Everybody has encountered computer difficulties. However, if you can't articulate exactly what has happened, diagnosing the problem afterward will be challenging. It's simple to capture a snapshot of the issue.

        This is useful when talking with customer service representatives. Rather than discussing the issue, email them an image to help them see it. Publish your image immediately to Screencast and obtain a URL to share it. Sharing photos might help you get help quickly.

        It can also help customer support personnel and their interactions with users. They may assist consumers more quickly by sending screenshots or photographs to assist them in resolving difficulties.

        Snapshots are a simple method for social media administrators to categorize, emphasize, or record a specific moment. Pictures are an easy method to keep track of shifting stats or troublesome followers. It might be challenging to track down subscribers who breach social network regulations. Comments and users are frequently lost in ever-expanding discussions.

        Take a snapshot of the problem to document it. Save this image as a file or store it in the screenshots folder of Screencast. Even if people remove their remarks, you will have proof of inappropriate activity.

        Conclusion

        This tutorial taught us how to take screenshots from a Raspberry Pi using different methods. We also went through how to remotely take snapshots on our Pi using SSH and discussed some of the benefits of using the screenshot tool. However, In the following tutorial, we will learn how to use a raspberry pi as a webserver.

        Voice Control Project using Raspberry Pi 4

        Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to make a button-controlled "music box" that plays different sounds depending on which buttons are pressed. In this lesson, we will configure our raspberry pi for voice control.

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

        What will you learn?

        Like the Amazon Echo, voice-activated gadgets are becoming increasingly popular, but you can also construct your own with a Raspberry, a cheap USB mic, and some appropriate software. Simply speaking to your Raspberry Pi will allow you to search YouTube, view websites, activate applications, and even answer inquiries.

        What will you need?

        Because the Raspberry Pi lacks a soundcard or audio port, this project requires a USB microphone or a camera with a built-in microphone. If your mic only has an audio jack, look for an affordable USB soundcard that connects to a USB port on one side and has a headphone and mic output on the other.

        Getting started

        For the Raspberry Pi, there are various speech recognition programs. We're utilizing Steve Hickson's Pi AUI Toolkit for this project since it is powerful and straightforward to set up and operate. You may install a variety of programs using the Pi AUI Suite. The first question is whether or not the dependencies should be installed. These are the files that the Raspberry Pi requires to work with voice commands, so pick Yes, then press Enter to agree.

        Following that, you'll be asked if you wish to download the PlayVideo software, which allows you to open and play video content using voice commands. If you select Y, you'll be prompted to enter the location of your media files, such as /home/pi/Videos. It's worth noting the upper-case letters are crucial in this scenario. The application will tell you if the route is incorrect.

        Next, you'll be asked if you wish to download the Downloader application, which explores the internet for files and downloads them for you automatically. If you select Yes, you will be prompted to enter an address, port, password, and username. If you're not sure, press Return to choose the default settings in each scenario for now.

        Install the Google Texts to Speech Service if you require your raspberry pi to read the contents of the text files. Since it communicates to Google servers to translate text into speech, the Raspberry Pi must be hooked up to the internet to utilize this service.

        You'll require a google user account to install this. The installation requests your username—press Return after completing this step. The Google password is then requested. Return to the previous page and type this.

        You may also use the installer to download Google Voice Commands. This makes use of Google's speech-to-text technology. To proceed, you must enter your Google login and password once again.

        Regardless of whether you choose Google-specific software or not, the program will ask if you wish to download the YouTube scripts. These technologies allow you to say something like "play pi tutorial," An appropriate video clip will be played—press Return after typing a new welcome. You can also enable the silent flag to prevent the Raspberry Pi from responding verbally.

        Lastly, the software installs the Voice command, which includes some of the more helpful scripts, such as the ability to deploy your internet browser by simply saying "internet."

        Basic voice commands used

        Youtube: When you say "YouTube" followed by a title tag, a youtube clip of the first related YouTube clip appears. "I'm feeling lucky" is comparable to "I'm feeling lucky" on google. Say "YouTube" followed by the title of the video you want to watch, for example, "YouTube fluffy kittens."

        Internet: Your internet browser is launched when you use the word "internet." Midori is the internet browser for Rpi by default, but you may alter that.

        Download: When you say "download," followed by a search query, the Pirate Bay webpage searches for the files in demand. For instance, you can say "Download Into the badlands" to get the most current edition of the movie.

        Play: This phrase utilizes the in-built media player to open an audio or video file. For instance, "Play football.mp4" would play the file "football.mp4" from the media directory you chose during setup, like /home/pi/movies.

        Show me: When you say "show me," a directory of your choice appears. The command defaults to not going to a valid root directory, so you'll need to modify your configuration so that it points to one. For instance, show me==/Documents.

        You'll be asked if you want the Voice command to set things up automatically. If an issue occurs at this point, run the following command to download and install the required software.

        Configuring the Raspberry Pi master voice

        After installing the Voice command application, you may want to perform a few basic adjustments to the setup to fine-tune it. Execute the following command from your Raspberry Pi's Terminal or via SSH.

        Following that, you'll be asked several yes/no questions. The first question is whether you wish to enable the continuous flag permanently. The Voice command application, in clear English, asks if you would want to listen to your voice commands constantly every time you launch it.

        For the time being, choose Yes. After that, you'll be asked if you wish the Voice command application to set the verify flag permanently. If you select Y, the application will expect you to pronounce your keyword (the default setting is "Pi") before responding to requests.

        If you like the RPi to monitor continually but not act on all words you say, this is a good option.

        The next step asks if you wish to enable the ignore flag permanently. If Voice command receives a command that isn't expressly listed in the config file, it will try to find and launch a program from your installed apps. For example, if you say "leafpad," a notepad tool, the Voice command looks for it and starts it even if you don't tell it to.

        This is a functionality that we would not recommend anyone to enable. Because you're using Voice command at the SuperUser level, there's a significant danger that you'll accidentally issue a command to the Raspberry Pi that will harm your files. If you wish to set up other programs to function with the Voice command, you can update the configuration file for each scenario.

        The voice command afterward asks if you want to permanently enable the silence flag so that it doesn't respond verbally whenever you talk. As you see fit, select yes or no. After that, you'll be prompted to adjust the default voice recognition timeframe. If Pi is having problems hearing your commands, you should modify this.

        If you select Yes, you'll be prompted to enter a number; this is the number of seconds that the Raspberry Pi will listen for a voice command; the default for RPI is 3. The application then allows you to customize your text-to-speech choices. Before you do this, make sure your volume is turned up. The application attempts to speak something and then asks if you heard it.

        When the system receives your keyword, it responds with "Yes, sir?" as the default response. To modify this, select Yes in the following prompt, then enter your chosen response, for example, "Yes, ma'am?" Once you're finished, hit the enter key. The program will replay the assigned response to check that you are satisfied with the outcome.

        Whenever the program receives an unidentified command, the method is the same as the default response. "Received the wrong command" is set as the default response, but you could still alter it to something more friendly by typing yes, then your desired response, like, "The command is not known."

        You now have the option of configuring the voice recognition parameters. This will check to see if you have a suitable mic. The Pi will then ask you if you want it to test your sound threshold using the Voice command.

        Check for background sound, then press Yes, then press enter key. It then requests you to say a command to ensure that it is using the correct audio device. Type Yes to have the application automatically select the appropriate audio threshold for your Rpi.

        Lastly, the Raspberry Pi will ask if you wish to modify the default voice command term ("Pi"). After that, type Y and your new keyword, then press enter when you're finished.

        After that, you'll be requested to say your keyword to acclimate the RPi to your voice. If everything looks good, press Y to finish the setup. Start with the fundamental commands outlined above when using the Voice command software.

        Once you've mastered these commands, use the following line of code to exit the application and, if desired, change your config file.

        Vexing sounds and how to get rid of them

        The Raspberry Pi's technology is still a work-in-progress, so not everything you speak may be recognized by the program.

        Stay near the mic and talk slowly and clearly to maximize your chances of being heard by the program if you still have difficulties understanding. Launch the terminal or log in through SSH to your Raspberry Pi and type the following command to access your audio settings to change your audio preferences.

        Hit the F4 button on the keyboard to select audio input, then the F6 key to exit. Select your input device, the mic with the arrow up or down keys, then press Enter key. To change the mic's volume, push it up using the up-arrow key to maximum (100).

        If your device isn't identified at all, it may require more current than a universal serial bus port on a Raspberry Pi can supply. A powered universal serial bus hub is the ideal solution for this.

         

        If you have difficulty connecting after installing the Download application, please ensure that connection to The Pirate Bay site is not limited.

        To download the files, you'll also require a BitTorrent application for your RPi, such as transmission. To install this, launch your terminal or access your RPi through SSH and type the following command:

        The Transmission homepage has instructions about getting started and utilizing the application. You should always download files that have permission from the copyright holder.

        Please remember that whatever you speak and any text documents you provide are transferred to Google servers for translation if you use Google text or speech Commands.

        Google maintains that none of this information is kept on its servers. Even if this is the case, any data communicated through the worldwide web can be decrypted by any skilled third party or a hacker. Google, however, encrypts your connection to minimize the risk of this happening.

        If you like this voice command tool, you might want the program to launch automatically every time the Rpi is powered on. If this is the case, launch the terminal from your RPi or access it via SSH and execute the command below:

        The above command opens the script that controls which programs run whenever your Raspberry Pi is booted. By default, this script is doing nothing. Type the following line of code directly above the one reading exit 0:

        To save any changes, use Ctrl+X, enter yes, and press enter key. At this point, you can restart the Raspberry Pi to ensure that it is working.

        Launch your Rpi terminal, type the command below, and press enter to see a list of active processes.

        How can we reduce vexing noise?

        Noise from air conditioners and heaters can damage your audio and make it impossible for the program to understand what you're saying. The only other alternative is to turn these systems off during recording unless the entire system is redesigned to be more acoustically friendly. However, upon listening to the audio, it becomes clear and annoying.

        Computer hardware cooling fans are also sources of mechanical noise. These can be disabled manually and for a limited period. Besides that, try isolating the disturbance in another space or utilizing an isolation box as an alternative.

        Conclusion

        We learned how to configure our raspberry pi for voice control. We also looked at a few basic commands used to control the raspberry pi and the software used. However, In the following tutorial, we will learn how to tweet on Raspberry pi.

        Build a GPIO Soundboard in Raspberry Pi 4

        Welcome to the next tutorial of our Raspberry Pi programming course. In our previous tutorial, we learned how to create a timelapse video with still images and understand how phototimer and FFmpeg work. In this lesson, you'll make a button-controlled "music box" that plays different sounds depending on which buttons are pressed.

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

        What you will learn

        Connect button pushes to function calls using the Python gpiozero package and uses the Python dictionary data structure

        Components

        • Raspberry Pi
        • Breadboard
        • Buttons
        • Jumper wires
        • Speaker

        Set up your project

        For this project, you'll need some audio samples. On Raspbian, there are many audio files; however, playing them with Python can be challenging. You can, however, transform the audio files to a more simply used format for Python.

        Please make a new folder and rename it because all of your project files will be saved in the new location.

        Copy the sample sounds

        Create a new folder named samples using the same technique as before in your new folder.

        In /usr/share/sonic-pi/sample, you'll find a bunch of sample sounds. These sounds will be copied into the samples folder in the following phase.

        Open the command window by selecting the icon in the upper left corner of your screen.

        To transfer all items from one folder to another, execute the following lines:

        You should now see all the .flac audio files inside the sample folder.

        Convert the sound files

        To use Python to play sound files, you must first convert them from .flac to .wav format.

        Go to the sample folder inside a terminal.

        How can we converting the media files?

        FFmpeg is a software program that can quickly transcode video files on Raspberry Pi. This comes preloaded on the most recent Raspbian releases.

        You may use this simple command to convert music or movie files format:

        To transform an audio (.wav) to a mp3 format (.mp3), for example, type:

        Running batch operations on a file using bash

        What are batch operations?

        A batch operation is a process for processing or treating a large quantity of material. When creating modest amounts of goods, the batch operation is preferred. Because this procedure provides superior traceability and flexibility, it is highly prevalent in pharmaceutical and specialized chemical manufacturing.

        It's simple to rename a file with bash. For example, you may use the mv command.

        But what if you had a thousand files to rename?

        When you run a script or a series of commands on several files, this is known as a batch operation.

        • Try your first simple batch process with any directory containing a few files. The first thing you should do is try something simple.

        The first step is to notify bash that you wish to work with all the files inside the folder.

        • f will be used to denote each directory listing inside the folder individually.
        • After that, you must instruct bash which operations to perform on each file. The file name should be echoed to standard output in this scenario.

        The dollar symbol indicates that you're referring to f in this case. Finally, inform bash that you're finished.

        If you press enter after each statement, bash will wait until you input done before running the loop; therefore, the command would appear as shown below:

        You might also use a semi-colon to separate the instructions rather than pressing Return after every line.

        How do we manipulate strings?

        The process of processing and analyzing strings is referred to as string manipulation. It entails several processes involving altering and processing strings to utilize and change their data.

        That final command was meaningless, but batch operations can accomplish a lot more. You can use the following command to rename each file.

        • If you run ls in the terminal, you'll notice that all files will be renamed. So, how did it all come together?
        • The first portion of the f inside *.txt instructs bash to do the action on all files ($f) with the.txt extension.
        • The command does mv $f instructs bash to relocate each file. After that, you must tell bash what the new name of the relocated file is. To do so, delete the.txt extension and replace it with .md. Fortunately, bash includes an inherent operator for removing string ends. Please take a look at this sample to understand how it works.
        • At this point, you may add something more to the string's end.

        As a result, the $f percent.txt.MD syntax replaces all.txt strings with .md strings. Use the hash operator instead of the % sign to remove a string from the beginning rather than the end.

        Write the following lines in your terminal. All .flac files will be converted to .wav files, and the old ones will be deleted.

        Based on the Raspberry version you're using, it might take a couple of minutes.

        All of the new.wav files will then be visible inside the sample folder.

        How do we play sounds using python?

        After that, you'll begin writing Python code. You can do this with any code editor or IDE, but Mu is often an excellent option.

        To begin building the components for your musical instrument, you'll need to see if Python will play any of the audio files you've copied.

        To play audio files, import and initialize the pygame library.

        This file should be saved in the gpio-music-box directory.

        Select four audio files to utilize in your composition, such as:

        Then make an object which references an audio file. Give the file a different name. Consider the following case:

        For the following three sounds, create labelled objects.

        Hint

        Because all of your audio files are in the sample folder, the path will be as follows:

        Each audio object should be given a name, for example, cymbal:

        This is how your program should appear:

        Please make a backup of your code and execute it. Then use the .play() function inside the shell from the code editor to play the audio.

        Ensure that the speaker is functional and the volume is cranked up if you don't hear anything.

        Connect your buttons

        Four pushbuttons will be required, each connected to a different GPIO pin.

        There are 26 GPIO pins on a Raspberry Pi. You may use them to transmit on/off pulses to/from electrical components like Led, actuators, and switches.

        The GPIO pins are laid out as below.

        There are extra pins for 3.3 V, 5v, and Grounded connections and a number for each pin.

        Another illustration of the pin placement may be seen here. It also displays some of the unique pins that are available as options.

        A figure with a quick explanation is shown below.

        How can we use a button with a Raspberry Pi?

        One of the basic input components is a button.

        Buttons come in various shapes and sizes, with two or four legs, for example. Flying wire is commonly used to link the two-leg variants to a control system. Four-legged buttons are usually put on a breadboard.

        The illustrations below illustrate how to connect a Raspberry Pi to a button. Pin 17 is indeed the input in both scenarios.

        The breadboard's negative rail may be connected to a single GND, allowing all pushbuttons to share the same grounded rail.

        On the breadboard, attach the four buttons.

        Connect each pushbutton to a GPIO pin with a specific number. You are free to select whatever pin you prefer, but you must recall its number.

        Hint

        Connect one Ground pin to the breadboard's neutral rail. Then connect one of each button's legs to this rail. Finally, connect the remaining buttons' legs to separate GPIO pins.

        Here's a wiring schematic that may be of use. The extra legs of the pushbuttons are connected to Pin 4, pin 17, pin 27, and Pin 10 in this case.

        Play sounds at the press of a button.

        A single pushbutton has been connected to pin 17 in the figure below.

        The button may be used to invoke methods that don't need any arguments:

        First, use Python language and the gpiozero library to configure the button.

        The next step is to design a function with no parameters. This straightforward method prints the phrase Hello in the terminal.

        Finally, build a function-calling trigger.

        You can now see Hello displayed in the terminal each time that button is clicked.

        You may make your function as complicated as you want it to be, and you can also call methods which are part of modules. In this case, hitting the button causes an LED in pin 4 to turn on.

        The application should execute a function like drum.play() whenever the button is pushed.

        However, brackets are not used when using an action (like a button push) to invoke a function

        . The software must call that method whenever the button is pushed, not immediately. All you have to do is use drum.play in this situation.

        First, establish one of the buttons. Ensure to replace the numbers from the example with the ones of the pins you've used.

        Add the following line of code at the end of your script to play the audio whenever the button is pushed:

        Push the button after running the software. If you don't hear the sound, double-check your button's connections.

        Add code to the three remaining buttons to have them play their audio.

        For the second button, you may use the code below.

        How can we improve our script?

        Good code is clear, intelligible, tested, never overly convoluted, and does the task at hand.

        You should be able to run your code with no issues. However, once you have a working prototype, it's typically a good practice to tidy up your code.

        Subsequent stages are entirely optional. If you're satisfied with your writing, leave it alone. Follow the instructions on this page and make your code a little cleaner.

        Instead of creating eight individual objects, you may keep your pushbutton objects and audio in a dictionary. These are, nonetheless, the seven characteristics of good code.

        1. Readability

        If you're writing one-time discard code that no one, including yourself, will have to see in the future, you may write in any way you like. However, the majority of useful software that has been produced has to be updated regularly.

        1. Scalable

        The next important feature of excellent programming is scalability, or the capacity to expand with the demands of your organization. Scalability is primarily concerned with the code's efficiency. Scalable code doesn't always require frequent design changes to maintain performance and resolve various workloads.

        1. Testable

        Last-minute adjustments are unavoidable while developing software. It will be difficult to send new changes through if the code can not be rapidly and automatically tested.

        1. Meet functional requirement

        Every piece of software that is built has a certain goal in mind. For persons familiar with the functionality, a code that adheres to its requirements is simple to understand. As a result, one important characteristic of excellent code is that it meets the functional requirements.

        1. Gracefully fails

        Mistakes and flaws are an inherent element of software development. You can't anticipate every conceivable manufacturing case, no matter how cautious you were during the design process. You should, however, shield your application against the negative effects of such situations.

        1. Extendable

        This is an important feature of excellent coding. A reusable and sustainable code is extendable. You write code and double-check that it works as expected. Extensions and related advances can be added to the feature by modules that require it.

        1. The Code Is Reusable

        For every software application, reusable coding is essential and highly beneficial. It aids in the simplification of your source code and avoids redundancy. Reusable codes save time and are cheaper in the long term.

        Learn how to create simple dictionaries and iterate over them by following the methods below.

        First, establish a dictionary where the Buttons serve as keys and audio as values.

        Whenever the pushbutton is pressed, you can loop through the dictionary to instruct the computer to play the audio:

        Conclusion

        We learned how to make a "music box" with buttons that play sounds depending on which button is pushed in this lesson. We also learnt how to interface our raspberry pi with buttons via the GPIO pins and wrote a python program to control the effects of pressing the buttons. In the following tutorial, we will learn how to perform a voice control on Raspberry pi.

        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