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.

Implementing PWM with Raspberry Pi Pico using MicroPython

Hello readers, I hope you all are doing great. In our previous tutorial, we discussed the implementation of LED interfacing and blinking program with Raspberry Pi Pico using MicroPython programming language. So continuing with our previous tutorial, in this tutorial we will learn how to control the LED brightness using PWM (pulse width modulation technique).

As we mentioned above, in our previous tutorial we implemented the LED blinking program with a Raspberry Pi Pico board. Blinking an LED means turning ON and OFF and thus the process involves only two states that are ‘1’ (HIGH) and ‘0’ (LOW). But, sometimes it is required to change the digital output between these two (ON and OFF states) for example changing the LED brightness. PWM or Pulse Width Modulation technique is used to change the brightness of the LED.

Raspberry Pi Pico PWM

Raspberry Pi Pico (RP2040) offers 40 pins which include power supply pins, General Purpose Input Output (GPIOs) pins, ADC, PWM etc. where most of the pins are multifunctional except power supply pins. Almost all the GPIO pins (30 pins) can be used to implement pulse width modulation technology.

Fig. 1 Raspberry Pi Pico Pi-Out

RP2040 offers 16 PWM channels and each channel is independent of another. Means we can set the duty cycle and frequency for one channels without affecting the others. These PWM channels are represented in the form of slices or groups and each slice contains two PWM outputs channel (A/B). There are total 8 slices and hence 16 channels. The pin B from PWM (A/B) can also be used as an input pin for duty cycle and frequency measurement.

The PWM channel provided in RP2040 are of 16 bit resolution which means maximum PWM resolution is 2^16 or ranges between 0 to 65536.

For more information on Raspberry Pi Pico’s PWM channels you can visit the Raspberry Pi organization’s official website: https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf

 

Before programming the Raspberry Pi Pico for PWM implementation let’s first understand the concept of Pulse Width Modulation.

PWM

Fig. 2 Pulse width modulated signal

Pulse Width Modulation (or PWM) is a modulation technique used for controlling the power delivered to a load or external/peripheral devices without causing any power loss by pulsing the direct current (DC) and varying the ON time of the digital pulse. Using a digital input signal, the Pulse Width Modulation technique produces modulated output signals.

The following factors influence the behaviour of a pulse width modulated signal:

  1. Frequency
  2. Duty Cycle
  3. Resolution

Frequency : Technically, frequency means “number of cycles per second”. When we toggle a digital signal (ON and OFF) at a high frequency, the result is an analog signal with a constant voltage level.

The number of cycles per second defined by a signal's frequency is inversely proportional to the time period. PWM frequency is determined by the clock source. The frequency and resolution of PWM are inversely proportional.

Duty Cycle : It is the ratio of ON time (when the signal is high) to the total time taken to complete the cycle.

Duty Cycle =

  • The duty cycle is represented in the form of percentage (%) or ratio.

Fig. 3 Duty cycle

Resolution: A PWM signal's resolution refers to the number of steps it can take from zero to full power. The resolution of the PWM signal can be changed. For example, the Raspberry Pi Pico module has a 1- 16 bit resolution, which means we can set up to 65536 steps from zero to full power.

Various applications of Pulse Width Modulation technique are:

  • Speed control of DC motor
  • Direction or position control of a servo motor
  • To control the LED brightness
  • Loudness control in buzzers
  • Measurements purpose
  • Controlling the fan speed

Software and Hardware Components Required

  • Raspberry Pi Pico Module
  • Latest version of Python
  • Latest version on Thonny IDE should be installed on your system
  • MicroPython setup installed in Raspberry Pi Pico
  • Breadboard
  • LED
  • Resistor (330 ohm)
  • USB cable

We have already published tutorials on how to download and install the above-mentioned software components.

Follow the given link for a detailed study of Raspberry Pi Pico: https://www.theengineeringprojects.com/2022/04/getting-started-with-raspberry-pi-pico.html

Programming Raspberry Pi Pico with MicroPython

To program the Raspberry Pi Pico board there are various development environments available (like uPyCraft IDE, Visual Studio Code, Thonny IDE ect.) and multiple programming languages as well.

In this tutorial, we are going to use Thonny IDE to program the Raspberry Pi Pico board.

Installing Thonny IDE for Raspberry Pi Pico Programming:

We have already published a tutorial on installing Thonny IDe for Raspberry Pi Pico Programming. Follow the given link to install the IDE: https://www.theengineeringprojects.com/2022/04/installing-thonny-ide-for-raspberry-pi-pico-programming.html

Steps to write a program for LED brightness conrtol are:

  • Open the installed Thonny IDE for all users.
  • Connect the Raspberry Pi Pico development board with your system (laptop or desktop).
  • To create a new project; go to Files >> New.

