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.

How to Create a Time-Lapse Animations with Raspberry Pi 4

Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial looked at how to Interface DS18B20 with Raspberry Pi 4. This tutorial will teach us how to create a time-lapse video with still images and understand how phototimer and FFmpeg work.

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

What is time-lapse?

When photographing something over a lengthy period, "time-lapse" comes to mind. A video can be created by mixing the still photos. Plant development may be tracked with time-lapse movies, as can the changing of the seasons. They can also be utilized as low-resolution security cameras.

Components

  • Raspberry pi 4B
  • Pi camera

Connect to the Raspberry Pi

Cameras that can be used with the Raspberry Pi are a bit limited. A powered USB hub is required for most webcams that are compatible. For this post, we’ll be using a camera specifically made for the Raspberry Pi. The camera module can be plugged into a specified port on the Raspberry Pi. How to do it;

  • Turn off the pi

Shutting down the pi is recommended before adding a camera. A power button should be installed on Pi 4 so that you may shut down the device safely every time.

  • Locate the camera port and lift the tabs to install the camera's cord.
  • Secure the tabs on the flex cable after inserting it into the flex cable slot.

Slide the cord into the port by using an image as a guide. Finally, press down tabs, securing the cable to the motherboard.

Enable the camera in Raspberry Pi OS

Click on the main menu button, select Preferences, and then click Pi Configuration if you're using a monitor. Enable the camera by clicking on the Interfaces tab.

To continue, headless users must type the command below. Make sure the camera is turned on in Interfacing Options. Rebooting the Raspberry Pi will be required.

How to record time-lapse images

Individual stills are used to create time-lapse videos. We'll be using raspistill to acquire our time-lapse images. As part of the Raspberry Pi OS, you don't need to install anything extra. The are two way to record a time lapse:

  • Using the raspistill tool on the Rpi alone
  • Using phototimer
  1. Using the Raspistill tool only

Raspistill is a Linux-based software library that aims to make it easier for Linux users to use sophisticated camera systems. We can use open-source programs running on ARM processors to control the camera system with the Raspberry Pi. Almost all of the Broadcom GPU's proprietary code is bypassed, which customers have no access to.

It provides a C++ API to apps and operates at the base of configuring a camera and enabling the program to obtain image frames. Image buffers are stored in memory space and can be supplied to either video encoders (like H.264) or still image encoding algorithms like JPEG or PNG. raspistill, on the other hand, does not perform any image encoding or display operations directly.

How can we use this tool?

An illustration of how to take time-lapse photography is shown in the following image.

In this case, the time-lapse capture was 10 seconds long. The Raspberry will wait for a total of 2000 milliseconds between each image. For 10 seconds, the Raspberry Pi will take a picture every two seconds.

The photos will be stored as .jpg files. This example uses the name "Pic" and a number that increases with each frame to identify each image. The final digit of percent 04d is a zero. Pic0000.jpg and Pic0001.jpg would be the names of the first two photographs, and so on. Change this value according to the requirements of your project.

How can we compile the to a video?

Your time-lapse video needs to be put together once all of your photographs have been taken. FFmpeg is the tool we'll be utilizing to generate our timelapse video. The command to download the package is as follows:

Allow the installation to be complete before moving on. Using this command, you can create a finished video:

Pic%04d.jpg corresponds to the image filename you specified in the preceding section. If you have previously changed this name, please do so here. With the -r option, you can specify how many frames per second you want to record. When creating a time-lapse video, replace the phrase video-file with your name. Make sure to keep the .mp4 file extension.

What is FFmpeg?

A high-speed audio and video conversion tool that can also capture from a webcast source is included. On the fly, video resizing and sampling can also be done with high-grade polyphase filters.

A plain output URL specifies an indefinite number of outputs that FFmpeg can read from (standard files, piped streams, network streams, capturing devices, etc.), whereas the -i option specifies the number of input files. An output URL is encountered on the command-line interface that cannot be treated as an option.

Video/audio/subtitle/attachment/data streams can all be included in a single input or output URL. The container format may limit the quantity or type of stream used. The -map option can map input streams to output streams, either automatically or manually.

For options, input files must be referred to by their indices (0-based). It's not uncommon to have an infinite number of input files. Indexes are used to identify streams inside a file. As an illustration, the encoding 2:3 designates the third input file's fourth and final stream. In addition, check out the chapter on Stream specifiers.

  1. Using Photo timer

A Python library named phototimer will be used to control the raspistill command-line that comes pre-installed on the Raspbian OS.

  • With the use of this tool, we're able to add valuable features like:
  • Set a time frame for your day.
  • After capturing a photo, create a date-based folder such as:

Let us install docker to use this tool

Using docker, you can develop, analyze, and publish apps in a short time. To run phototimer with Python installed, you'll need to use Docker with Raspbian Lite.

  • Automatic restarts of the time-lapse

A new location does not necessitate an SSH login. The lapse of time will be restarted.

  • Easy setup

Download the Docker image, activate the camera interface, and start the container instead of executing a git clone on each device.

  • Easy access to logs

If you disconnect from the container, docker will keep track of the log information and will enable you to reconnect at any time.

Install Docker in Raspberry pi

We can easily set up docker with the following set of commands.

Clone the phototimer GitHub repository

Download the docker file as a zip as shown below

Or use the terminal by copying the phototimer code as shown here:

If git isn't already installed, use the following command to add it:

Edit the config file

By modifying the config.py file, you can change the time-appearance lapses and duration.

  • Set the hours

You will likely want to alter the default time-lapse settings so that they better fit your requirements, which start at 4 am and end at 8 pm.

  • Set the quality level

For some reason, overall quality of 35/100 produces a substantially smaller image than one with a quality of 60-80/100. You can modify the file to determine how much space you'll need.

  • Flip the image

Depending on how your camera is positioned, the image may need to be flipped horizontally or vertically. True or False in each situation will have the same result.

  • Height and Width

To achieve a specific aspect ratio, you can change the height or width of the image in this way. The default setting is what I use.

The Docker container must be re-built and restarted every time you change your setup.

