Speech Recognition System Using Raspberry pi 4

Thank you for joining us for yet another session of this series on Raspberry Pi programming. In the preceding tutorial, we created a pi-hole ad blocker for our home network using raspberry pi 4. We also learned how to install pi-hole on raspberry pi four and how to access it in any way with other devices. This tutorial will implement a speech recognition system using raspberry pi and use it in our project. First, we will learn the fundamentals of speech recognition, and then we will build a game that uses the user's voice to play it and discover how it all works with a speech recognition package.

Here, you'll learn:

  • The basics of voice recognition
  • On PyPI, what packages may be found?
  • Utilize the SpeechRecognition package with a wide range of useful features.
Where To Buy?
No.ComponentsDistributorLink To Buy
1Raspberry Pi 4AmazonBuy Now

Components

  • Raspberry pi 4
  • Microphone
 

A Brief Overview of Speech Recognition

Are you curious about how to incorporate speech recognition into a Python program? Well, when it comes to conducting voice recognition in Python, there are a few things you need to know first. I'm not going to overwhelm you with the technical specifics because it would take up an entire book. Things have gone a long way when it comes to modern voice recognition technologies. Several speakers can be recognized and have extensive vocabulary in several languages.

Voice is the first element of speech recognition. A mic and an analog-to-digital converter are required to turn speech into an electronic signal and digital data. The audio can be converted to text using various models once it has been digitized.

Markov models are used in most modern voice recognition programs. It is assumed that audio signals can be reasonably represented as a stationary series when seen over a short timescale.

The audio signals are broken into 10-millisecond chunks in a conventional HMM. Each fragment's spectrogram is converted into a real number called cepstral coefficients. The dimensions of this cepstral might range from 10 to 32, depending on the device's accuracy. These vectors are the end product of the HMM.

Training is required for this calculation because the voice of a phoneme changes based on the source and even within a single utterance by the same person. The most probable word to produce the specified phoneme sequence is determined using a particular algorithm.

This entire process could be computationally costly, as one might expect. Before HMM recognition, feature transformations and dimension reduction methods are employed in many current speech recognition programs. It is also possible to limit an audio input to only those parts which are probable to include speech using voice detectors. As a result, the recognizer does not have to waste time studying sections of the signal that aren't relevant.

Choosing a Speech Recognition Tool

There are a few speech recognition packages in PyPI. There are a few examples:

NLP can discern a user's purpose in some of these programs, which goes beyond simple speech recognition. Several other services are focused on speech-to-text conversion alone, such as Google Cloud-Speech.

SpeechRecognition is the most user-friendly of all the packages.

Voice recognition necessitates audio input, which SpeechRecognition makes a cinch. SpeechRecognition will get you up to speed in minutes rather than requiring you to write your code for connecting mics and interpreting audio files.

Since it wraps a variety of common speech application programming interfaces, this SpeechRecognition package offers a high degree of extensibility. The SpeechRecognition library is a fantastic choice for every Python project because of its flexibility and ease of usage. The APIs it encapsulates may or may not be able to support every feature. For SpeechRecognition to operate in your situation, you'll need to research the various choices.

You've decided to give SpeechRecognition ago, and now you need to get it deployed in your environment.

Speech Recognition Software Installation

Using pip, you may set up Speech Recognition software in the terminal:

$ pip install SpeechRecognition

When you've completed the setup, you should start a command line window and type:

Import speech_recognition as sr

Sr.__version__

Let's leave this window open for now. Soon enough, you'll be able to use it.

If you only need to deal with pre-existing audio recordings, Speech Recognition will work straight out of the box. A few prerequisites are required for some use cases, though. In particular, the PyAudio library must record audio from a mic.

As you continue reading, you'll discover which components you require. For the time being, let's look at the package's fundamentals.

Recognizer Class

The recognizer is at the heart of Speech Recognition's magic.

Naturally, the fundamental function of a Recognizer class is to recognize spoken words and phrases. Each instance has a wide range of options for identifying voice from the input audio.

The process of setting up a Recognizer is straightforward. It's as simple as typing "in your active interpreter window."

sr.Recognizer()

There are seven ways to recognize the voice from input audio by utilizing a distinct application programming interface in each Recognizer class. The following are examples:

Aside from recognizing sphinx(), all the other functions fail to work offline using CMU Sphinx. Internet access is required for the remaining six activities.

This tutorial does not cover all of the capabilities and features of every Application programming interface in detail. Speech Recognition comes with a preset application programming interface key for the Google Speech Application programming interface, allowing you to immediately get up and running with the service. As a result, this tutorial will extensively use the Web Speech Application programming interface. Only the Application programming interface key and the user are required for the remaining six application programming interfaces.

Speech Recognition provides a default application programming interface key for testing reasons only, and Google reserves the right to cancel it at any time. Using the Google Web application programming interface in a production setting is not recommended. There is no method to increase the daily request quota, even if you have a valid application programming interface key. If you learn how to use the Speech Recognition application programming interface today, it will be straightforward to apply to any of your projects.

Whenever a recognize function fails to recognize the voice, it will output an error message. Request Error if the application programming interface is unavailable. A faulty Sphinx install could cause this in the case of recognizing sphinx(). If quotas are exceeded, servers are unreachable, or there isn't internet service, a Request Error will be raised for all the six methods.

Let us use recognize google() in our interpreter window and see if it works!

Exactly what has transpired?

Something like this is most likely what you've gotten.

I'm sure you could have foreseen this. How is it possible to tell something from nothing?

The Recognizer function recognize() expects an audio data parameter. If you're using Speech Recognition, then audio data should become an instance of the audio data class.

To construct an AudioData instance, you have two options: you can either use an audio file or record your audio. We'll begin with audio files because they're simpler to work with.

Using Audio Files

To proceed, you must first obtain and save an audio file. Use the same location where your Python interpreter is running to store the file.

Speech Recognition's AudioFile interface allows us to work with audio files easily. As a context manager, this class gives the ability to access the information of an audio file by providing a path to its location.

File Formats that are supported

This software supports various file formats, which include:

  • WAV
  • AIFF
  • FLAC

You'll need to get a hold of the FLAC command line and a FLAC encoding tool.

Recording data using the record() Function

To play the "har.wav" file, enter the following commands into your interpreter window:

har = sr.AudioFile('har.wav')

with harvard as source:

audio = r.record(source)

Using the AudioFile class source, the context manager stores the data read from the file. Then, using the record() function, the full file's data is saved to an AudioData class. Verify this by looking at the format of the audio:

type(audio)

You can now use recognize_google() to see if any voice can be found in the audio file. You might have to wait a few seconds for the output to appear, based on the speed of your broadband connection.

r.recognize_google(audio)

Congratulations! You've just finished your very first audio transcription!

Within the "har.wav" file, you'll find instances of Har Phrases if you're curious. In 1965, the IEEE issued these phrases to evaluate telephone lines for voice intelligibility. VoIP and telecom testing continue to make use of them nowadays.

Seventy-two lists of 10 phrases are included in the Har Phrases. On the Open Voice Repository webpage, you'll discover a free recording of these words and phrases. Each language has its own set of translations for the recordings. Put your code through its paces; they offer many free resources.

Segments with a start and end time

You may want to record a small section of the speaker's speech. The record() method accepts the duration term parameter, which terminates the program after a defined amount of time.

Using the example above, the first 4 secs of the file will be saved as a transcript.

with har as source:

audio = r.record(source, duration=4)

r.recognize_google(audio)

In the files stream, utilize the record() function within a block. As a result, the 4 secs of audio you recorded for 4 seconds will be returned when you record for 4 seconds again.

with har as source:

audio1 = r.record(source, duration=4)

audio2 = r.record(source, duration=4)

r.recognize_google(audio1)

r.recognize_google(audio2)

As you can see, the 3rd phrase is contained within audio2. When a timeframe is specified, the recorder can cease in the middle of a word. This can harm the transcript. In the meantime, here's what I have to say about this.

The offset keywords arguments can be passed to the record() function combined with a recording period. Before recording, this setting specifies how many frames of a file to disregard.

with har as source:

audio = r.record(source, offset=4, duration=3)

r.recognize_google(audio)

Using the duration and the offset word parameters can help you segment an audio track if you understand the language structure beforehand. They can, however, be misused if used hurriedly. Using the following command in your interpreter should get the desired result.

 

with har as source:

audio = r.record(source, offset=4.7, duration=2.8)

r.recognize_google(audio)

The application programming interface only received "akes heat," which matches "Mesquite," because "it t" half of the sentence was missed.

You also recorded "a co," the first word of the 3rd phrase after the recording. The application programming interface matched this to "Aiko."