Fig. 4 New Project

  • Connect the Raspberry Pi Pico board with laptop/desktop using USB cable.
  • Click on the ‘MicoPython(Raspberry Pi Pico)’ option from lower right corner in-order to select the interpreter for raspberry Pi Pico programming using MicroPython programming language. We already selected the one from lower right corner menu from the Thonny IDE window.

Fig. 5 Select Interpreter

  • Select interpreter ‘MicroPython (Raspberry Pi Pico)’ for Raspberry Pi Pico programming.

Image: 6 MicroPython for raspberry Pi Pico programming

  • You should see this MicroPython Version details in Shell section (to ensure that Thonny is ready to program your Raspberry Pi Pico board) as shown below:

Image: 7 Ready to program

MicroPython program to change the brightness of peripheral LED.

In this example code we will implement the pulse width modulation on the digital output pin (GPIO 14). The brightness of the will vary from minimum to maximum brightness back and forth. The maximum possible resolution is 16 bit that is 2^16 (or 0 – 65535). Let’s write and understand the MicroPython program for PWM implementation:

The first task is importing library files necessary for PWM implementation. We are importing two libraries first one is to access the GPIO pins and another one is to implement pulse width modulation techniques. We also need to import ‘time’ library file to add some delay.

Fig. 8 Import libraries

To define the GPIO pin to be used as a PWM pin a ‘PWM()’ function is used which further contains the ‘Pin()’ function that is passing the PWM GPIO (14) pin number.

The PWM function is further represented using a ‘led’ object. If you are not familiar with the PWM pin details like to which slice and channel the pwm pin belongs, you can get the respective details using print(led) function.

Fig. 9 declare object

The led.freq() command is used to set frequency rate at which the digital pulse will be modulated.

Fig. 10 Frequency of modulation

Inside the while loop we are using two for() loops. First one to change the LED brightness from minimum to maximum resolution (‘0’ to ‘65525’ ).

Fig. 11

Another for loop() is used to set the LED brightness from maximum resolution (65535) to ‘0’ (minimum resolution).

The process will be repeated back and forth due to the ‘while()’ loop.

Fig. 12

Save and test the PWM program

    1. Click on the ‘save’ icon to save the PWM program.

Fig. 13 Save the program

  1. After clicking on the ‘Save’ icon, an option ‘Where to save to?’ will pop-up. You can select any of the ‘Raspberry Pi Pico’ option.

Fig. 14 Save the program

  1. Run the program once it is successfully saved to change the LED brightness by clicking on the ‘Run’ icon as shown below:

Fig. 15 Run the saved program

Code

from machine import Pin, PWM

import time

led = PWM(Pin(14))

print(led)

led.freq(1000)

while True:

for duty in range(0, 65535):

led.duty_u16(duty)

print(duty)

time.sleep(0.001)

for duty in range(65535, 1):

led.duty_u16(duty)

print(duty)

time.sleep(0.001)

Testing and Results

Let’s interface a peripheral LED with raspberry Pi Pico. As mentioned in the code description the GPIO 14 pin is configured as PWM pin. Connect the LED with raspberry Pi Pico board. The connections of LED with Raspberry Pi Pico board are shown in Table 1.

Table 1

Schematic of LED interfacing with raspberry Pi Pico is shown below:

Image: 16 LED Interfacing with Raspberry Pi Pico

  • The results of the pulse width modulation implementation on LED are shown in the images attached below.
  • In the first image the LED brightness is very low.

Fig. 17 Brightness level 1

  • In the second image the LED brightness is slightly increased than the previous one.

Fig. 18 Brightness level 2

  • The third image represents the maximum brightness level.

Fig. 19 Brightness level 3

  • If you are not familiar with the PMW pin details we can the details of respective pwm pin using print command ‘pritn(“enter the pwm pin here”)’.
  • The image attached below represents the PWM pin details like to which slice and channel the PWM pin (GPIO 14) belongs.
  • As we can see from the image attached below that PWM slice is ‘7’ and channel is ‘0’.

Fig. 20 PWM pin details

  • We can also visualize the PWM output on Thonny IDE.
  • In Thonny IDE there is a ‘plotter’ feature available for graphical representation.
  • To enable the plotter feature, go to View and check the plotter option.

Fig. 21

  • Now you should see the plotter section on the right side of Shell

Fig. 22 Plotter

  • The duty cycle is printed in both Shell and Plotter using print()
  • The image attached below, represents the pulse width modulated output observed from the GPIO 14 PWM pin during rising edge (0 to 65535) or while the LED brightness increasing.

Fig. 23 Rising PWM output 0 to 65535 (brightness increasing)

  • Pulse width modulated output during falling edge or decreasing LED brightness (65535 to 0) is shown in the image attached below:

Fig. 24 PWM output maximum to 0