Now let`s build a Docker container

When docker does a build, it will construct an image from the current directory's code and a base image, like Debian.

The most crucial part is that the image we create right now contains everything our application might want.

For those just getting started, these are some helpful keyboard shortcuts and CLI commands:

Start the timelapse

Let us configure the time zone for docker

The default time zone for the Docker container is UTC. If you're in a different time zone, you'll want to adjust your daylight savings time accordingly.

Docker can be configured to run in your current local time by adding the following additional option to the command:

As a result, the following is what a time-lapse in Texas, United States, might look like:

Below are some time-lapse images taken from the raspberry pi camera.

How can we save the file to our laptop?

To save your photos to your laptop, follow these steps once you've captured a few pictures:

The ssh and SCP functions are included in Git for Windows, which may be installed on Windows.

Connectivity options

You'll need a way to connect to your new rig when you're not near your wi-fi router if you plan on doing the same thing I did. There are a few ideas to get you started:

Use a USB OTG cable

All Pi models allow networking via USB, and it is very straightforward to establish and will not interfere with the wi-fi network. You will have to bring a USB cord to each new site to directly change the Wireless SSID/password on the pi.

Drop a wpa_supplicant.conf file into /boot

Plugging an SD card into your computer while on the road allows you to update your wi-fi configuration file easily, provided there is an SD card adapter nearby. The existing configuration will be replaced with this new one on the next reboot.

Setup the RPi as a wi-fi hotspot

If you're comfortable with Linux, you can use hostapd to create your hotspot on the RPi. To connect to your Raspberry Pi, you'll need a computer with an Ethernet cable and a web browser.

Install your wi-fi Username and password and use that to start/stop timelapse capture and download files if you won't be using the rig outside your location.

How to edit the video

The imported files should be in the correct order if you drag them onto the timeline after they've been imported, so be sure to do that. The crop factor should be set to "fill." Instead of 4.0 seconds, use 0.1 seconds for the showtime every frame.

  1. Transfer files to the Raspberry Pi using SCP

It is often necessary to transfer documents between the Linux laptop to an industrial Raspberry Pi for testing purposes.

Occasionally, you'll need to transfer files or folders between your commercial Raspberry to your computer.

There is no longer a need for you to worry about transmitting files via email, pen drive, or any other method that takes up time. Automation and industry control can help you automate the process in this post.

As the name suggests, SCP refers to secure copy. This command-line application lets you securely transfer files and folders between two remote places, such as between your local computer and another computer or between your computer and another computer.

You may see SCP info by using the command below:

Using SCP, you can transfer files to the RPi in the quickest possible manner. There is a learning curve associated with this strategy for novice users, but you'll be glad you did once you get the hang of it.

  1. Enable SSH

You must activate ssh on your Raspberry Pi to use SCP.

Converting to GIF

A free program like Giphy can help you convert the videos to a GIF; however, this will lower the number of frames.

Conclusion

We learned how to use the Raspberry Pi to create a time-lapse animation in this lesson. In addition, we looked into the pi camera raspistill interface and used FFmpeg and phototimer to create a time-lapse. We also learnt how to interface our raspberry pi with our pc using ssh and transfer files between the two computers. The following tutorial will teach how to design and code a GPIO soundboard using raspberry pi 4.

Interface DS18B20 with Raspberry Pi 4

Hello friends, I hope you all are having fun. Today, we are going to share the 7th tutorial of Section-III in our Raspberry Pi Programming Course. In the last tutorial, we interfaced a DHT11 sensor with Raspberry Pi 4. Today, we are going to interface another temperature sensor i.e. DS18B20 with Raspberry Pi 4.

DS18B20 is a popular temperature sensor especially in severe/critical environments i.e. chemical plants, mines, industrial sites etc. because of its 1-wire operational technique and accurate readings up to 4 decimal digits.

Project Description

Today, we will interface a DS18B20 temperature sensor with Raspberry Pi 4 and will display the values on a 16x2 LCD.

Let's have a look at the components required for this project:

Components Required

Here's the list of components:

  • DS18B20.
  • Raspberry Pi 4.
  • LCD 16x2
  • 10k trim pot
  • 10k Pull up resistor
  • Breadboard
  • Male to Female Jumper Wires

DS18B20 Sensor: A Quick Overview

  • DS18B20 is a low-cost, 3-terminal temperature sensor, that uses a 1-wire protocol to send its data.
  • To communicate with a microcontroller or processor board like Raspberry Pi, the DS18B20 uses only one wire.
  • We can also interact with multiple DS18B20 sensors with a single Pin by calling their signatures.
  • DS18B20 temperature sensor along with pinout, is shown in the below figure:

A waterproof variant of this sensor is also available, which encloses the sensor within a cylindrical metal tube. The sensor depicted in the above image will be used in today's project. The sensor's specifications are shown below.

Types of Temperature Sensors

A wide variety of temperature sensors are available. The following are the two most common kinds of temperature sensors:

Contact sensor: Some thermometers use direct contact with an object, referred to as "contact type temperature sensors," to measure the degree of warmth or cold.

Non-Contact sensor: This type of thermometer does not touch the object it is measuring; instead, it measures the temperature based on the radiation emitted from that object. DS18B20 is a non-contact temperature sensor.

Circuit Diagram of DS18B20 with Raspberry Pi 4

Here's the circuit diagram of the DS18B20 temperature sensor and a 16x2 LCD display, connected with Raspberry Pi 4:

  • GPIO4 of Raspberry Pi 4 is used to connect the data Pin of DS18B20 and we have placed a pull-up resistor of 10k ohm, as shown in the circuit diagram.
  • GPIO 7, 8, 18, 23, 24, and 25 are used to interface LCD with Raspberry Pi 4. (You should read LCD interfacing with RPi4)
  • Potentiometer is used to adjust the brightness/contrast on the LCD.
  • Connected the Raspberry Pi's 5V pin with that of the LCD and DS18B20 Sensor, similarly, connect the GND pin of RPi4 with the GND of the sensor & LCD.
  • Here's the Raspberry Pi 4 Pinout:

Now, let's design this circuit on a breadboard with the help of Jumper wires. When everything is connected, my hardware will look like this.

We have designed our circuit, so it's finally time to write the Python code for DS18B20 with Raspberry Pi 4:

Installation of Python Libraries

Before start working on our code, we need to first install the LCD Python library and enable the 1-wire protocol in RPi board.

  1. Adafruit LCD Library.
  2. 1-Wire Protocol.

Adafruit LCD library

We need to install Raspberry Pi's Adafruit LCD library to display the temperature on the LCD screen. Using Adafruit's library, we can easily operate the LCD in 4-bit mode. So, follow the below instructions to install Adafruit Python Library:

  • Step 1: Use the following command to install git on your Raspberry Pi:

Any project on GitHub can be cloned using Git. Since the library is hosted on Github, we'll need to set up a Git before installing this library.

  • Step 2: To copy the LCD library project to Pi's home directory, run the below command:

  • Step 3: Now we need to open the LCD library folder, so type the below command in the terminal to change the directory:

  • Step 4: Now, we need to install the LCD library, so run the following command:

That's all there is; the library should now be operational. In the same way, let's install the 1-wire library for DS18B20 sensor.

Enabling 1-Wire Protocol in Raspberry Pi

If we want to connect with the DS18B20 sensor via a One-Wire approach, we must have to enable the One-Wire Protocol in Raspberry Pi first. So, follow the below instructions:

  • Step 1: To open the config file, type the following command in the Command Prompt window:

  • Step 2: Add the following line to the config file: "dtoverlay=w1-gpio" and save the file:

  • Step 3: Run the following command to restart the Pi:

  • Step 4:- Take a look at your terminal after the system has been restarted and type as follows:

This is what you can expect to see in your terminal windows:

  • Step 5:- To get a unique pi number, type "ls". According to the sensor, this number will vary from user to user, but will always begin with 28-. In our case, it's 28-03172337caff.
  • Step 6:- The following commands can be used to verify that the sensor is functioning correctly:

You can see the sensor's readings on the terminal as a result of these commands. The image below shows a red arrow pointing to the temperature. The current temperature in my home is 37 degrees Celsius.

Using Python on a Raspberry Pi

Here's the complete Python Code to display the temperature from DS18B20 on an LCD display with Raspberry Pi 4:

So, let's understand this Pi code for LCD display and One-Wire communication. I've broken down the code into smaller, more digestible chunks below to make it easier to understand.

DS18B20 Python Code Explanation

Importing the necessary header files is always the first step in a new program. Time and the LCD header are imported here to use the LCD with Pi.

It is important to mention the Display pins linked to the Raspberry GPIO. Consult the diagram above if you're unsure of the pin numbers for specific GPIO pins. Once the pins on the PI to which the LCD is connected have been declared, use these lines of code to initialize the LCD display.

Once the LCD has been initialized, we show a sample text message. To indicate a new line, the character 'n' is used. There is a delay of two seconds before users can begin reading the intro message.

Make sure you remember what you did in step 4 in order to enable the one-wire interface on your Pi. For this reason, we are using the os.system function to repeat the code. Afterwards, a file path is supplied where the temperature value will be read from. We can't open the folder since we don't know its exact name. The device folder variable connects to the '28-' folder using the * symbol. The temperature value is stored in a file with the name device file, which is also in that folder.

Then we create a get temp method, which specifies how to read the temperature from the file we previously linked. There will be a file containing the temperature data; however, the format will be as follows:

We only need the temperature value, which is 37000, from this. A reading of 37.00°C can be seen in this instance. After trimming all the unnecessary information from this type of text, we must next divide 37000 by 1000.

Using the lines variable, the file's lines can be parsed. A search for "t=" is done in these lines, and in the variable temp string, the value that comes after that letter is recorded. Finally, we perform division on the string value with 1000 in the variable temp c to obtain the temperature value. Finally, the code should output the temp c variable.

To display the current temperature on the LCD panel, we merely need to invoke the previously described function inside the infinite while loop. Every second, we refresh the LCD display to show the current value.

Output

Use the code provided at the end of this page to compile it on your Raspberry Pi and see what happens. Before running the application, Install the display libraries and enable a one-wire connection on the Pi. You can now run the application and see if everything went well; if so, the intro text should be visible. Adjust the contrast potentiometer, if necessary. What you'll see when it's all done is shown in the below images:

DS18B20 Applications

Temperature sensors can be used in a variety of ways, so here are some examples.

  • Motors - Temperature monitoring is required for several motor components to ensure that the motor does not overheat.
  • Surface plate – In order to accurately detect temperature, a typical type of surface plate temperature sensor is the ring terminal sensor (RTS).
  • Home appliances – Temperature sensors will be found in everything from coffee makers to toasters to washing machines and dishwashers.
  • Computers – Temperature sensors are built into computers to guard against overheating.
  • Industrial equipment – The temperature sensors utilized in these applications must be extremely durable because of the harsh conditions.
  • Warming Electrical Radiators – In order to regulate the temperature of electric radiators, NTC thermistors are employed.
  • Monitoring of Exhaust Gases from Racing Vehicles – Temperature sensors used in racing must be extremely reliable and long-lasting to ensure that performance does not suffer.
  • Food Production; 3D printed chocolates – The melted chocolate used in 3D printing is monitored using temperature sensors.
  • Alcohol breathalyzer – Alcohol breathalyzers employ thermistors to gauge the subject's exhaled breath temperature.

Conclusion

In this lesson, we have studied how to use Raspberry Pi's GPIO pins to connect DS18B20. In addition, we looked into the sensor's fundamental principles and current-day usefulness. We also designed a circuit that we later programmed to collect temperature readings using the temperature sensor and perform a little calculation and display it on the LCD screen in degrees Celsius. In the next tutorial, we will interface the BMP180 Air Pressure sensor with Raspberry Pi 4. So, stay tuned. Have a blessed day.

Interface DHT11 Sensor with Raspberry Pi 4

Hello friends, I hope you all are doing great. Today, I am going to share the 6th tutorial of Section-III in the Raspberry Pi Programming Course. In our previous tutorial, we have seen how to interface an Ultrasonic Sensor with Raspberry Pi 4 and used Python to perform its calculations. In today's tutorial, we'll discuss how to interface a DHT11 temperature and humidity sensor to a Raspberry Pi.

So, let's get started:

Components

Here's the list of components, we are going to use in today's circuit:

  • LCD display
  • DHT11 sensor
  • Raspberry pi
  • Breadboard
  • Male-to-female jumper wires

What is a DHT11 sensor?

DHT11 is a low-cost digital sensor, used to measure temperature and humidity in the surroundings. DHT sensor has three main components i.e.

  1. A resistive-type sensor(used to measure humidity)
  2. NTC Temperature Sensor(used to measure temperature)
  3. 8-Bit Microcontroller(to calibrate & serially transmit the values as a digital signal)

Now, let's have a look at the Pinout of DHT11 sensor:

DHT11 Pinout

DHT11 has 4 pins in total, which are:

  1. Vcc: We need to provide +5V at this pin.
  2. Data Pin: We need to connect it to the Digital Pin of the Microcontroller to get humidity & temperature data.
  3. NC: Not Connected.
  4. GND: We need to connect it to the Ground Pin.

  • Here's the Pinout of the DHT11 Module:

DHT11 Working Principle

The DHT11 timing diagram is shown in the below figure:

This device uses a thermistor to monitor temperature and a capacitive humidity sensor to measure relative humidity. A humidity-detecting capacitor's electrodes are separated by a dielectric substrate that retains moisture. When the humidity level fluctuates, the capacitance value changes as well. Analog resistance values are measured, processed, and stored by the IC, which then translates them into digital values.

The resistance value of this sensor is monitored, as it warms up using a negative temperature coefficient thermometer(NTC). This sensor is commonly made of semiconductor ceramics in order to achieve a higher resistance value even at the smallest temperature change.

With a 2°C precision, the DHT11's temperature range is 0 to 50 degrees Fahrenheit. This sensor can accurately monitor humidity levels from 20% to 80% with a 5% degree of precision. One reading per second, or 1Hz, is the sampling rate of this sensor. The microcontroller DHT11 has a power consumption of 3 to 5 volts. The maximum amount of current that can be drawn during a measurement is 2.5 mA.

The sensor and the microcontroller are connected via a 5K to 10K ohm pull-up resistor.

Types of Temperature and Humidity Sensors

There are many types of temperature sensors available. Factors involved in selecting a correct sensor are: what we're measuring, how precise we need it to be, and where we're taking the readings. The Negative Temperature Coefficient (NTC) thermistor, thermocouple, semiconductor sensors, and Resistance Temperature Detector(RTD) are the most commonly used temperature sensors.

Grove – AHT20

With its dual-row flat, no-lead SMD design, Grove's new AHT20 temperature and humidity sensor is ideal for use in reflow soldering applications. In addition to the standard temperature sensor, the AHT20 has a capacitive humidity sensor made by MEMS semiconductors that is more accurate than the standard sensors.

DHT11

Digital sensors can monitor temperature as well as relative humidity. Two measurements are converted into a digital signal via an analog-to-digital converter chip. Temperature sensors with long-term stability and great performance are among the most popular.

DHT22

Both temperature and humidity are monitored by the DHT22, quite similar to DHT11. The DHT22 costs a little more because it has a wider temperature and humidity range than DHT11, making it more precise. In terms of how it's handled and coded, the DHT22 is identical to DHT11. A temperature sensor that performs better and is more accurate should definitely be considered.

BMP280

When compared to the DHT series, the BMP280 has the capability to measure both temperature and barometric pressure. You can use this in both SPI and I2C modes, making it an upgrade from the BMP180. Because the air pressure changes with elevation, it can estimate a location's altitude as well.

BME280

While the BMP280 only monitors temperature and air pressure, the BME280 has a humidity measurement in addition.

DS18B20

DS18B20 is a one-wire temperature sensor and gives accurate values up to 4 decimal digits.

AF5485

AF5485 is a small and light-weight sensor but it has an impressively complex internal system that allows it to provide the best accuracy. Building automation, weather stations, and temperature monitoring are just a few possible applications.

AM2311A

Compact and lightweight, the AM2311A is an auto-calibration module that consumes minimal power. Furthermore, it is capable of transmitting data at distances greater than 20 meters. It goes without saying that this sensor is extremely dependable and stable over the long run. As a result, it can be employed in a variety of settings.

Circuit Diagram of DHT11 with Raspberry Pi 4

  • Here's the circuit diagram of DHT11 with any microcontroller:

As you can see in the above figure, the circuit diagram is quite straightforward. To avoid noise in the DHT11 output, a 5K pull-up resistor is connected to the Data Pin. The temperature and humidity readings are transmitted as serial data through this pin.

  • Here's the Circuit Diagram of DHT11 with Raspberry Pi 4:

We have also placed an LCD 16x2 to display the values. We have already discussed LCD Interfacing with RPi4, but in that tutorial, we used data pins to write on the LCD, but today, we will use an I2C LCD and send the data via I2C pins.

  • Here are few of the images of our hardware setup and as you can see, we have interfaced both DHT11 and I2C LCD with our Raspberry Pi board:

To connect the DHT11 sensor to the Raspberry Pi, the following steps must be followed.

  • The DHT11 sensor's signal pin is connected to GPIO 4 of the Raspberry Pi board via the yellow wire.
  • The sensor's power pin is connected to the 5V pin on the Rpi board using the red wire.
  • The sensor's GND pin is connected to the Raspberry Pi's GND pin with a black wire.

Now, Raspberry Pi 4 has to be connected to the 16x2 LCD screen:

  • The GND Pin of LCD is connected to the Raspberry Pi's GND pin through a black wire.
  • Connecting the LCD display's voltage pin to the Raspberry Pi board's 5V pin is done using the red wire.
  • The LCD display's SDA pin is connected to the Raspberry Pi's SDA pin by a blue cable.
  • The SCL pin of the LCD display is connected to the Raspberry Pi board using an orange wire.
  • Now let's power up the Pi board to check, if everything's correct:

All our modules are powered up, so everything's correct. Now it's time to write the Python Code for getting DHT11 values and displaying them on the LCD screen:

Python Code for DHT11 Sensor with Raspberry Pi 4

 We need to install the DHT11 Adafruit library to read the sensor values from Raspberry Pi 4.

DHT11 Adafruit Library

  • Step 1: To download the Adafruit module for DHT11, use the following command in the RPi console.

  • Step 2: To install the library on your RPi, follow the below instructions one by one.

  • Step 3: The device must be rebooted, after the library installation.

Now let's design our Python code:

Python Code to read DHT11 data

Here's the complete Python Code to read the data from the DHT11 sensor using Raspberry Pi 4:

Let's understand the code line by line:

  • First of all, we need to import the required Python modules in our code.
  • In order to use system-specific parameters in our program, we first need to import the sys module.
  • To control the I2C LCD screen, we need to import the I2C LCD Driver.
  • When connecting a DHT11 sensor to a Raspberry Pi, the Adafruit DHT module is used.
  • We also need to import the time module to add delays to our program.
  • After importing RPi modules, we initialized an I2C LCD object named "mylcd"  and printed a welcome message on the LCD screen.
  • In the Try code, we are reading the Humidity and Temperature values from the DHT11 sensor.
  • If we got the values, we printed them on the LCD screen.
  • If someone exits the code, a Greeting Message will be displayed.

Reading DHT11 Output with RPi4

  • Before the temperature and humidity values are shown on the screen, the following text appears on the screen.

  • The LCD display will show the first reading from the sensor after a short delay:

  • It will take some time for a new set of values to appear, as shown below:

  • Any warm object placed near the sensor will alter the sensor's reading:

  • You'll see the following text if you provide a keyboard interrupt, while the program is running:

DHT11 Applications

Networked IoT Environment Monitoring

Monitoring or controlling environmental quality is the main goal of environmental monitoring. The DHT11 humidity and temperature sensors are widely used in such systems.

Weather Station

Since this temperature sensor is inexpensive, it can be used in low-cost but effective weather stations that show the temperature and humidity of the surrounding environment.

Climate Control

Climate control is a method of managing the temperature. So, the DHT11 temperature and humidity sensors may be useful in ensuring that the environmental readings are accurate. Temperature and humidity sensors are sent to the microcontroller, and the system will respond if the temperature exceeds a predetermined upper or lower limit.

Conclusion

In this tutorial, we have studied how to connect a DHT11 sensor for humidity and temperature readings with Raspberry Pi 4. The sensor's principles and applicability in the current world were also studied. In the next tutorial, we'll learn how to interface DS18B20 with Raspberry Pi 4. So, stay tuned. Have a good day.

Interface Ultrasonic Sensor with Raspberry Pi 4 using Python

Hello friends, I hope you all are doing well. Today, I am going to share the 5th tutorial of Section-III in our Raspberry Pi Programming Course. In our previous tutorial, we have seen the interfacing of a PIR Sensor with Raspberry Pi 4. In today's tutorial, we will interface an Ultrasonic sensor with Raspberry Pi and will use Python to perform its calculations. So, let's get started:

Components:

Here's the list of components, we are going to use in today's project:

  • Raspberry Pi 4
  • Ultrasonic sensor
  • Male-to-female jumper wires
  • Breadboard
  • 1k ohm resistor
  • 2k ohm resistor

What are Ultrasonic Sensors?

An Ultrasonic Sensor consists of a transmitter and a receiver, the transmitter emits the ultrasonic wave, which after hitting some object bounces back and receives by the ultrasonic receiver. If the Ultrasonic sensor is operated at 5V, it normally measures a distance of up to 450 centimeters.

With an ultrasonic sensor, you can measure the distance between your body and a target item, by sending and receiving ultrasonic sound waves. Unlike audible sounds, ultrasonic waves move faster. To create ultrasonic sound waves, the transmitter uses piezoelectric crystals. The sound then travels to and from the target. When it returns, the receiver gets the sound.

Mostly, ultrasonic sensors can detect objects as close as a few centimeters and as far as about five meters. Measurements of approximately 20 meters can be achieved with specially designed units.

An established technology, ultrasonic sensors have a wide range of uses, from industrial to consumer. Many new devices requiring presence detection or distance measuring can benefit from their simplicity, low cost, and durable construction. Because the hardware and software settings can be changed, they can be used in a wide range of situations.

Ultrasonic Sensor Pinout

The Ultrasonic Sensor has four connections:

  • Vcc: We need to provide +5V here.
  • Trig: Trigger Pin(Connected to Microcontroller)
  • Echo: The sensor's response (Connected to Microcontroller)
  • GND: We need to provide Gound here.

Ultrasonic Sensor Working Principle

An ultrasonic sensor is made up of two parts: a transmitter and a receiver, arranged side by side as close as possible. Smaller measurement errors are achieved when the receiver is near the emitter, as the path of sound from the source to the destination is straight-lined. In addition, the transmitter and reception functionalities of some ultrasonic transceivers are combined into a single device, decreasing inaccuracy to the greatest extent possible while simultaneously reducing the PCB footprint of the device.

Moving further away from the transmitter causes sound waves to broaden and the detection area increases. Ultrasonic sensors, instead of specifying a fixed detecting region, provide coverage specifications in the form of beam width or beam angle to account for this shifting terrain. For comparison, either the full beam angle or the difference from a transducer's straight line, is being used.

The beam angle has a secondary effect on the device's range. As shown in the above figure,  in the case of a narrow beam, the energy of an ultrasonic pulse can travel farther, before it dissipates to unusable levels. Wide beams are better for broad detection and covering large regions, while narrow beams are better for preventing false positives, since they limit the detection region.

When looking for individual parts, transmitters and receivers for ultrasonic sensors can be found separately, or as part of a single device called an ultrasonic transceiver. In most analog ultrasonic sensor alternatives, a trigger signal is sent by the transmitter, and the receiver gets the signal as soon as the echo is recognized. In order to meet specific requirements, the designer can alter the pulse length and any encoding. The microcontroller is ultimately responsible for decoding and calculating the time between the trigger and the echo.

How is the distance calculated?

Ultrasonic sensors typically emit a chirp of ultrasonic radiation, that is much higher in frequency than the range of human hearing. This chirp is used to calculate the duration taken for sound to reflect from an item. This method is based on the principles of echolocation, which are used by bats to detect their prey. With this in mind, it is easy to convert the time of the ultrasonic chip to distance because the sound travels at 343 m/s in the air at ambient temperature. So, in order to calculate the distance covered, we will use the following formula:

We have divided it by 2 because the waves will cover the distance twice, one while going toward the object and the second while coming back from the object.

For example, an ultrasonic sensor emits an ultrasonic wave pointed toward a box. The waves take 0.025 seconds to bounce back. Now, in order to calculate the distance between the sensor and the box, we need to use the above formula and it gives us 4.2875 meters, as shown in the below figure:

Interface Ultrasonic Sensor with Raspberry Pi 4

As we discussed in the Pinout section, Ultrasonic Sensor has 4 pins in total.

  • The sensor emits an ultrasonic signal if a high pulse is detected on the Trigger pin.
  • An echo will return a HIGH signal to the Microcontroller, almost at the same time.
  • Until the reflected sound is detected, the Echo Pin keeps on sending a HIGH signal.
  • When the sensor's receiver gets a sound back, the Echo output gets LOW.
  • With the time difference between the rising and falling edges of your Echo pin, we can easily get the distance between the sensor and the obstacle in the software.

Voltage Divider at Echo Pin

If you set Vcc to 5 volts, the Echo pin will also output 5 volts. Raspberry Pi GPIO pins are prone to voltages above 3.3V, so it is imperative to avoid them. Two alternatives exist at this point:

  • To compensate for this, we can use 3.3 V to power the sensor, but it will reduce the range to about 50cm, which was 250cm in the case of 5V.
  • The sensor is powered up by 5 volts and a simple voltage divider is used on the Echo Pin, to drop the incoming voltage from 5V to 3.3V. So, you get the sensor's full range, but you'll need two additional resistors to design this voltage divider.

Circuit Diagram

  • Here's the circuit Diagram of the Ultrasonic sensor(HC-SR04) with Raspberry Pi 4:

  • As you can see in the above figure, we have placed two resisters at the Echo Pin, to divide the voltage, as we need 3.3V max at RPi4 GPIO.
  • Any spare GPIO pin can be used, instead of Pin11 and Pin13.

Now let's design it with real hardware:

  • I have placed Male-to-female jumper wires on the Ultrasonic Sensor, the other side of these jumper wires will be plugged in the Breadboard:

  • Now connecting Jumper wires to Raspberry Pi 4:

  • Connected Ultrasonic Sensor & Raspberry Pi 4 via Breadboard:

  • Now, let's design the voltage divider for Echo Pin, so placing a 1k ohm resistor on the breadboard:

  • The second resistor used is of 2k ohm:

  • Here's our Raspberry Pi 4:

  • Pin 18 will be connected between the 1k ohm and 2k ohm resistors as shown below:

Python Code for Ultrasonic Sensor

Double-time distance measurements are calculated with the following Python program:

For ten seconds, the trigger is engaged and the sensor uses this signal to produce sound pulses. The start time is decided as soon as the echo signal rises to a high level. Once the echo signal's negative edge is identified, the stop time is calculated. To calculate how long it will take for a sound wave to travel between two points, subtract the starting time from the final time. The speed of sound in the air is 343 m/s, so multiple this time is multiplied by the speed of sound. You must multiply the values by 100 in order to display them in cm. A speed of 34,300 cm/s is obtained. Finally, to acquire a single distance, divide everything by 2. Now let's implement this pseudocode in Python script:

  • This code's first line imports modules for working with the Raspberry Pi's GPIO pins.

  • RPi.GPIO is a module that allows us to communicate with Raspberry Pi's GPIO pins.
  • When delivering ultrasonic sound waves, the Time Module is used to create a delay before the sound is picked up by the receiver.

When using the GPIO SetMode, the numbering scheme used to work on Raspberry Pi's GPIO can be defined in two ways: GPIO.board and GPIO.BCM, respectively.

If you want to learn more about GPIO.Board and BCM, I'd like you to check out the following picture.

  • Use the GPIO.setmode(GPIO.board) function to access the pin with the number in the circle.
  • GPIO.setmode (GPIO.BCM): BCM is the abbreviation for the Broadcom chip-specific number.GPIO.SetMode can be used to represent a pin number as a rectangle (GPIO.BCM).
  • When working with serial, SPI, I2C, and other communication protocols, I prefer to utilize GPIO.setmode (GPIO.BCM) method.

  • Assigning GPIO Pins to Trig and Echo pins:

>

  • Here, we are making the Trig Pin OUTPUT and the Echo Pin INPUT.

Python Code for Distance Calculation

  • In the below code, we are keeping the Trig Pin LOW for 2 milliseconds:

  • After that, we sent a HIGH signal at the Trig Pin and again make it LOW.

  • The delays are added to the GPIO TRIG pin in accordance with sensor datasheets.
  • Next, we need to calculate the Start and Stop time.
  • As seen in the below code, while the Echo Pin is LOW, we keep on updating the Start Time.
  • Once the Echo Pin gets HGIH, the second while loop will start and we will get the Bounce-back time.
  • NExt, we calculated the Pulse Duration and applied the distance formula.
  • Finally printed the distance formula in Raspberry Pi console.

  • The print function described above won't work, if you are using a Python version lower than 3.0. If this is the case, the print line can be modified as follows:

  • Here are the results:

Ultrasonic Sensors: Drawbacks

It is important to take into account the limits of ultrasonic sensors before making a final decision on which sensor to use.

  • Temperature and humidity affect the speed of sound, which can affect the accuracy of the measurements.
  • Just like any other sensor, they can become clogged, wet, or frozen, causing them to malfunction.
  • In a vacuum, ultrasonic sensors can't work. This is because they need sound, which needs a medium to make it work.

Conclusion

In this tutorial, we learned how to connect ultrasonic sensors to Raspberry Pi 4. In addition, we studied the sensor's fundamentals and the distance calculation etc. Next, we'll learn how to interface a DHT11 sensor with Raspberry Pi 4 board. Till then, take care. Have fun!!!

Control Servo Motor with Raspberry Pi 4 using Python

Hello friends, I hope you all are doing well. Welcome to the 11th tutorial of our Raspberry Pi programming course. In the previous chapter, we have seen how to regulate the speed of a Stepper motor with Raspberry Pi 4. Today, we'll work on the servo motor and will control it with RPi4. So, let's get started:

Components Required:

We will need the following components to control Servo Motor with Raspberry Pi 4:

  • Raspberry Pi 4.
  • Servo Motor.
  • Male-to-female jumper wires.

What is a servo motor?

  • A Servo Motor is a simple DC motor with a position feedback Control System and a gearbox.
  • A Servo Motor's primary advantage is its ability to maintain its shaft's angular position at any desired angle i.e. if we want to keep our shaft at 67 degrees, we can easily achieve that with a servo motor.
  • In most cases, a servo motor's sweep area is 180 degrees or 90 degrees on either side.

  • Servo Motors come in a variety of styles and sizes. Tower Pro SG90 and Tower Pro MG90S are two of the most popular Servo Motors.
  • The gearbox in the Servo motor could be metallic or plastic.
  • We will use SG90 Servo Motor in today's project and it has a  plastic gearbox, shown in the below figure:

The Tower Pro SG90 Servo Motor has 3 wires in total, which are:

  • Signal(Orange or Yellow)
  • VCC (Red)
  • GND(black)

Vcc and GND pins of the servo motor should be connected to the power supply. The Servo Motor's Signal Wire should be connected to the Controller's GPIO Pin.

Types of Servo Motors

There are three wires in a standard servo motor: one for power control, one for ground, and one for neutral. Their intended purpose determines the size and shape of these motors.

There are unlimited possibilities in Robotics where we can use Raspberry Pi to control servo motors.

DC Servo Motors

DC servo motors usually have separate DC sources for the stator and armature windings. The armature current and the field current can be controlled to get the desired result.

AC Servo Motors

An AC servo motor, which incorporates an encoder, is employed for closed-loop control systems. This motor may be precisely positioned and regulated to meet the application's needs. Better bearings and higher tolerances are common in these motors, and higher voltages are sometimes used in simple designs to boost torque. When it comes to robotics, CNC machines, and other automated systems, servo motors are preferred because of their accuracy and precision.

Positional Rotation Servo Motor

It is the most commonly used servo motor and has a rotation of approximately 180 degrees. To keep the rotation sensor safe, it has physical brakes built into the gear mechanism. Many of these popular servos are used in radio-controlled water, radio-controlled automobiles, airplanes, robotics, toys, and many more applications.

Linear Servo

Additional gears transform the servo motor output from circular motion to back-and-forth motion.

Servo Motor Working Principle

A servo mechanism consists of three main components i.e.

  • DC Motor.
  • Feedback.
  • Control Electronics.

The servo motor uses a permanent magnet DC motor with an inbuilt tachometer to calculate the output voltage. The electronics drive provides motors with electrical power in response to tachometer feedback voltages. After setting a commanded speed using a closed velocity loop, the driver's circuitry compares the tachometer feedback voltage to the goal speed. The velocity loop monitors the tachometer feedback and the commanded velocity while the driver modulates the power in the motor.

A sophisticated servo motor system has multiple integrated loops configured to optimal performance for the most precise motion control. For current, velocity, and location, the system uses feedback loops with high precision. To adjust parameters in real-time, each loop notifies the next and checks the feedback elements.

The current loop, also known as the torque loop, is the foundation for all other loops. An electric motor's acceleration or thrust is determined by the relationship between current and torque (or force, in the case of a linear motor). A current sensor is a device that measures the amount of current flowing through the motor and communicates this information to the user. Control electronics frequently receive proportional signals via analog or digital techniques. Ordered signals are subtracted from this signal. The servo motor needs to run at the specified current for an extended period to keep the loop intact. It will then update at sub-second intervals until it reaches the desired current.

Similarly, the velocity loop works with a voltage proportional to velocity in the same method. At low velocities, the current loop receives a command from the velocity loop to increase voltage.

The velocity loop is fed a velocity command from a PLC or motion controller that supplies the required current for acceleration and deceleration of the motor. The servo mechanism is controlled precisely and smoothly by the three loops working together in perfect harmony.

It doesn't matter if it's brushed or brushless, rotatory, or linear. The servo system receives feedback from various sensors, i.e. potentiometers, encoders, linear transducers etc. This system's capabilities are rounded out by an electronic control system that verifies feedback data and command references to make sure the servo motor is performing as instructed. Multi-axis milling centers use brushless motors and motion control systems more complex than those used in recreational applications.

How to Control a Servo Motor?

Pulse Width Modulation is required to operate a servo motor. The pulse's width or length controls the servo motor's shaft position when using the PWM approach.

There is a defined frequency for the PWM signal, determined by the type of Servo Motor being used. The PWM Frequency of our SG90 and MG90S Servo Motors is 50Hz.

A pulse width signal of one millisecond (one-thousandth of a second) sets the servo's position to the LEFT. This post has a duty cycle of 0.5 percent.

As with pulse widths of 1.5 and 2 microseconds, the servo is set to MIDDLE (7.5% duty cycle) and FAR RIGHT with a duty cycle of 10%.

Circuit Diagram of Raspberry Pi Servo Motor Interface:

  • Here is a diagram of the Raspberry Pi Servo Motor Interface's circuit:

  • As you can see in the above figure, a single PWM Pin(GPIO25) of the Raspberry Pi 4 is used to control the Servo position.
  • Servo Vcc is connected to 5V, while the GND is connected to the Ground of Raspberry Pi 4.
  • Here's a wiring diagram that can help you visualize the connections better:

  • Here's our hardware setup of Servo Motor with Raspberry Pi 4:

  • The motor has three wires: red, brown, and orange, which you should pay attention to. The color red denotes positive(Vcc), while the color brown denotes negative(GND).

  • Pulse-width modulation control signals are sent through the orange wires. So, we have connected 3 wires with the pins of Raspberry Pi 4.

  • We have used jumper cables, as depicted in the image below:

Python Code for Servo Control with Raspberry Pi 4

Now let's design the Python code for Servo Motor Control using Raspberry Pi. We'll be using our favorite code editor, Thonny, so get it up and running on your Raspberry Pi:

Importing libraries

  • Importing the necessary libraries is the first step. Time and the GPIO of the Raspberry Pi in this scenario.

GPIO board mode

  • When the GPIO numbering mode is changed, it will be consistent with the board's numbering system.

Configuring PWM GPIO

  • Now, set Pin11 to be the output:

  • After that, we'll create a variable. I used PWM to name my servo's Pin11. 50 is the pulse frequency at Pin11, while 11 is the PIN.

Start PWM

Rotate the Servo shaft

Variable duties are defined and assigned random values, such as 2. When counting our intervals, it serves as the starting point.

After that, we'll run a for loop to find all the duty values between 2 and 17. Given the range of 2 to 17 as an interval, The motor will move the shaft if duty is increased by one every time the shaft moves. After every one-second interval, the shaft rotates 12 degrees to the right until it reaches 180 degrees.

Let's turn the shaft back

  • Changing the duty cycle is all it takes to reset the shaft to 0 degrees.

Clean up

  • The following code snippet is used to clean the pins.

Final Servo Output

  • When all of the code in the example above is run, the motor shaft will be rotated 180 degrees back and forth.

You can experiment with multiple motors to see how much fun this can be. This project's complete source code can be seen below:

Working on the setup

When it comes time to put the concept into action, we'll take advantage of Raspberry Pi's PWM functionality. If you've been following along, you know that the Servo Motor position changes depending on the PWM signal from the Raspberry Pi.

To achieve a sweeping effect from the Servo Motor, we need to alter the PWM signal's Duty Cycle between 5% and 10%, corresponding to the extreme left and right positions.

If you look at the code, you'll see that the duty cycle steadily increases from 5% to 10%, with a 0.5 percent increase at each stage. The reversal will commence as soon as it hits 10%.

Applications of servo motors

Many applications can benefit from regulating the angle of rotation of the Servo Motor via the Raspberry Pi, such as:

Cameras, telescopes, and antennas

It is impossible to find a radio signal, take pictures of a galaxy billions of light-years away, or photograph a live subject without using a servo motor.

Elevator

It's all about safety while designing and implementing transportation networks for buildings. Servo motors are extensively used in elevators in some of the world's highest buildings to carry passengers safely and smoothly.

Robotics

Robotics is a hot topic, and their practical applications are growing at an ever-increasing rate. Servo motors, which are compact, powerful, and precise due to their changing size and force density, are the most widely utilized in robotics. Using robots to control the detonation of bombs, autonomous firefighter trucks, or even the joints in robot arms is all possible.

Industrial production

To eliminate the risk of human error and speed up production, manufacturers are creating robotic alternatives. Another robot example is the pick and place robot, which can move items from one side of an industrial building to the other. Servo motors are commonly utilized when mobility or rotations could be hazardous.

Precision and power are critical features of servo motors, which are used in bending and cutting metal sheets and high-speed milling machines. Servo motors are commonly employed in the spinning sections of conveyor systems in various industries, such as the food and beverage industry.

Conclusion

Congratulations! You have made it to the end of this tutorial. We have seen how PWM is used to control a servo motor. A variety of servo motor designs and real-world applications have also been demonstrated and their application in real life. In the next tutorial, we will learn how to interface an LDR Sensor with Raspberry Pi 4. Thanks for reading. Have a good day.

Control Stepper Motor with Raspberry Pi 4 using Python

Hello friends, I hope you all are having fun. Welcome to the 10th tutorial of our Raspberry Pi programming course. In the last chapter, PWM was utilized to regulate the DC motor's speed and direction with a motor driver L293D. In this chapter, we'll advance our skills with PWM and use it to control a stepper motor using the same motor driver L293D.

Here's the video demonstration of this project:

Let's get started:

Components Required

Here's the list of components, which we will use to control the speed and direction of Raspberry Pi 4:

  • Raspberry Pi 4.
  • Stepper Motor.
  • Motor Driver IC(L293D).
  • Jumper wires.
  • 9V Battery.
  • Breadboard.

The Raspberry Pi with desktop is required for this project. An SSH connection can be made, or the RPi can be shown on an LCD screen with a keyboard, and mouse. (We discussed this in previous chapters)

What is Stepper Motor?

  • A stepper motor(step motor or stepping motor) is an asynchronous, brushless DC motor having electromagnets(stator) to rotate the rotor in a number of equal steps.

  • The Stepper motor gives precise movement and its precision increases with the increase in electromagnets used.
  • The Stepper motor has normally 4 or 6 wires to control the motion.
  • The electromagnets are turned ON and OFF in a sequence in order to make the rotor rotate.
  • Stepper motors are used in applications where high torque at low speed is required.
  • Because of its precise & accurate movement, its normally used in open-loop projects.

Stepper Motor Working Principle

  • The below image shows the internal structure of a simple stepper motor, I have designed it for explaining the stepper working.

  • As you can see in the above figure, it has a rotor in the center surrounded by 4 pairs of stator coils(electromagnets).
  • When current passes through this stator coil, a magnetic field is generated around it.
  • This magnetic field attracts the rotor towards it.
  • In the first figure of the below image, pair A stator coil got energized and aligned the rotor.

  • In the second figure, the coil A pair got de-energized, while the coil B pair got energized and the rotor aligned itself with pair B by taking a rotation of 60 degrees.
  • In the third figure, the coil B pair got de-energized, while the coil C pair got energized and the rotor now aligned with coil C and thus covered another 60 degrees.
  • That's how the rotor completes its rotations in the stepper motor.
  • This switching of coils is carried out in nanoseconds.

L293D Motor Driver IC

We will use an L293D motor driver to control the direction and speed of the stepper motor. In our last lecture, we controlled the DC motor with the same driver i.e. L293D and I explained it's working & why we use it? in detail there. So, please check that tutorial out, if you are new to this motor driver.

  • L293D Pinout is shown in the below figure:

  • In the last lecture, we discussed that 2 DC motors can be controlled by a single L293D chip at the same time because a normal DC motor has 2 pins in total.
  • But Stepper motors have either 4 or 6 pins to control their rotation.
  • So, we can control only 1 Stepper Motor from a single chip of L293D.
  • Four controlling pins of stepper motors are connected to the Output pins of L293D.

Stepper Motor with RPi4 Circuit Diagram

The below figure shows the circuit diagram of Stepper motor interfacing with Raspberry Pi4:

  • As you can see in the above figure, we have used all 4 input pins of L293D to control a single stepper motor.
  • The rest of the circuit is the same as that of the DC Motor Control i.e. Vss is provided with 3.3V, Vs is connected to the +9V from the battery, GND of battery & Rpi4 is connected to the GND of L293D motor driver.
  • Moreover, both the Enable Pins of L293D are connected to Rpi4 GPIOs.

.

The wire mappings from my Raspberry Pi 4 to a stepper motor driver are shown in the below diagrams:

 

Python Code for Stepper Control with RPi4

Open Thonny text editor. Importing the GPIO and time modules is the first step. Make sure you type the GPIO module's name exactly, case-sensitively, on the first line.

  • Set the mode of GPIO pins to the board:

  • Set up the control pins, which are going to connect to the Input pins of L293D:

  • Use a for loop to set all the pins as output:

  • Create a sequence list, 1 being high and 0 being low.
  • As you can see in the below code, this sequence is turning ON the consecutive coils.

  • Take user input for the number of rotations:

  • Substitute the input value for the rotation and place a for loop to move the stepper motor in steps using this code.

  • Finally, clean up the pins after the code execution is complete:

Conclusion

Congratulations! You have made it to the end of this tutorial. We have seen how PWM is used with a motor driver IC to control a stepper motor. We have also seen different stepper motor control techniques, how to set up our circuit diagram, and how to write a Python program that controls the steps for our motor. In the next tutorial, we will have a look at how to control a Servo Motor with Raspberry Pi 4 using Python. Till then, take care and have fun !!!


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