Another possible explanation for the inaccuracy of your transcriptions is human error. Noise! Since the audio is relatively clean, the instances mentioned above all worked. Noise-free audio cannot be expected in the actual world except if the soundtracks can be processed in advance.

Noise Can Affect Speech Recognition.

Noise is an unavoidable part of everyday existence. All audiotapes have some noise level, and speech recognition programs can suffer if the noise isn't properly handled.

I listened to the "jackhammer" audio sample to understand how noise can impair speech recognition. Ensure to save it to the root folder of your interpreter session.

The sound of a jackhammer is heard in the background while the words "the stale scent of old beer remains" are spoken.

Try to translate this file and see what unfolds.

jackmer = sr.AudioFile('jackmer.wav')

with jackhammer as source:

audio = r.record(source)

r.recognize_google(audio)

How wrong!

So, how do you go about dealing with this situation? The Recognizer class has an adjust for ambient noise() function you might want to give a shot.

with jackmer as source:

r.adjust_for_ambient_noise(source)

audio = r.record(source)

r.recognize_google(audio)

You're getting closer, but it's still not quite there yet. In addition, the statement's first word is missing: "the." How come?

Recognizer calibration is done by reading the first seconds of the audio stream and adjusting for noise level. As a result, the stream has already been consumed when you run record() to record the data.

Adjusting ambient noise() takes the duration word parameter to change the time frame for analysis. The default value for this parameter is 1, but you can change it to whatever you choose. Reduce this value by half.

with jackmer as a source:

r.adjust_for_ambient_noise(source, duration=0.5)

audio = r.record(source)

r.recognize_google(audio)

Now you've got a whole new set of problems to deal with after getting "the" at the start of the sentence. There are times when the noise can't be removed from the signal because it simply has a lot of noise to cope with. That's the case in this particular file.

These problems may necessitate some sound pre-processing if you encounter them regularly. Audio editing programs, which can add filters to the audio, can be used to accomplish this. For the time being, know that background noise can cause issues and needs to be handled to improve voice recognition accuracy.

Application programming interface responses might be useful whenever working with noisy files. There are various ways to parse the JSON text returned by most application programming interfaces. For the recognize google() function to produce the most accurate transcription, you must explicitly request it.

Using the recognize google() function and the show all boolean argument will do this.

r.recognize_google(audio, show_all=True)

A transcript list can be found in the dictionary returned by recognizing google(), with the entry 'alternative .'This response format varies in different application programming interfaces, but it's primarily useful for debugging purposes when you get it.

As you've seen, the Speech Recognition software has a lot to offer. Aside from gaining expertise with the offsets and duration arguments, you also learned about the harmful effects noise has on transcription accuracy.

The fun is about to begin. Make your project dynamic by using a mic instead of transcribing audio clips that don't require any input from the user.

Using Microphone

For Speech Recognizer to work, you must obtain the PyAudio library.

Install PyAudio

Use the command below to install pyaudio in raspberry pi:

sudo apt-get install python-pyaudio python3-pyaudio

Confirmation of Successful Setup

Using the console, you can verify that PyAudio is working properly.

python -m speech_recognition

Ensure your mic is turned on and unmuted. This is what you'll see if everything went according to plan:

Let SpeechRecognition translate your voice by talking into your mic and discovering its accuracy.

Microphone instance

The recognizer class should be created in a separate interpreter window.

import speech_recognition as sr

r = sr.Recognizer()

After utilizing an audio recording, you'll use the system mic as your input. Instantiation your Microphone interface to get at this information!

mic = sr.Microphone()

For raspberry pi, you must provide a device's index to use a certain mic. For a list of microphones, simply call our Mic class function.

Sr.Microphone.list_microphone_names()

Keep in mind that the results may vary from those shown in the examples.

You may find the mic's device index using the list microphone names function. A mic instance might look like this if you wanted to use the "front" mic, which has a value of Three in the output.

mic = sr.Microphone(device_index=3)

Use listen() to record the audio from the mic

A Mic instance is ready, so let's get started recording.

Similar to AudioFile, Mic serves as a context manager for the application. The listen() function of the Recognizer interface can be used in the with section to record audio from the mic. This technique uses an input source as its initial parameter to capture audio until quiet is invoked.

with mic as source:

audio = r.listen(source)

Try saying "hi" into your mic once you've completed the block. Please be patient as the interpreter prompts reappear. Once you hear the ">>>" prompt again, you should be able to hear the voice.

r.recognize_google(audio)

If the message never appears again, your mic is probably taking up the excessive background noise. Ctrl then C key can halt the execution and restore your prompts.

Recognizer class's adjustment of ambient noise() method must be used to deal with the noise level, much like you did while attempting to decipher the noisy audio track. It's wise to do this whenever you're listening for mic input because it's less unpredictable than audio file sources.

with mic as source:

r.adjust_for_ambient_noise(source)

audio = r.listen(source)

Allow for adjustment of ambient noise() to finish before speaking "hello" into the mic after executing the code mentioned above. Be patient as the interpreter's prompts reappear before ascertaining the speech.

Keep in mind that the audio input is analyzed for a second by adjusting ambient noise(). Using the duration parameter, you can shorten it if necessary.

According to the website, not under 0.5 secs is recommended by the Speech Recognition specification. There are times when greater durations are more effective. The lower the ambient noise, the lower the value you need. Sadly, this knowledge is often left out of the development process. In my opinion, the default one-second duration is sufficient for most purposes.

How to handle speech that isn't recognizable?

Using your interpreter, type in the above code snippet and mutter anything nonsensical into the mic. You may expect a response such as this:

An UnknownValueError exception is thrown if the application programming interface cannot translate speech into text. You must always encapsulate application programming interface requests in try and except statements to address this problem.

Getting the exception thrown may take more effort than you imagine. When it comes to transcribing vocal sounds, the API puts in a lot of time and effort. For me, even the tiniest of noises were translated into words like "how." A cough, claps of the hands, or clicking the tongue would all raise an exception.

A "Guess the Word" game to Put everything together

To put what you've learned from the SpeechRecognition library into practice, develop a simple game that randomly selects a phrase from a set of words and allows the player three tries to guess it.

Listed below are all of the scripts:

import random

import time

import speech_recognition as sr

def recognize_speech_from_mic(recognizer, microphone):

if not isinstance(recognizer, sr.Recognizer):

raise TypeError("`recognizer` must be `Recognizer` instance")

if not isinstance(microphone, sr.Microphone):

raise TypeError("`microphone` must be `Microphone` instance")

with microphone as source:

recognizer.adjust_for_ambient_noise(source)

audio = recognizer.listen(source)

response = {

"success": True,

"error": None,

"transcription": None

}

 

try: response["transcription"] = recognizer.recognize_google(audio)

except sr.RequestError:

response["success"] = False

response["error"] = "API unavailable"

except sr.UnknownValueError:

response["error"] = "Unable to recognize speech"

return response

if __name__ == "__main__":

WORDS = ["apple", "banana", "grape", "orange", "mango", "lemon"]

NUM_GUESSES = 3

PROMPT_LIMIT = 5

recognizer = sr.Recognizer()

microphone = sr.Microphone()

word = random.choice(WORDS)

instructions = (

"I'm thinking of one of these words:\n"

"{words}\n"

"You have {n} tries to guess which one.\n"

).format(words=', '.join(WORDS), n=NUM_GUESSES)

print(instructions)

time.sleep(3)

for i in range(NUM_GUESSES):

for j in range(PROMPT_LIMIT):

print('Guess {}. Speak!'.format(i+1))

guess = recognize_speech_from_mic(recognizer, microphone)

if guess["transcription"]:

break

if not guess["success"]:

break

print("I didn't catch that. What did you say?\n")

if guess["error"]:

print("ERROR: {}".format(guess["error"]))

break

print("You said: {}".format(guess["transcription"]))

guess_is_correct = guess["transcription"].lower() == word.lower()

user_has_more_attempts = i < NUM_GUESSES - 1

if guess_is_correct:

print("Correct! You win!".format(word))

break

elif user_has_more_attempts:

print("Incorrect. Try again.\n")

else:

print("Sorry, you lose!\nI was thinking of '{}'.".format(word))

break

Let's analyze this a little bit further.

There are three keys to this function: Recognizer and Mic. It takes these two as inputs and outputs a dictionary. The "success" value indicates the success or failure of the application programming interface request. It is possible that the 2nd key, "error," is a notification showing that the application programming interface is inaccessible or that a user's speech was incomprehensible. As a final touch, the audio input "transcription" key includes a translation of all of the captured audio.

A TypeError is raised if the recognition system or mic parameters are invalid:

Using the listen() function, the mic's sound is recorded.