Implementing Pulse Width modulation with multiple LEDs

Now let’s take another example where we will interface multiple LEDs (16) with Raspberry Pi Pico board and then will implement pulse width modulation on those LEDs.

The procedure of interfacing and programming with Thonny IDE using MicroPython will remain similar to the previous example.

Fig. 25 Interfacing Multiple LEDs with Pico

Let’s write the code:

Code

from machine import Pin, PWM

import time

led_1 = PWM(Pin(5)) # declaring led_x object for PWM pins

led_2 = PWM(Pin(6))

led_3 = PWM(Pin(8))

led_4 = PWM(Pin(9))

led_5 = PWM(Pin(10))

led_6 = PWM(Pin(13))

led_7 = PWM(Pin(14))

led_8 = PWM(Pin(15))

led_9 = PWM(Pin(16))

led_10 = PWM(Pin(17))

led_11 = PWM(Pin(18))

led_12 = PWM(Pin(19))

led_13 = PWM(Pin(20))

led_14 = PWM(Pin(21))

led_15 = PWM(Pin(22))

led_16 = PWM(Pin(26))

print(led_1)

def led_freq(x):

led_1.freq(x)

led_2.freq(x)

led_3.freq(x)

led_4.freq(x)

led_5.freq(x)

led_6.freq(x)

led_6.freq(x)

led_7.freq(x)

led_8.freq(x)

led_9.freq(x)

led_10.freq(x)

led_11.freq(x)

led_12.freq(x)

led_13.freq(x)

led_14.freq(x)

led_15.freq(x)

led_16.freq(x)

led_freq(1000) # setting pulse width modulation prequency

while True:

for duty in range(0, 65535): # Increasing LED broghtness

led_1.duty_u16(duty)

led_2.duty_u16(duty)

led_3.duty_u16(duty)

led_4.duty_u16(duty)

led_5.duty_u16(duty)

led_6.duty_u16(duty)

led_7.duty_u16(duty)

led_8.duty_u16(duty)

led_9.duty_u16(duty)

led_10.duty_u16(duty)

led_11.duty_u16(duty)

led_12.duty_u16(duty)

led_13.duty_u16(duty)

led_14.duty_u16(duty)

led_15.duty_u16(duty)

led_16.duty_u16(duty)

print(duty) # Print the duty Cycle

time.sleep(0.001)

for duty in range(65535, 0): # deccresing LED brightness

led_1.duty_u16(duty)

led_2.duty_u16(duty)

led_3.duty_u16(duty)

led_4.duty_u16(duty)

led_5.duty_u16(duty)

led_6.duty_u16(duty)

led_7.duty_u16(duty)

led_8.duty_u16(duty)

led_9.duty_u16(duty)

led_10.duty_u16(duty)

led_11.duty_u16(duty)

led_12.duty_u16(duty)

led_13.duty_u16(duty)

led_14.duty_u16(duty)

led_15.duty_u16(duty)

led_16.duty_u16(duty)

print(duty)

time.sleep(0.001)

Code Description

As we mentioned in the introduction part raspberry Pi Pico has 8 PWM slices and 16 PWM channels. So in this example code we are interfacing 16 LEDs with PWM pins.

Most of the code instructions and commands are similar to the previous example. Here we declare 16 different led objects for 16 different GPIO pins (PWM pins).

Fig. 26 Declaring ‘led’ object

  • Next we created a function ‘led_freq()’ to set the frequency at which pulse width modulation takes place.

Fig.27 PWM frequency

  • The programming part of increasing the and decreasing the brightness of LEDs is similar to the previous example.

Result

In the images attached below, we can see the variation in LED brightness.

Fig. 28 Minimum Brightness Level

Fig. 29 Intermediate Brightness Level

Fig. 30 Maximum Brightness Level

Conclusion

In this tutorial we demonstrated the implementation of pulse width modulation on LEDs with Raspberry Pi Pico module and MicroPython programming language.

Continuing with this tutorial, in our upcoming tutorial we will discuss the interfacing of a servo-motor with raspberry pi Pico and we will also implement PWM on servo motor to control the direction of rotation.

This concludes the tutorial, we hope you find this of some help and also hope to see you soon with a new tutorial on Raspberry Pi Pico programming.

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.

LED blinking with Raspberry Pi Pico and MicroPython

Hello readers, I hope you all are doing great. In our previous tutorials on raspberry pi Pico, we discussed the basic features, architecture, download and installation of development environments for raspberry Pi Pico programming. In this tutorial, we will learn how to access and control Raspberry Pi Pico and its GPIO pins to implement LED blinking using MicroPython.

Introduction

