Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Breadboard | Amazon | Buy Now | |
2 | DC Motor | Amazon | Buy Now | |
3 | Jumper Wires | Amazon | Buy Now | |
4 | Raspberry Pi 4 | Amazon | Buy Now |
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.
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.
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."
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.
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.
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.
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.
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.
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 (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.
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:
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 =
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:
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
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.
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
Fig. 4 New Project
Fig. 5 Select Interpreter
Image: 6 MicroPython for raspberry Pi Pico programming
Image: 7 Ready to program
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
Fig. 13 Save the program
Fig. 14 Save the program
Fig. 15 Run the saved program
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)
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
Fig. 17 Brightness level 1
Fig. 18 Brightness level 2
Fig. 19 Brightness level 3
Fig. 20 PWM pin details
Fig. 21
Fig. 22 Plotter
Fig. 23 Rising PWM output 0 to 65535 (brightness increasing)
Fig. 24 PWM output maximum to 0
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:
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)
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
Fig.27 PWM frequency
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
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.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Breadboard | Amazon | Buy Now | |
2 | Jumper Wires | Amazon | Buy Now | |
3 | Raspberry Pi 4 | Amazon | Buy Now |
Connect button pushes to function calls using the Python gpiozero package and uses the Python dictionary data structure
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.
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.
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.
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:
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.
The first step is to notify bash that you wish to work with all the files inside the folder.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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. | Components | Distributor | Link To Buy | |
1 | Raspberry Pi 4 | Amazon | Buy Now |
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.
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;
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.
Slide the cord into the port by using an image as a guide. Finally, press down tabs, securing the cable to the motherboard.
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.
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:
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.
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.
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.
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.
A Python library named phototimer will be used to control the raspistill command-line that comes pre-installed on the Raspbian OS.
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.
A new location does not necessitate an SSH login. The lapse of time will be restarted.
Download the Docker image, activate the camera interface, and start the container instead of executing a git clone on each device.
If you disconnect from the container, docker will keep track of the log information and will enable you to reconnect at any time.
We can easily set up docker with the following set of commands.
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:
By modifying the config.py file, you can change the time-appearance lapses and duration.
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.
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.
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.
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.
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:
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.
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.
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:
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.
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.
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.
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.
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.
You must activate ssh on your Raspberry Pi to use SCP.
A free program like Giphy can help you convert the videos to a GIF; however, this will lower the number of frames.
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.
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.
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.
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
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.
Fig.
Steps included in programming the Raspberry Pi Pico to make the onboard LED to blink are:
“from machine import Pin, Timer”
“led = Pin(25, Pin.OUT)”
“ led.toggle()”
Fig. Save the program
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.
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)
Fig. Blinking On-board LED
Table 1
Fig. Iterfacing LED with Raspberry Pi Pico
Steps included in programming the Raspberry Pi Pico to make the peripheral LED to blink are:
“from machine import Pin”
“import time”
Create an object ‘led’ from pin14 and set GPIO pin14 to output.
“led=Pin(14,Pin.OUT)”
“while True:"
“led.value(1)”
“time.sleep(1)”
“led.value(0)”
Fig. Interfacing and Blinking LED with raspberry Pi Pico
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)
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.
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.
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:
Here's the list of components:
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.
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.
Here's the circuit diagram of the DS18B20 temperature sensor and a 16x2 LCD display, connected with Raspberry Pi 4:
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:
Before start working on our code, we need to first install the LCD Python library and enable the 1-wire protocol in RPi board.
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:
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.
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.
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:
This is what you can expect to see in your terminal windows:
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.
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.
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:
Temperature sensors can be used in a variety of ways, so here are some examples.
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.
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:
Here's the list of components, we are going to use in today's circuit:
DHT11 is a low-cost digital sensor, used to measure temperature and humidity in the surroundings. DHT sensor has three main components i.e.
Now, let's have a look at the Pinout of DHT11 sensor:
DHT11 has 4 pins in total, which are:
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.
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.
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.
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.
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.
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.
While the BMP280 only monitors temperature and air pressure, the BME280 has a humidity measurement in addition.
DS18B20 is a one-wire temperature sensor and gives accurate values up to 4 decimal digits.
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.
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.
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.
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.
To connect the DHT11 sensor to the Raspberry Pi, the following steps must be followed.
Now, Raspberry Pi 4 has to be connected to the 16x2 LCD screen:
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:
We need to install the DHT11 Adafruit library to read the sensor values from Raspberry Pi 4.
Now let's design our Python code:
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:
Monitoring or controlling environmental quality is the main goal of environmental monitoring. The DHT11 humidity and temperature sensors are widely used in such systems.
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 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.
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.
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:
Here's the list of components, we are going to use in today's project:
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.
The Ultrasonic Sensor has four connections:
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.
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:
As we discussed in the Pinout section, Ultrasonic Sensor has 4 pins in total.
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:
Now let's design it with real hardware:
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:
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.
It is important to take into account the limits of ultrasonic sensors before making a final decision on which sensor to use.
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!!!
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:
We will need the following components to control Servo Motor with Raspberry Pi 4:
The Tower Pro SG90 Servo Motor has 3 wires in total, which are:
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.
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 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.
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.
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.
Additional gears transform the servo motor output from circular motion to back-and-forth motion.
A servo mechanism consists of three main components i.e.
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.
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%.
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:
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.
You can experiment with multiple motors to see how much fun this can be. This project's complete source code can be seen below:
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%.
Many applications can benefit from regulating the angle of rotation of the Servo Motor via the Raspberry Pi, such as:
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.
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 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.
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.
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.
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:
Here's the list of components, which we will use to control the speed and direction of Raspberry Pi 4:
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)
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.
The below figure shows the circuit diagram of Stepper motor interfacing with Raspberry Pi4:
The wire mappings from my Raspberry Pi 4 to a stepper motor driver are shown in the below diagrams:
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.
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 !!!