For every call to recognize speech from the mic(), the recognizer is re-calibrated using the adjust for ambient noise() technique.

After that, whether there is any voice in the audio, recognize function is invoked to translate it. RequestError and UnknownValueError are caught by the try and except block and dealt with accordingly. Recognition of voice from a microphone returns a dictionary containing the success, error, and translated voice of the application programming interface request and the dictionary keys.

In an interpreter window, execute the following code to see if the function works as expected:

import speech_recognition as sr

from guessing_game import recognize_speech_from_mic

r = sr.Recognizer()

m = sr.Microphone()

recognize_speech_from_mic(r, m)

The actual gameplay is quite basic. An initial set of phrases, a maximum of guesses permitted, and a time restriction are established:

Once this is done, a random phrase is selected from the list of WORDS and input into the Recognizer and Mic instances.

After displaying some directions, the condition statement is utilized to handle each user's attempts at guessing the selected word. This is the first operation that happens inside of the first loop. Another loop tries to identify the person's guesses at least PROMPT LIMIT instances and stores the dictionary provided to a variable guess.

Otherwise, a translation was performed, and the closed-loop will end with a break in case the guess "transcription" value is unknown. False is set as an application programming interface error when no audio is transcribed; this causes the loop to be broken again with a break. Aside from that, the application programming interface request was successful; nonetheless, the speech was unintelligible. As a precaution, the for loop repeatedly warns the user, giving them a second chance to succeed.

If there are any errors inside the guess dictionary, the inner loop will be terminated again. An error notice will be printed, and a break is used to exit the outer for loop, which will stop the program execution.

Transcriptions are checked for accuracy by comparing the entered text to a word drawn at random. As a result, the lower() function for text objects is employed to ensure a more accurate prediction. In this case, it doesn't matter if the application programming interface returns "Apple" or "apple" as the speech matching the phrase "apple."

If the user's estimate was correct, the game is over, and they have won. The outermost loop restarts when a person guesses incorrectly and a fresh guess is found. Otherwise, the user will be eliminated from the contest.

This is what you'll get when you run the program:

Recognition of Other Languages

Speech recognition in other languages, on the other hand, is entirely doable and incredibly simple.

The language parameter must be set to the required string to use the recognize() function in a language other than English.

r = sr.Recognizer()

with sr.AudioFile('path/to/audiofile.wav') as source:

audio = r.record(source)

r.recognize_google(audio, language='fr-FR')

There are only a few methods that accept-language keywords:

What are the applications of speech recognition software?

  1. Mobile Payment with Voice command

Do you ever have second thoughts about how you're going to pay for future purchases? Has it occurred to you that, in the future, you may be able to pay for goods and services simply by speaking? There's a good chance that will happen soon! Several companies are already developing voice commands for money transfers.

This system allows you to speak a one-time passcode rather than entering a passcode before buying the product. When it comes to online security, think of captchas and other one-time passwords that are read aloud. This is a considerably better option than reusing a password every time. Soon, voice-activated mobile banking will be widely used.

  1. AI Assistants

When driving, you may use such Intelligent systems to get navigation, perform a Google search, start a playlist of songs, or even turn on the lights in your home without touching your gadget. These digital assistants are programmed to respond to every voice activation, regardless of the user.

There are new technologies that enable Ai applications to recognize individual users. This tech, for instance, allows it to respond to the voice of a certain person exclusively. Using an iPhone as an example, it's been around for a few years now. If you want Siri to only respond to your commands and queries when you speak to it, you can do so on your iPhone. Unauthorized access to your gadgets, information, and property is far less possible when your voice can only activate your Artificial intelligent assistant. Anyone who is not permitted to use the assistant will not be able to activate it. Other uses for this technology are almost probably on the horizon.

  1. Translation Application

In a distant place, imagine attempting to check into an unfamiliar hotel. Since neither you nor the front desk employee is fluent in the other country's language, no one is available to act as a translator. You can use the translator device to talk into the microphone and have your speech processed and translated verbally or graphically to communicate with another person.

Additionally, this tech can benefit multinational enterprises, educational institutions, or other institutions. You can have a more productive conversation with anyone who doesn't speak your language, which helps break down the linguistic barrier.

Conclusion

There are many ways to use the SpeechRecognition program, including installing it and utilizing its Recognizer interface, which may be used to recognize audio from both files and the mic. You learned how to use the record offset and the duration keywords to extract segments from an audio recording.

The recognizer's tolerance to noise level can be adjusted using the adjust for the ambient noise function, which you've seen in action. Recognizer instances can throw RequestErrors and UnknownValueErrors, and you've learned how to manage them with try and except block.

More can be learned about speech recognition than what you've just read. We will implement the RTC module integration in our upcoming tutorial to enable real-time control.

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.

How to Use a Raspberry pi as a VPN Server

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us how to use a raspberry pi as a DNS server. We also looked at the benefit of this DNS server. This tutorial will teach us to set up Raspberry pi as a VPN server.

This is an excellent method for increasing your network security and getting access to your local area network from the world wide web, but setting up your VPN server might be a challenge. Pi VPN uses a guided install to turn your Raspberry into a low-cost, high-performance VPN server.

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

What is Pi VPN?

It is an OpenVPN server optimized for all Raspberry platforms above pi 2. It allows you to access your home network over the internet safely and securely. Smart devices and your network can be connected via a "bridge" created by connecting a Raspberry Pi to your router.

A virtual private network (VPN) is a secure option if you frequently use your router to forward traffic. Anyone can gain access to your network through any of the ports you forward. For maximum network security, use Pi VPN, which only exposes a single port and employs industry-standard encryption algorithms.

How can we choose a VPN service provider?

Selecting a virtual private network service is critical before you begin this project. It would be best to bear in mind cybersecurity, bandwidth, and delay when making this decision.

Ensure that your Virtual private network supplier doesn't record how you use their services. Nevertheless, speed and delay are critical here.

As a result, we've decided to go with IPVanish in this project. When it comes to network latency and network bandwidth, IPVanish is among the best.

Preparation for Pi VPN

The Raspberry Pi can get the best out of the device with a wired or wireless connection.

Use the Interfacing settings menu to turn on the secure shell service in RPi Settings. The configuration tool can be launched from the Pi menu or with the following command:

Activate the secure shell server and then restart your Pi

You can disconnect your display and switch off your desktop once your Pi hooks to your local network via a secure shell. It's simple to use a program like Putty or the terminal on your Mac to access your RPi.

Connect to the Raspberry Pi

You will not have to use a monitor to manage your Pi virtual private network server. A Raspberry Pi can be accessed from another device using SSH.

Use the ifconfig command to display your Raspberry IP address before unplugging it from the monitor.

If you configure your Raspberry Pi VPN server on Windows, you should use Putty.

Login to the RPi using the Internet protocol address noted earlier when Putty runs. Check to see if the secure shell is for the connection type. To save this connection to your profile, click the Save button.

You don't need a secure shell client if you're using a Macintosh or Linux computer to install Pi VPN. SSH is in your operating system's terminal, so you don't need to do anything extra.

A security key is saved on your Raspberry Pi the first time you access the raspberry pi. Accept the key and store it on your computer by pressing the Yes option on the screen.

Your password must be entered next. You'll be logged in as Raspberry Pi as long as you haven't changed the default password on your Raspberry

The prompt pi@hostname shows a successful login.

Update Raspbian for Pi VPN

Begin by obtaining a list of the most recent applications. Using the command: you can see if any installed programs are up to date.

Set a static IP address

When it comes to network services, you will have to locate your RPi, implying that you will set up a static Ip before you begin using the app. Also, modify your hostname at this point. When you get access, you'll notice a difference in the prompt. It's a simple way to distinguish between several Pis, but you can always change your hostname.

To establish a static Ip, you'll have to update the configuration file /etc/dhcpcd.conf. Before opening the file, know your router's Internet protocol address and Domain name system. This data is available using the ifconfig utility.

Take advantage of this command when you're ready to edit its config script:

To find an example of static IP configuration, look for the line with the label Sample static IP config inside the file. Simply remove the example comments and replace your Ip, routers, and gateway with your own to get started.

If you prefer a static IP address, remove the comment from it and replace it with the desired value.

Your custom values should be provided for static IP and DNS.

To alter your hostname, run the command below as superuser to open /etc/hostname in nano:

When finished, use Ctrl+X to close the editor. Then, press Yes to save the changes.

The /etc/hosts file must be edited in the same way. The file editing command is:

Change your hostname from 127.0.0.1 to whatever you've selected. Use the command below to force a reboot of your Raspberry Pi:

You should always change your connection's IP address after restarting your Raspberry Pi to reflect its new static address.