Raspberry Pi development boards are quite popular and frequently used among students and hobbyists. But the drawback of Raspberry Pi is their cost i.e., around $35-$45. So when cost of the development board is of prime importance the users prefer to use ESP8266, ESP32, Arduino, PIC etc. over Raspberry Pi. To overcome this drawback, Raspberry Pi foundations designed a new board i.e., Raspberry Pi Pico which is a cost effective solution for costlier Raspberry Pi boards.

Raspberry Pi Pico is a cost-effective development platform designed by Raspberry Pi which has enough processing power to handle complex task. It is a low cost and yet powerful microcontroller board with RP2040 silicon chip.

Prerequisites

  • Raspberry Pi Pico Module
  • Latest version of Python
  • Latest version on Thonny IDE should be installed on your system
  • MicroPython setup installed in Raspberry Pi Pico

We have already published tutorials on how to download and install the above mentioned software components.

Follow the given link for detailed study of Raspberry Pi Pico: https://www.theengineeringprojects.com/2022/04/getting-started-with-raspberry-pi-pico.html

Programming Raspberry Pi Pico

To program Raspberry Pi Pico board there are various development environments available (like uPyCraft IDE, Visual Studio Code, Thonny IDE etc.) and multiple programming languages as well. In this tutorial, we are going to use Thonny IDE to program the Raspberry Pi Pico board.

Installing Thonny IDE for Raspberry Pi Pico Programming:

We have already published a tutorial on installing Thonny IDE for Raspberry Pi Pico Programming. Follow the given link to install the IDE: https://www.theengineeringprojects.com/2022/04/installing-thonny-ide-for-raspberry-pi-pico-programming.html

The Raspberry Pi Pico board comes with an onboard LED which is internally connected with GPIO 25. So first we will discuss how to access the on board LED and then will interface an external one.

Controlling (Blinking) Raspberry Pi Pico’s on board LED:

  • Open the Thonny IDE.
  • Connect your Raspberry Pi Pico board with your system (laptop or desktop).
  • To create a new project; go to Files >> New.

Fig.

  1. Write the program to blink the inbuilt LED with a particular delay.

Programming

Steps included in programming the Raspberry Pi Pico to make the onboard LED to blink are:

  1. Importing necessary files from machine

“from machine import Pin, Timer”

  1. The onboard LED is internally connected to the GPIO 25 of the raspberry Pi Pico board. So, the next step is creating LED object from pin 25 and setting the GPIO25 as output pin.

“led = Pin(25, Pin.OUT)”

  1. Toggle the LED: toggle() command is used to blink the onboard LED.

“ led.toggle()”

  1. Save the program.
  2. Save the program. We can save the program either on computer or on Raspberry Pi Pico board.

Fig. Save the program

  1. Run the code.

Fig. Run the code

Note: If you are already running a program on Raspberry Pi Pico board then press ‘Stop’ before running a new program.

Code to blink onboard LED

from machine import Pin, Timer

led = Pin(25, Pin.OUT)

timer = Timer()

def blink(timer):

led.toggle()

timer.init(freq=2.5, mode=Timer.PERIODIC, callback=blink)

Result

Fig. Blinking On-board LED

Interfacing peripherals (LED) with raspberry Pi Pico

Table 1

Fig. Iterfacing LED with Raspberry Pi Pico

Programming

Steps included in programming the Raspberry Pi Pico to make the peripheral LED to blink are:

  1. Importing necessary files from machine: We are importing two files one is to access GPIO pins and another for accessing timer functions.

“from machine import Pin”

“import time”

  1. Create LED object: We have multiple GPIOs available where we can interface peripheral LED. So we are using GPIO_14 of Raspberry Pi Pico board.

Create an object ‘led’ from pin14 and set GPIO pin14 to output.

“led=Pin(14,Pin.OUT)”

  1. Making the onboard LED to continuously blink: We are using the ‘while loop’ to make the inbuilt led blink continuously.

“while True:"

  1. Setting LED high: Thevalue()’ command is used to set the peripheral LED as high where we are passing ‘1’ as an argument for HIGH output.

“led.value(1)”

  1. Adding delay: A delay of 1 second is added to make the led blink.

“time.sleep(1)”

  1. Setting LED Low: Argument ‘0’ is passed inside ‘led.value()’ command to set the led as LOW.

“led.value(0)”

  1. Save the program either on Raspberry Pi Pico board or on your system..
  2. If you are already running a program on Raspberry Pi Pico board then press ‘Stop’ before running a new program.

Result

Fig. Interfacing and Blinking LED with raspberry Pi Pico

Code

from machine import Pin, time

led=Pin(14,Pin.OUT) #Creating LED object from pin14 and Set Pin 14 to output

while True:

led.value(1) #Set led turn ON

time.sleep(1)

led.value(0) #Set led turn OFF

time.sleep(1)

Conclusion

This concludes the tutorial, we hope you find this of some help and also hope to see you soon with a new tutorial on Raspberry Pi Pico programming.

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