How can we figure out Raspbian’s firewall?

In Linux distributions, firewalls are embedded in kernels and will activate by default in Raspbian. The default setting for a new installation is to leave it unlocked.

There are no restrictions on inbound or outbound packets, and the firewall forwards any requests. Before securing the firewall, make sure it is entirely accessible.

Use iptables -L to see if your firewall protocols match. It's possible to return the firewall to its default settings using the following commands:

Choose an encryption

During configuring the Raspberry virtual private network, you will select the level of encryption. What you need to remember is the following:

  • Generally, 2048-bit encryption is the best for download and streaming. However, 4096-bit is ideal for emailing and browsing, giving better security.

Allowing 4096-bit is enticing for those who stream film or music; however, it will add a significant amount of overhead and slows down your connection significantly. For the most part, we use 2048-bit encryption, which is the industry standard.

Timing out during lengthy procedures

You'll inevitably stumble across a peculiarity in a secure shell. For more prolonged operations, if you are using SSH to communicate with the Raspberry, the connection is lost whenever the desktop hibernates. Any pi commands running stop working whenever a secure shell connection is lost; therefore, you must re-enter it.

A screen is an excellent tool for dealing with long SSH processes. One task might be the only focus of your screen sessions. Afterwards, you'll be able to join and disconnect at will and return to your session to see how it progresses.

Once Screen installs, you will need only a handful of commands to get the most out of it. Use apt to install screen utility as a starting point:

Once Screen installs, run it by typing the following command into your terminal window:

Even if nothing has changed, the commands you issue will continue to run even if you disconnect.

Whenever your Raspberry Pi connection stops, simply re-SSH in and type:

If only one secure shell session is open, you'll immediately get reconnected.

Installing Pi, the virtual private network

The Pi VPN works once you have your Raspberry working. It's the first step in a multi-part installation that will grant you access to Pi's virtual private network backend capability. Setting up an outgoing virtual private network tunnel connection for privacy will be done in the following steps.

Launch the installer

Configure the Pi VPN via a command-line utility called curl, which you download from the company's website. You don't even need a browser to use curl to download from the internet.

Pi VPN installs using the following command:

You can obtain the installation package and feed it into bash for execution using this command.

Instantly, the procedure of installation begins. It begins by scanning for any packages that need updating on your system. Your system should be the latest version

to proceed.

Launch the pi VPN installation after meeting a few pre-requisites.

The Pi VPN installer

To get the most out of your SSH session, you should use the Pi Virtual private network Installer. We can get started when the Screen changes colour to blue, and an installer notification appears.

Start by pressing Enter to begin the VPN setup procedure.

Static IP addresses are required, and in case you do not have any, you will get a notice. If you have not already done so, head back to the previous section and finish configuring a static IP address.

The Ip that Raspberry Virtual private network detects displays to you. Click the Yes if it is correct.

IP address conflicts display for your attention. Static IP addresses outside the dynamic host configuration protocol range are the safest method of avoiding conflicts with other devices on your network.

To continue, simply press the OK button.

Set the raspberry user, then click the OK to proceed with installing your preferred software.

If you want your Raspberry virtual private network server to get automatic security upgrades, you should select Yes when prompted. Because port forwarding makes your Pi vulnerable to the internet, Pi VPN must be updated.

Make sure you conduct frequent updates manually if you select "No."

After activating automatic updates, it's usual to see the console for some time. You can expect another installation attempt in the next few seconds.

You'll want to use the UDP protocol while setting up a Pi VPN for most circumstances. If you're going to use a VPN subscription service to establish a highly secure two-hop connection, stick with TCP instead of UDP.

The default port you're using for the virtual private network will come in handy later.

UDP uses port 1194 by default, whereas TCP uses port 443. Do not use port 443 when configuring the double-hop virtual private network because it will end up causing a conflict afterwards. Instead, we use TCP port 4430.

Set up an encryption

Select the encryption type you want at this point. Earlier, we explained why you might choose each option and why you should do so. If you're still undecided, refer back to what we discussed.

Using the space bar, choose the encryption you want to employ and press OK. Streaming video is only possible with 2048-bit encryption.

It may take some time to generate these keys. It will take significantly longer if you're encrypting at a high level. Wait for Pi VPN to produce your server keys.

Installing the final piece

The Raspberry Virtual private network setup procedure is nearly complete once the server key generates. After a few more stages, you'll be able to establish a connection.

If you do not have a domain Name system account, choose the public IP. In this case, we will need to input your hostname and domain name system account settings as usual if we are using a Dynamic domain name system.

You will need to select a domain name server provider for your virtual private network. Google is recommended to most people because it is free and straightforward. If you're concerned about DNS leakages, OpenDNS offers safe DNS solutions. If you plan to use Pi-hole to handle DNS requests, you may want to select Custom.

The installation will guide you through the process of adding additional users using the command line. Install a web app for managing users in the following phase. Additionally, pivpn add is an option.

Select Yes and restart your Raspberry Pi.

Setup of the Pi Virtual private network GUI

There is a Pi Virtual private network Graphical interface for Pi VPN. Using it simplifies the process of adding new devices and users.

When you add a new user to the VPN, a *.ovpn profile generates. In addition to creating a user account, you may efficiently utilize the Pi Virtual private network GUI to download the profiles.

If you don't want to utilize the Pi Virtual private network GUI, you can use the following to add or delete users.

Preparing to install the GUI for Pi VPN

Adding a repository is necessary if you want the Pi VPN GUI's required software to be easily accessible. Let me show you how.

Edit apt's source list with nano. The directive is:

Add the lines below to the sources. Make a list of everything you can find:

This will inform apt that Raspberry can install packages. Debian stretch repositories do not currently contain some of the required third-party software Pi Virtual private network GUI uses.

It's not good to include a link to a previous build in the sources.list script, even though we currently need it. Once additional software installs, it may interfere with it. Once these software packages install, you can delete the line in the sources.list you just added.

Next, save the changes and exit the Nano application. Then update with the command below:

Once the check is complete, use the following command to install any new or updated packages:

All you have to do now is tell apt about the new repository. The Pi VPN Graphical interface pre-requisites can now install using the command:

When prompted, select "YES" and allow the setup to begin. Before using the Pi Virtual private network GUI, you must change some config files.

Make sure all of your pre-requisite software install before running the apt update.

Updating the web configuration

The Pi Virtual private network GUI relies on an apache server to function effectively as a web application. However, we need to make a few adjustments before the Pi Virtual private network GUI start operating.

To begin, modify the user’s account under which apache executes. It runs as an unsupported account by default; therefore, we need to change it to the user pi. Use the following command to make changes to the Apache configuration file:

Find the line with $(APACHE RUN USER)

To exit and save, use Ctrl+X.

You'll also want to give yourself complete control over the /var directory, where Apache stores all of its web pages. Use the following command to grant pi complete control over the webroot directory:

Run the following command to move to the /var/www/HTML folder:

The raspberry pi should install the Pi Virtual private network Interface from that location.

Obtaining and installing the GUI for Pi VPN

After troubleshooting, downloading and installing the raspberry virtual private network graphical user interface is a breeze. You only need to use git to check out the project. You've already installed the git software if you've been following along.

Then run the following command from the HTML folder.

The command below will utilize git to copy the Pi Virtual private network GUI project folder into the directory of your apache server so that it is accessible as a web page. With a quick check-in of your browser, you can verify that the installation went smoothly.

Connect to Pi virtual private network GUI

You can now launch the Pi Virtual private network GUI from your internet browser and manage Pi Virtual private network users.

Use the Internet address that matches your setup and launch the Pi Virtual private network GUI from your internet browser.

Once a login screen appears, you've successfully connected to the network. For the time being, simply save a link to the Pi Virtual private network GUI for quick access. Setting up an outgoing VPN connection is the next step in protecting your online activity. If you don't want to utilize IPVanish, you may set up your router and add users without signing up for anything.

Establish outbound virtual private network connection

In the absence of an outbound Virtual private network, all traffic from all connected devices will use the public IP address of the local network to reach the worldwide web. The websites think that you are in the home network whenever you are connected. For example, you may wish to watch Netflix while away from home.

We recommend creating a "double-hop" connection with a VPN service outside the Pi virtual private network for the best results.

VPN connections with two hops allow for complete encryption whenever you access a site using HTTPS. Since the outgoing virtual private network server never notices the request source, the additional security offered by using two tunnels goes far beyond standard Virtual private network solutions.

If your Vpn service provider retains logs, they will not identify the devices from which each specific request was made. This additional layer of anonymity further obscures anything you do online.

Do not bother with this step if all you need is remote access to your local network via Pi's virtual private network. In contrast, if you're looking for safe and anonymous internet access for your mobile device, you can use an outgoing virtual private network connection and Raspberry virtual private network.

Outbound VPN with IPVanish

Due to its low latency, IPVanish is an excellent choice for establishing a double-hop virtual private network connection, requiring two separate virtual private network servers. Any OpenVPN profile-publishing VPN service will follow the same procedure.

Your VPN service's digital certificate and an autologin profile can be obtained below.

SSH onto your Raspberry Pi VPN server, then use wget to obtain the resources you need from the internet. Take a look at your Pi Virtual private network server and ensure it is online before using these instructions to obtain the data you require:

If you want to access the IPVanish server, you'll need to alter the uniform resource locator in the second field.

Make sure you rename the *.ovpn to use the OpenVPN service when connecting to IPVanish. Only profiles ending in *.conf can be connected to the network. Change the name of the file with the command below to outgoing.conf:

Establish the IPVanish connection

You can easily track two concurrent virtual private connections by renaming each interface.

The connection names will not change to or from between the two interfaces when renaming interfaces. To effectively configure your firewall, you must know the device's name.

If you go into the connection settings for each interface, you can modify the name. There is a *.config file for each OpenVPN connection linked with it. By altering the first few lines of each file, you can rename the network's graphical user interface.

To begin, run the command below to edit the Pi Virtual private network settings:

You should change the first line to:

Add a new line to the following:

Save your modifications by pressing Ctrl+X, then Y. /dev/tun-incoming will be created the next time the Pi Virtual private network is online.

Also, edit the OpenVPN outgoing configuration file.

Modify the first statement and add another at the start of the configuration file like before. In this case, the text should be as follows:

In addition, the outbound Virtual private network will need to be updated as well. Enter your name and password so that the Virtual private network can immediately connect to the server's cert you obtained in the previous stage.

To use the IPVanish server SSL certificate, make the necessary changes to the outgoing.conf file. Replace the word ca with:

Please use the following command to direct IPVanish to the password file we will create shortly: auth-user-pass

In addition, you must instruct your outbound virtual private network connection not to relay Local traffic. Your outgoing.conf file must have the following line added to it to allow access via Pi virtual private network to your home network:

Password files are now generated for use with IPVanish by OpenVPN.

Click Ctrl + X followed by the key to save the changes after entering your password and email address. You should encrypt the file because it holds your login details. With chmod, you can prevent anyone from accessing the password file in the OpenVPN configuration directory:

The root user can modify the password script file, which is the bare minimum level of protection required when keeping your login information in the clear text form.

Update the routing table of the Raspberry Pi

Your Rpi should be configured correctly for the outgoing Virtual private network to encrypt your internet connection. The static IP address of your Raspberry Pi must be substituted if it is different.

You'll need to update or generate the file below and add some lines. The command is as follows:

Include the following two lines in your script:

We require only one change to the routing table of your Raspberry Pi. We can use incoming and outbound VPN connections simultaneously when you save the adjustments and restart your Raspberry Pi computer.

Keep your DNS requests safe and secure

To ensure that your connection is genuinely safe, you must prevent DNS leaks. Using a Domain name server that isn't part of your virtual private network encrypted network results in a Domain name server leaks. For example, domain name server login and perform a man in the middle attack on your Virtual private network customers.

Forcing all incoming Virtual private network users to utilize the safe Domain name server from your outbound Vpn service provider is the solution.

OpenVPN config file is updated to change your domain name server without reinstalling the Pi Virtual private network. Use the following command to open the config file for editing:

The lines that send the Domain name server to your virtual private network clients are found by scrolling in the file.

When utilizing IPVanish, you need to replace these lines:

To identify the Domain name servers of a different Virtual private network, you'll need to research online. Save the file after editing it. As soon as the OpenVPN server starts up, your Virtual private network clients will connect automatically to secured servers provided by IPVanish.

Connect to IPVanish

OpenVPN should not connect automatically to the outbound virtual private network provider unless the connection is tested and verified. Type the following into the Run window:

The virtual private network connection status displays in the text on your screen. If you're having trouble connecting, double-check the outgoing configuration file and ensure your user information is in the password file on different lines. Hit Ctrl + C to exit the VPN once you've established a connection.

How can we connect to the virtual private network automatically?

After the connection is tested and found to be working, you should automate the startup for your VPN tunnel. You can connect to every connection using OpenVPN by its configuration file name.

This command will edit the OpenVPN global config file, which you'll need to begin.

Undo this line's comments.

Change it to:

Afterwards, save your modifications and reboot your Raspberry virtual private network server:

Pi VPN router settings

A virtual private network is a tunnel from the wide-area network to the local area network. Consequently, your router must be configured to accept specific connections. If you have a router that doesn't support port forwarding, you may have to perform this manually.

VPN port forwarding

If you didn't specify a port forward before, no Virtual private network clients would be able to access the network. We have to apply an exception to the security of our router's policies to allow these requests.

To access your router, copy its Internet address into your internet browser.

After logging in, go through the menus and select it from the list to enable port forwarding.

You'll have to remember the port number you previously chose in this process. Additionally, you'll need to know the static IP of your Raspberry Virtual private network server.

When you've completed port forwarding, click Save. VPN users can now access their accounts even if they are not in the local network.

Conclusion

This tutorial taught us to set up Raspberry pi as a virtual private network server. We also learned how to set up port forwarding and improve our network security. In the following tutorial, we will learn how to use a raspberry pi as a DNS server.

How to Use a Raspberry Pi as A Media Server

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to set up a webserver in raspberry pi. We also looked at configuring addclient and deploying apps to our repositories. This tutorial will teach us to set up a free media server on Raspberry Pi.

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

Using a Raspberry Pi as a multimedia server requires:

  • An operating system and miniDLNA program installed on your Raspberry Pi,
  • You can attach various cleanly formatted and fragmented hard disks to your Raspberry Pi for storing and streaming media files.
  • A basic understanding of how to use a computer, Client-server architecture skills, familiarity with Unix terminal and Secure shell, and a passion for computing and the media are a must!

Even if you lack some of the expertise mentioned above and experience, we can still attempt to accomplish this task, and you will gain new knowledge in the process!

This can be done in a variety of ways. It's a mix of free and paid options. While we're here, we'll learn how to use the DLNA protocol to run a public media server on a Raspberry Pi. Let's get right down to business right away.

What Exactly Is a Multimedia Server?

It's possible to store information in the form of files on a media server at a central location. It doesn't matter if it's a document, image, film, ebook, or scripting file stored on a conventional media server; everything it contains is a file. It merely allows you to store data in a more orderly fashion. Accessing data should necessitate you navigating it on your own.

A media server sits on top of the file server. Media items such as photos, music, and videos can be accessed with this application. In addition, it enables network playback. There's no need to worry about where the video files are kept. You don't have to do anything more than type in your questions and wait for the results to appear. For example, you can search for all the music by a particular artist or musician. These new features improve the media server's usability, manageability, and overall appeal.

What is DLNA?

Let's have a look at the DLNA, shall we? When it comes to digital living, DLNA (Digitized Living Network Alliance) is the acronym. SONY with Intel collaborated to create a multimedia transfer protocol standard. Its primary purpose is to set guidelines for media distribution via the Internet. Smart gadgets like android Tv, smartphones, and set-top boxes that can share multimedia content are all DLNA-compliant. Microsoft Media Player, VLC, and Plex will all be DLNA-enabled in the future.

Computers can now be used as multimedia servers thanks to the DLNA standard. A DLNA server and a DLNA client are necessary for DLNA to function. Media sharing is a server-to-client process that occurs at all times. Servers and clients cannot independently share material. Clients and servers are two terms you may hear used interchangeably. What do you think about their appearance? Any DLNA-enabled device can serve as a DLNA client. Smart devices that can stream media over the Internet are one example. Setting up a DLNA server does not necessitate a large server. Any of your friends can access it and set up their server with it. The Windows Player is capable of serving as a Digitized Living Network Alliance server. In addition, many NAS devices are equipped with DLNA server programs that allow users to view multimedia files stored on them. Free multimedia services can be built on the Raspberry Pi using the miniDLNA software.

How Do We Setup MiniDLNA on a Raspberry Pi?

Because of its small size, it can be run on any Raspberry model. Let us set up a miniDLNA service on our RPi and transfer multimedia files to external smart devices via the network.

A better grasp of the setup procedure is gained by splitting this topic into four primary subsections.

  1. Install miniDLNA on your Raspberry Pi.
  2. Create directories for the storage of databases and logs.
  3. Configuring of miniDLNA for media files to be picked up.
  4. Rebooting the miniDLNA service.

Install miniDLNA on your Raspberry Pi

Install miniDLNA:

It's as easy to set up as any other application. Let's do an apt installation.

Minidlna's DB and logs should be stored in this directory:

/mnt/data-ext4/ is where we'll create all of the directories we need for our demonstration purposes.

Adding the group and user to the minidlna directory ownership list:

Inside the minidlna folder, we can write to a folder instead of root, as shown by the permissions below. In general, it's not a good idea to offer complete access to everyone. s Instead, new users and groups are created, and the ownership is transferred to them. Therefore, the database and logs are stored in this folder.

Ownership can be changed with the command shown. In the chown command, the user and the group are permitted to access the folder.

MiniDLNA directories must have the necessary permissions set.

Minidlna folder ownership after the chown command is shown here.

Create directories for the storage of databases and logs

Set up an entirely new subdirectory named "Music" inside the "public" folder you just created. The 'public' folder has all permissions for all the users, so the sudo word isn't necessary anymore. This folder is owned by 'user' and group 'pi,' and no one else has to write access to this folder.

The write permissions of the Music directory need to be fixed:

You can use the same 'chown' command to make the Music folder owned by everyone and grant write access. Everyone acknowledges the file/directory because nobody and no group are users.

Organize multimedia content by creating a few additional folders:

Likewise, you can reorganize your multimedia files in any way you see fit by creating new folders. For demonstration, we will establish a couple of extra subdirectories.

Add a few extra subdirectories inside the /mnt/NTFS public folder. Then, add some audio and video files to each of these folders.

The miniDLNA configuration file should be set up as follows:

Now tell miniDLNA where to find the media files. Modify the configuration file in your preferred text editor.

The media directories should be configured at this point:

Make a list of all additional folders you've made to contain multimedia files in the line where you see 'media dir.' Just after the equal sign is a letter, ',' include the location of the files.

A: Audio

P: Picture

V: Video

PV: Pictures and Videos

Use the following steps to set up a database and log storage location:

Navigate a little farther down the page to specify where the DB and logs will get saved. Quit the editor and save the modifications you've just made.

Restart the minidlna service:

Restart your minidlna server for the modifications to be reflected in the database and take effect. If everything is okay, the program should be functioning. Please check the status of the server.

Allow only a limited number of users to watch at once:

Analyze the logs to confirm that everything is functioning as intended.

Just keep an eye out for warning logs. There are claims it can manage up to 8192 folders and subfolders. If you have a more extensive selection, you can change the value of your collection to make it more valuable.

/proc/sys/fs/inotify/max_user_watches. But, this will not survive a reboot.

Permanently limit the number of people who can watch a video:

To keep the value set indefinitely. Modify the document /etc/sysctl.conf.

At the very end, add the following sentence:

Restarting the minidlna service is as simple as configuring it to do so.

This can be accomplished in a variety of ways. Here's an easy one:

It's done. However, keep in mind that indexing and cataloging massive data will take longer. The cataloging process might take a little longer at times.

Use Plex to set up a media server for your home.

Download the Plex Media Server Package

Choose Plex Media Server from the menu button of the official website, then Linux from the left-hand platform drop-down, and select the Choose Distribution button there.

If you're looking for an ARMv7-based distribution, choose Ubuntu (16.04+) or Debian (8+), then save the image. Then follow the steps below to install.

Method 1:Using the WinSCP utility on a Windows Pc.

Installing WinSCP is as simple as going to the official website and downloading the software. Run the program you downloaded and installed after it has finished downloading and installation.

  1. First, go to the Session > New Site option.
  2. File Transfer Protocol: SFTP
  3. Enter the hostname
  4. Enter username
  5. Enter password
  6. Login

Once you've logged in, you should see the local Computer system files on your left side and the Raspberry Pi system files on the other side.

Locate the Plex Storage Server you already downloaded, right-click on it, and select Upload. On the raspberry home directory, the file will be stored there.

Method 2: Use a secure shell to access the wget command in raspberry pi.

Using a secure shell, you may download plex with the wget command from your Raspberry Pi. Direct access to the application file is required to download the entire package. Copy the link address of the application by right-clicking on it and selecting "Copy Link Address."

To download a specific package, run wget accompanied by the URL link and press return on your pi terminal.

The package is saved to the current working directory after downloading.

Install Plex on the Raspberry Pi

Connect to the Pi through a secure shell using PuTTY. You should be in the root directory. The program 'ls' output will reveal the file that was previously.

We'll now use the dpkg tool to complete the installation.

IMPORTANT: The filename must match exactly what appears in the secure shell terminal. The reference name of the command is just for illustrative purposes.

Press the return key then you'll be prompted for additional verification. Please accept them, and it'll be deployed as intended. Once the server has been set up, it may be found at:

Whenever you launch the service for the first time, it will prompt you to check in to the Plex account. Once you've entered your username and password, the page should reroute to the local server.

Setting up an external HDD for use with Plex

The OS makes it more difficult to mount a hard drive in headless mode. Using this method, you should be able to get everything you need to get this working.

Use the following command to make a new directory in the media directory:

To make a copy of your system's /etc/fstab, type the command:

To identify the external HDD, type the command:

The name may differ if you're looking for the sda2 (/dev/sda2).

Type the command below to obtain the partition Block ID:

There is a LABEL to identify this drive and its type as NTFS, which you can see by looking at the printout. You may also get it as ext4, depending on the format.

The following command is used to modify the /etc/fstab file:

Insert this line in the file:

This UUID is the one that we acquired when we checked the id of the block in the steps above. Ntfs or ext4 should be the file system on the attached drive.

Hit Ctrl + O to save the file, followed by Ctrl + X to quit; the file is saved.

Reboot the Pi while the HDD is still plugged, and then run the df program once more to make everything work as it should. A working /media/HDD mount is still required.

If something goes wrong during this stage, getting the server up and running again will be more challenging.

How can we upload media to the Plex server?

The Plex app can is found on the Internet by browsing the following address:

Then, click the settings button displayed below.

 

Navigate to MANAGE > LIBRARIES from the left menu. Libraries are now clearly visible. Select "Add Library" from the drop-down menu. You should now be able to select a media type from a new popup:

Click Next, then Browse for a Multimedia Folder to select the files you want to use. The hard drive will be as seen in the image below. To upload media, click Add and then choose the media directory from which you want to add it.

At this point, the service should begin searching for your files. Depending on the content and the volume of data in the folder, this could take a while to accomplish.

How can we stream on smart devices?

The server-side plex setup is now complete and operational. You can now choose from a variety of ways to consume your media.

  1. If you have a Smart TV, you can use the Plex client application for streaming. Get the plex application installed, and sign in. In your Wireless connection, the application will find the server for you. You can now begin streaming and listening to the files.
  2. You can download the mobile application from the google play store and log in with your details. The server on your local wireless network should be detected automatically by the application. Is it possible to begin viewing the media? However, it is required that you purchase either a plex pass or a one-time unlock the key to consume the multimedia files using your Android phone. If you expect to stream a lot, this is a good investment.
  3. If you have a desktop or laptop computer, you can access the application through the internet browser at:

You'll be able to watch movies, web series, and live TV through the client application and your local media files.

Conclusion

This tutorial taught us to set up a free media server on Raspberry Pi. It is now possible to stream and organize your media files attractive and portable manner. In the following tutorial, we will learn how to use a raspberry pi as a DNS server.

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.

Printing in Raspberry Pi 4

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to how to tweet from Raspberry pi. We also discussed some methods used by the tweepy library to perform some API calls in our project. We will learn how to print from a Raspberry pi in this lesson.

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

Let us get started

There are several benefits of having a print server. Print servers may link numerous computers to one or multiple printers, either physically or wirelessly, allowing you to access the printer with various devices and send print instructions from all the other connected computers.

It is not easy to print from an Android smartphone to a cabled printer; however, a printer server makes it simple. A print server is useful in small workplaces where employees may print from any business printer. Another benefit is that we do not need to install drivers and software for the printer on your devices.

Requirements

  • Raspberry Pi
  • USB Printer
  • Ethernet Cable
  • Power Supply

CUPS

The Common Unix Printing System is a printing tool for machines running UNIX-like operating systems. It enables the machine installed to function as a printer server. A CUPS-enabled computer may take tasks from numerous devices, process them, and send them to the right printer for printing.

Setup Print Server Software CUPS

With our Raspberry terminal, we will configure the typical Unix printing system.

  1. Update Pi

We need to ensure that our Pi runs the most recent software; thus, we will carry out the following command in the terminal.

Once the installation is finished, we will restart our raspberry pi.

  1. Use Static IP

A few system changes are required before utilizing the Pi as a "server" on the network. We must configure the dynamic host configuration protocol client to use a static Ip; otherwise, the DHCP client may choose any accessible network address, making it difficult to access the RPi over the network.

We begin by modifying the DHCP configuration file.

If you choose to create a static Ip for the wired connection or a Wi-Fi connection, add either one of the below.

  1. Interface: This is the network connection for configuring the settings.
  2. the static Ip address is the Ip you'll use to configure your device. (Don't forget to include a /24 in the end.)
  3. static routers: It is the default gateway.
  4. Static domain_name_servers: Your DNS server's IP address is this.

Save your file by pressing Ctrl Plus X, then Yes, finally Enter key. Lastly, restart your Raspberry Pi.

Note that your network setup may differ in address category and Ip. This step must be done carefully; otherwise, your Pi will experience connection troubles. Run the following commands and look at the inet and subnet mask numbers to know what IP address you'll need:

  1. Install CUPS

The next step is to set up CUPS. This will take some time, but it will install with other requirements such as Samba, Perl, and several other tools or packages.

  1. Configure CUPS

We have to make adjustments to CUPs' config file. The following commands can be used to edit the configuration file:

To the config file, add the following. We will be able to communicate with CUPS panels due to these modifications.

If you wish to change the Ip port, locate and modify this line.

In addition, if we want to use the CUPS Interface, you must accept requests coming from that domain. Just before <location> tags, we add these lines.

Save your file by pressing Ctrl + X, then Yes, accompanied by the Enter key.

  1. User & Network Access Settings

The Raspberry user is then added to the lpadmin group. This allows the RPi to conduct CUPS administration duties without being a superuser.

We must guarantee that CUPS is available throughout the network.

Lastly, reboot CUPS to apply the modifications.

  1. Setup Samba

Samba is an industry-standard Microsoft interoperable package for Unix systems. It allows our Windows operating system to connect to our CUPS central server on the Raspberry Pi and transmit print instructions from the Windows system.

We have to change Samba's settings in the config file before we can proceed with the setup:

Scroll down to the print area and alter the guest's ok to yes.

Scroll down to the printer driver area and change the line shown below

Save the script by pressing Ctrl Plus X, then Yes, accompanied by the Enter key.

Lastly, reboot Samba to see the modifications take effect:

How do we set up our printer?

Install Printer Drivers

You may need to install printer drivers. You can look for the instructions for your specific printer brand on the internet, but we'll be using an HP printer for this lesson.

Install the following GUI if desired:

Then run the command below and download the displayed package from HP.

Adding Printer to CUPS

Link your computer to the network your Raspberry is in. Open the internet browser and navigate to the CUPS site by providing your Pi IP followed by port ":631," to which CUPS is connecting. If the internet browser displays the message "Connection not secure," select "Proceed Anyway."

You may find your Pi IP by running hostname -I on your Pi terminal. If all goes well, the website is:

Navigate to the Admin page and choose Add Printer. Ascertain that you turn the printer on and hook it to the Raspberry through USB. Follow the on-screen instructions to set up the printer. Check the "share this printer" checkbox before proceeding to the last stage. Lastly, print a sample page on the Printers tab to ensure that everything is working correctly.

Please remember that the printer might not be shown under "Local Printers." If this is the situation, you must configure the necessary printer drivers in your Raspberry Pi.

The last step is to transmit print instructions using any connected devices. After that, you can print wirelessly from Linux, Microsoft, Macintosh, Android, and apple. There is no need to install additional printer drivers for this.

Printing with the raspberry pi

This is the final and most straightforward step, in which we will wirelessly communicate print instructions to our printer. You must have CUPS installed on your Raspberry and print a sample page using the CUPS Web-based interface. Any gadget you would like to print from must be on the Pi network.

Windows

You must have Samba installed and set up on your Pi for this to function.

Navigate to Settings and select "Add a printer or scanner." This will automatically detect the network printer, and you may add it by clicking "Add Device."

Select "The printer that I want isn't displayed if it doesn't work."

The queue name, in this case, is like the printer's queue name in the Printers tab of the CUPS web-based interface.

Linux

You may add a wireless printer to a Linux desktop by going to GNOME Preferences- Devices and Printers. The procedure would be relatively similar in other Linux distributions.

The wireless printer will be discovered and added automatically. If that doesn't work, you might need to add the printers by entering the Ip of the Raspberry Pi.

macOS

At the bottom, press the Plus button. The printer will be detected automatically by Mac. Select and then click Add.

Android

The system includes a Print Function in Android. For previous versions, you must install the CUPS Print plugin. Then go to Settings -Devices Connected -Connectivity- Preference Printing and activate the CUPS Printing plugin. You may start the Print Capability in Oreo and later versions.

For printing a paper or file, open the files in a printing-compatible app. Go to Options Print, choose your printer, and press the print button.

There was an issue that occurred after installing a printer. The printer only printed a few jobs and ignored the rest. I had to reboot either the Raspberry Pi or the printers to resume printing. The command below resolved this issue:

Benefits of Wireless Printing

If you haven't yet experienced the pleasures of wireless connection printing, this project is a great place to start. But what's the point of wireless printing?

Mobility

Wireless connected printers enable users to work effectively on the go because there are no cables attaching the printer to a particular spot. This may be useful in various industries, from retail, where sales associates can construct more checkout stations during busy periods, to logistics, where haulage carriers must track the weights of their vehicles.

Organizations with mobile workers, such as health & security inspectors, may profit from wireless communication because employees can print their invoices, records, and results right away – instead of having to go back to their offices.

Accessibility

Instead of struggling to access your business services to download discs, these wireless printers work efficiently. The benefits of a wireless connection are limitless. It allows business employees to produce receipts, examination data, tickets, and labels with a single click and return to their job with minimal interruption.

Wireless printing can also eliminate the requirement for Wi-Fi using iOS and Android technologies, allowing mobile employees, public transportation drivers, and law enforcement officers to print files regardless of their place.

Multifunctional

Wi-Fi printers use infrared technologies to connect to other devices and quickly produce high-quality banners, receipts, and bar codes. The printer may increase doctor efficiency while drafting patient information if it is equipped with pre-cut labels and provide major benefits to CSI teams, who can now immediately manufacture evidence tags at crime scenes.

Depending on your company's needs, a single printer can serve various functions. While a shop manager may utilize a mini-printer for everyday receipt production, they could also opt to use the same printers to print tickets for exclusive launch events, therefore, lowering equipment expenses.

Convenience

Because the printer is small and portable, employees may set it wherever needed. The printers provide excellent space-saving solutions for better printing efficiency and the ability for many users to connect to a single printer to cut the cost of buying extra resources.

These printers are intended to reduce waste, which is very important for conferences and seminars. Workers may print on demand since the printer does not have to be supplied with pre-printed tickets, avoiding the possibility of an unneeded surplus.

Cost-effective

Wi-Fi printers are advantageous to small stores, like start-ups or pop-ups, since they are not well-established companies.

With a bit of investment in such a payment service and a portable printer, business owners may accept card payments at gatherings or establish temporary kiosks in existing businesses and cafés.

Despite their small size, Wi-Fi printers have a considerably longer battery storage life that may last weeks or even months on standby. This implies you won't have to pay a high electricity cost, and you won't have to resupply every day.

Wi-Fi printing makes printing more flexible, making it an excellent project for Raspberry Pis. The advantage of this approach is that it is compatible with Microsoft operating system, Macintosh, and other Linux distribution systems.

What Can We Do With Our Printer?

Greeting Cards

Decades ago, some individuals stopped sending these cards and letters. But there's nothing quite like receiving a handmade letter from someone. Your printer offers multiple options for printing in various sizes.

Print Your Artwork

You could even use an inkjet printer to print creative design work if you're a creative individual. Because inkjet ink offers a much more accurate and vibrant color representation than laser ink, we recommend utilizing them instead of laser printers.

Business Cards

There is no better method to share professional details with customers than offering them a professional card nowadays. Ordering these cards, on the other hand, is shockingly costly.

Custom Napkins

Are you preparing a great social event or party? Prepare your paper napkins by printing something unique on them. That's right: you can personalize your napkins with photos, graphics, initials, logos, and other details.

With this capability, you can elevate that special event or family dinner to a whole new level. Furthermore, if you own a modest business that offers personalized napkins, it is really a fantastic option to work from home.

Conclusion

In this tutorial, we learned how to print from Raspberry pi. We also learned some of the benefits of using a wireless printer. However, In the following tutorial, we will learn how to take a screenshot in our Raspberry pi.

Tweeting on Raspberry pi 4

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to configure our raspberry pi for voice control. We also discussed some methods of reducing vexing noises so that the voice command program understands you. However, in this lesson, we will learn how to tweet from Raspberry pi.

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

What will we learn?

Assume you wish to add tweeting into a Raspberry Pi software you're developing. This article will show you how to build a Twitter app, get access privilege tokens, and post a tweet. On our Raspberry Pi, we'll make a simple program that tweets the result of the uptime command. This is a made-up example, but it demonstrates what is needed to tweet from a raspberry pi.

For this session, a repo has been set up. Because we'll be referring to code within the repository, cloning it will be helpful. You could use this program as a reference point for your programs or copy the components you need.

Let's start by installing git with the command below.

We're going to clone the repository into our current working directory now:

After that, change the directory into the repository.

The Twitter Application programming interface requires that all queries use OAuth for authentication. To access the Application programming interface, you must first create the authentication credentials. Four text strings make up these credentials:

  • Consumers keys
  • Consumers secrets
  • Login Tokens
  • Login Secrets

If you're a Twitter account, go through the procedures below to get the keys, tokens, and secrets. If you don't have a Twitter account, you'll need to establish one first.

Step 1: To become a Twitter Developer, fill out the form below.

Visit Twitter's developer site to sign up for a new account. You must now select the Twitter subscriber in charge of this account. It's most likely going to be yourself or your company. This is how this page appears:

After that, Twitter asks you questions about whatever you want to utilize the developer's account, as seen below:

You must specify the developer account's username and whether it will be used for commercial or personal purposes.

Step 2: Create an application

Apps and not accounts have access to Twitter's authentication credentials. Every tool or program that uses Twitter's API qualifies as an app. To perform API calls, you must first register your application. Navigate to the Twitter applications page and click on the option to create an application to register the app.

The following details regarding your application and its aim must be provided:

  • App name: a name that will help people remember your app (such as examplebot)
  • The objective of your application is described in the application description
  • Uses of the app: how customers will utilize your application
  • The uniform resource locator of your app's website is required; however, it could be a personal website's URL because bots do not require a URL to function.

Step 3: Create your Credentials for Authentication

Navigate to your Twitter applications page to generate the authentication credentials. This is how the Apps page looks:

The Details button for your app can be found here. After hitting this button, you'll be sent to the following page, on which you can obtain your credentials. You could generate and copy the keys to use in your code by selecting the Keys and Tokens tab:

Save the credentials after you've generated them to use them later in your code.

The following snippet can be used to test the credentials:

How can we set the app permissions?

Ensure that the "Read, access, and write direct message" is ticked in the "Permissions" section.

How can we Install Tweepy?

Tweepy is a Library for python for utilizing the Twitter API, and it's included in the requirements.txt document, so all you have to do is:

How does tweepy work?

Tweepy is a library that simplifies the Twitter application programming interface. Tweepy is a collection of functions and classes that mirror Twitter models and application programming interfaces, and it handles implementation details discreetly, such as:

  • Decoding and encoding of data
  • Hypertext transfer protocol requests
  • Results paging
  • Authentication
  • Rate restrictions
  • Streaming

If you didn't use Tweepy, you'd have to deal with low-level features like hypertext transfer protocol, data encoding, authorization, and speed limits. This may consume a lot of time and is subject to mistakes. Tweepy allows us to concentrate on the functionalities we wish to implement.

Tweepy can be used to access the Twitter application programming interface features. Let's have a simple example to see what we're talking about.

The example command below will download all of your tweets from your timeline and output each one to the console. Twitter mandates that all requests be authenticated using OAuth. Tweepy makes using OAuth simple for you. We'll need to establish an account for our application to get started. Build a new app, and when it's done, you should get your authentication token and secret. Keep these two with you at all times; you'll need them.

Next, create an instance of OAuthHandler. We enter our user token and secret, which we received in the previous line, into this:

If you're utilizing a callbacks uniform resource locators that need to be given dynamically in a web application, you will pass it in like this:

If the callback uniform resource locator isn't going to change, it's preferable to put it up as static on Twitter when creating your app.

Unlike basic authentication, we must first perform the OAuth "dance" before we can use the API. The steps below must be completed for this:

  • Redirect the user to the Twitter account to approve our application by obtaining a request tokens from Twitter
  • Twitter sends the user to our website whenever a callback is used. Otherwise, the user will have to enter the verification code manually.
  • Substitute an access token for the authorized request token.

So, to start the dance, let's get our request token:

This call asks Twitter for a token and then provides the authorization uniform resource locator, to which the user should be redirected to approve us. Simply keeping our OAuthHandler object alive till the user returns is sufficient. In a web app, a callback will be used. As a result, the request token must be saved in the session because it will be required in the callback uniform resource locator request. A fictitious example of saving the request tokens in a session is as follows:

As a result, we can now redirect the visitor to the uniform resource locator returned by our authorization URL() function.

If it is a desktop program (or any other software that doesn't employ callbacks), we'll need to ask for the "verifier code" that Twitter will provide after they have authorized us. This verifying code is sent in the callback query from the Twitter account as a GET query argument in the URL within a web application.

The request token is then exchanged with an access token in the last phase. The access token is the "key" to the Twitter Application programming interface treasure chest. To obtain this token, we must perform the following steps:

It's good to keep the access token on hand if you need it later. It is not necessary to fetch it every time. Because Twitter does not currently expire tokens, they would become invalid only when the user revokes our application's access. Your application determines the location where you store the authentication token. Essentially, you must save two string values: secret and key:

You can save these in a database, a file, or wherever else your data is stored. To re-create an OAuthHandler using this cached access token, follow these steps:

Since we have an access token for our OAuthHandler, we can move on to the following step:

Tweet python code

How is API used in this library?

The application programming interface class gives you access to the Twitter RESTful API's entire methods. Each method can take different parameters and provide different results. The API methods are classified into the following groups:

User timeline methods

These ways allow you to read mentions, tweets, and retweets on your timeline and any other public user's timeline.

Tweet methods

These methods deal with tweet creation, retrieval, and retweeting. Tweepy is used in the following code to produce a tweet with specific text:

Users’ methods

The functions in this group may be used to retrieve users using a filtering criterion, extract user data, and show followers for each user so long as the account is public.

Follower methods

This set of routines includes methods for following as well as unfollowing persons, requesting followers for a user, and displaying the profiles a user is following.

Account methods

Using these methods, you may write and view your profile information. This code sample might be used to change your profile information, for example:

Likes method

You can designate any twitter message as Liked or delete the Like tag if it has already been added using these API calls.

Blocking user method

This collection of methods includes unblocking and blocking members and a list of blocked users. You can view the users you've blocked in the following way:

Search methods

You may search tweets using these methods using language, text, and other filters. For instance, this code will return the ten latest public tweets in English that contain the term "Python":

Trend methods

This set of tools allows you to generate a list of the most recent developments for any place. Here's how to construct a list of worldwide hot issues, for example:

Streaming methods

Streaming enables you to actively monitor tweets in real-time for those that meet particular criteria. This indicates the program waits for the latest tweet to be produced before processing it if no other tweets satisfy the requirements.

You must construct two objects to use streaming:

  1. The stream object retrieves tweets that meet certain criteria using the Twitter API. A streaming listener receives tweets from this source.
  2. The streaming listener receives the tweets from the stream.

This is how you do it:

How about models?

Most of the time, when we call an API method, we'll get a Tweepy class model object back. This will hold Twitter's data, which we can use in our program. The following code, for example, returns a user model:

The following are the model classes:

  1. Users
  2. Statuses
  3. Friendships
  4. Search Result

Let's assume you want to obtain a list of all the tweets that mention you, then like each one and follow the author. This is how we can go about doing it:

Since every tweet object given by the mentioned timeline() belongs to the Statuses class, you can use the following syntax:

  • favorite() to make it a favorite
  • favorite() to make it a favorite

Tweet.user property is also a user object. Follow() may add the author of that tweet to the list of individuals to follow. Using Tweepy models allows us to write concise and understandable code.

What is next after setting up our app?

Maybe we can put a motion detector and a camera on our cat and tweet images of it. Alternatively, we could set up a temperature sensor and tweet some weather-appropriate status updates. We can also leave the repository unchanged and tweet the uptime command if we only want others to know our pi's load average.

Conclusion

You may take the Twitter presence to another level by creating your personal Twitter bots. You may use bots to automate content generation and other Twitter tasks. This may save time and provide a better user experience for your viewers. The Tweepy library hides numerous low-level Twitter application programming interface details, allowing you to concentrate on the logic behind your Twitter bots.

In this tutorial, we learned how to set up our tweeter app on our Raspberry pi. We also learned how to generate access tokens, set up our app's permissions, and send a tweet. However, In the following tutorial, we will learn how to print on a Raspberry pi.

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