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!!!
Almost all designers agree that Adobe Illustrator is the best tool for creating vector graphics. You can use the software to create artwork, logos, infographics, artwork, icons, and pretty much anything else you like. Adobe Illustrator uses mathematical formulas to scale images as opposed to pixels, which means resizing might strain your computer, but you get seamless and infinite resizing.
Adobe Illustrator is not free. You get a free seven-day trial and then have to pay $20.99 per month after that.
Affinity Designer is regarded by many as the best Adobe Illustrator alternative. It is great for beginners and experienced designers alike, offering an intuitive interface and user-friendly features. You can also use it for almost all design work, and its two notable features are its 8,000X history steps and 1,000,000% zoom. Both of these features make it perfect for working with clients who want even the smallest details to be perfect.
In the past few years, stickers have grown exponentially in popularity, and it is almost impossible to go a day without seeing at least one sticker in real life or on social media. They are great promotional tools because they can be added to books, flasks, guitars, laptops, social media, and so many other places. With stickers being such useful marketing tools, designers need a way to create them easily.
Picsart Sticker maker makes it easy to make your own stickers, you only have to upload your photo and work on it using the tool. The platform also makes it easier to share all your stickers online or print physical copies for distribution.
Canva is an all-around online design tool that you can use to design almost anything. It uses a drag-and-drop interface that is familiar to many people, and that makes it easy even for beginners to whip up some quick and professional-looking designs.
The tool also comes with lots of backgrounds, templates, fonts, and images to get you started. Do note that you need to pay to get access to some of the assets on the platform.
Canva also stands out due to its social media integration; you can post designs directly from Canva to your accounts.
Pixlr is an image editing tool that is a little different; it does not come with all the tools other apps do. It provides all the basic and essential tools you need without requiring you to learn how to use new tools or integrate them into your workflow. Because of this, Pixlr is perfect if you are looking for a tool to help you complete quick edits.
Pixlr is part of an ecosystem of complementary design tools and supports many of the popular design file formats. It also uses a drag-and-drop interface which makes things a lot easier, even for beginners. As with Canva, it also comes with numerous design tools and templates to get you started quickly.
There are different graphic design tools, apps, and platforms available depending on what you are looking for. For beginners, there are online apps with simple features that get simple products done, while for professionals there is software that makes it easier to handle and complete massive and complex design projects.
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 !!!
Data loss or inaccessibility after a natural disaster is a significant concern. After Hurricane Sandy in 2012, data centers in Manhattan had to extract water from the generator rooms and restore switchgear to become operational. In the U.K., flooding in Leeds caused immense water damage to a Vodafone facility that it had to close for several days.
According to the Insurance Information Institute, over 25% of businesses never reopen after an extreme weather event. Fortunately, preventing disaster-related downtime is possible through proper monitoring systems and a disaster recovery plan.
Knowing which natural disasters to expect based on your server room and data center location can make the difference. Here’s how to protect your facility from the most common natural disasters.
Three levels of fire protection exist.
Your country will have specific fire suppression system standards. Typically, data centers choose between two sprinkler systems, wet pipes or pre-engineered. The former will have water in its pipes which automatically flow once you trigger the fire alarm. The only con is that wet pipe sprinklers can suffer leakage, damaging the servers.
On the other hand, pre-engineered sprinklers require two-point activation to disperse water. It’s also the preferred choice for many businesses. Depending on the model, some pre-action sprinklers operate on a quadrant level. Therefore, they will only disperse water in that specific area once activated. Like the wet piping, this system poses a risk of water damage, so you should consider installing a gaseous system instead.
Gaseous systems employ a clean agent or inert gas. The latter uses nitrogen and argon to reduce the oxygen in the server room, thereby putting out the fire. Note that you will need to install sound muffling equipment to prevent damage to hard drives.
Clean agent systems like FM-200 are a better option. They eliminate the fire through absorption. Also, they have low emissions and are non-conductive and non-corrosive, making them environmentally friendly.
Regular inspections ensure you stay compliant. Typically, the expert will confirm that the suppression systems and fire alarm is in good condition. More importantly, they’ll inspect whether the fire protection interface meets the sensitivity prerequisites.
Flooding can cause grave consequences from short circuits to corrosion. Besides rainfall-related flooding of a server room, several water sources can threaten the data security of your server room. These include:
Before taking action, you’ll need to perform a risk assessment to determine areas that require water leakage detection.
Monitoring systems are the simplest way to detect water leakage to prevent water damage. Various systems are available in the market. Typically, businesses choose between zone leak and distance-read leak monitoring systems. Zone leak detection is the ideal choice for small server rooms. In comparison, distance-read monitoring systems are suitable for large server rooms precisely because they can pinpoint the exact location
Which system should you choose? We recommend a centralized one that detects water leakage and humidity, motion, plus ambient temperature. A vital aspect of this system is a distribution list for fire alerts. Emails, SNMP, and SMS are excellent circulation, monitoring, and reporting channels.
Different leak detection cable runs range between two and fifty meters. These cables can go under power cables. And if any water starts leaking from the air conditioning systems or backup drains, these cables can detect with pinpoint precision and let you know the exact floor tile.
In case of leakage, swift action is paramount to save equipment and other items in the server room. An experienced water damage remediation company will perform immediate water extraction and contents restoration.
Earthquakes impact the most damage to server rooms and data centers than any other natural disaster. Approximately 500,000 incidents occur globally. The double aftermath of IT equipment damage and downtime can result in business closure. And although the world is yet to come up with tech that would predict the exact time and location of an earthquake, there are seismic planning activities you can do to protect your servers.
Rigid bolting is the most common server protection approach. Doing so secures equipment racks to the floor. And as a result, it prevents the server racks from vibrating during an earthquake. While you may want to perform cabinet bolting instead, this method only protects the employees, and servers can only escape damage if it’s a mild earthquake.
Base isolation technology is a more effective earthquake protection method. It works by significantly decreasing the path through which vibrations pass. As a consequence, it channels the seismic motions away from your servers. If your data center is located in an earthquake-prone area, base isolation systems ensure your business achieves tier 4 classification, i.e., zero disruption to the critical load.
Preventing power outages in your server room is perhaps the primary focus when preparing for hurricanes.
Here’s what you can do.
Natural disasters have proven to be a significant threat to data centers. For some businesses, the equipment damage is beyond repair, and for others, the downtime results in loss of customer trust. Having robust monitoring and report systems can mitigate disaster-related damage, thereby ensuring business continuity. Preparedness always pays off. Ultimately, leaving your servers unprotected with such high stakes would be a miscalculation.
The kind of data generated in every business environment varies, and these data sets only become useful once they are harnessed to give useful insights. Data engineers are the professionals often tasked with building and maintaining key systems that collect, manage and convert these data sets.
The huge amount of data generated in different industries has expanded the data engineering profession to cover a wide range of skills, including web-crawling, distributed computing, data cleansing, data storage, and data retrieval.
Over the years, data storage has become a subject of interest in the data engineering field, thanks to the rise of modern data storage options. Most data engineers and scientists are familiar with SQL databases such as MSSQL, PostgreSQL, and MySQL, but the shift in preference is slowly changing this narrative.
The need for speed, flexibility, and adaptability has also become apparent in data handling, and non-conventional data storage technologies are now coming to market. Several businesses are also embracing storage as a service solution, and the trend is just getting better. Below, we have discussed the three data storages that are increasingly becoming popular among data engineers.
Search engines, documents stores, and columnar stores are the three technologies that are seeing wider adoption in the data handling field. Here’s a quick overview of how they operate and why they are becoming storage options of choice.
When defining data storage in the data engineering field, three critical aspects are used to score the best storage solutions. These are data indexing, data sharing, and data aggregation.
Ideally, each data indexing technique improves specific queries but undermines others. So knowing the kind of queries used can often help you choose the right data storage option.
Data sharding is a process in which a single dataset is split and distributed across multiple databases so they can be stored in various data nodes. The goal is often to increase the total storage capacity of a given system. Sharding determines how the data infrastructure will grow as more data is stored in the system.
On the other hand, data aggregation is the process where data is collected and expressed in a more summarized manner before they are ready for statistical analysis. The wrong data aggregation strategy can limit the performance and the types of reports generated. Below, we’ve broken down the three data storage types based on the data indexing, sharding, and aggregation capabilities.
Search engine storage Elasticsearch is a data store that specializes in indexing texts. Unlike the traditional data stores that create indices based on the values in the field, this storage type allows for data retrieval with only a fragment of the text field. This is also done automatically through analyzers. The latter are modules that create multiple index keys after evaluating the field values and breaking them into smaller values.
Elasticsearch is built on top of Apache Lucene and provides a JSON-based REST API that refers to Lucene features. Scaling is often done by creating several Lucene shards and distributing them to multiple servers/nodes within a cluster. Therefore, each document is routed to its shard through the id field. When retrieving data, the master server sends each shard/ Lucene instance a copy of the query before it finally aggregates and ranks them for output.
Elasticsearch is document-based storage whose content can be bucketed by ranged, exact, or geolocation values. The buckets can also be grouped into finer details through nested aggregation. Metrics such as mean and standard deviations can be calculated easily for every layer, making it easy to analyze several parameters in a single query. However, it suffers the limitation of intra-document field comparisons. A solution is often to inject scripts as custom predicates, a feature that works for one-off analysis but is often unsustainable due to degraded performance in production.
MongoDB is a generic data store with lots of flexibility for indexing a wide range of data. However, unlike Elasticsearch, it’s designed to index the id field by default; hence you’ll need to manually create indices for the commonly queried fields. MongoDB’s text analyzer is also less powerful than that of Elasticsearch.
MongoDB’s cluster contains three types of servers: shard, config, and router. The servers will accept more requests when you scale the router, but most workloads are often directed to the shard servers. Like Elasticsearch, MongoDB documents are routed by default to their specific shards. When you execute a query request, the config server communicates to the router and shards the query. The router server then distributes the query and retrieves the results.
MongoDB’s Aggregation Pipeline is fast and very powerful. It operates on returned data in a stage-wise fashion, where each step can filter, transform and combine documents or unwind previously-aggregated groups. Since the operations are done step-by-step, the final documents are filtered, which minimizes the memory cost. Like Elasticsearch, MongoDB lacks the intra-document field comparison; hence it can’t use distributed computing.
Unlike MongoDB, Elasticsearch, and even the traditional SQL databases, Amazon Redshift doesn’t support data indexing. Instead, it reduces the query time by consistently sorting data on the disk. That is, each table has its sort key that determines how rows have been stored once the data is loaded.
Amazon Redshift’s cluster has one leader node and multiple compute nodes. The leader node computes and distributes queries before sampling intermediate results. Compared to MongoDB’s router servers, this leader node is very consistent and cannot be scaled horizontally. This creates some limitations but allows efficient caching for specific execution plans.
Since Amazon Redshift is a relational database that supports SQL, it’s quite popular among traditional database engineers. It also solves the slow aggregations common with MongoDB when analyzing mobile traffic. However, it doesn’t have the schema flexibility that Elasticsearch and MongoDB have. It’s also optimized for reading operations and hence suffers from performance issues during updates.
From the three alternative storage options above, choosing the ultimate best isn’t as obvious as it may seem. Depending on your unique data storage needs, one storage option is always better than the other. So instead of narrowing down to the ultimate best, you want to compare the different features and capabilities against your needs and then choose those that work best for you.
Hello friends, I hope you all are doing well. Welcome to the 9th tutorial of our Raspberry Pi programming course. In the last chapter, we generated a PWM signal from our Raspberry Pi to control the brightness of an LED. We also studied different functions used in Python to perform PWM. In this chapter, we'll get a bit advanced with PWM and use it to control the speed and direction of a DC motor with the help of a motor driver IC.
To control the speed & direction of the DC Motor, we will:
We will use the following components to control the DC motor speed:
Pulse Width Modulation(we studied in the previous tutorial) will be used to regulate the speed of a DC motor. A quick recall, a PWM signal is used to generate a variable voltage at the output depending on the duty cycle. The duty cycle refers to the length of time during which the signal is kept at a high level and determines how much power is given to the signal.
As a result of the PWM signal, the speed of a DC motor can be controlled in a non-resistive or non-dissipative manner.
The L293D pinout is shown in the following diagram.
The microcontrollers provide either 5V or 3.3V at their GPIO Pins, in the case of RPi4, it's 3.3V. The current rating of these GPIO pins is normally 10-50mA, which is quite low and it's justifiable as their sole purpose is to send the signal.
Now if we talk about DC Motors, they normally operate at 5V-48V and have a current rating from 100mA to 10A. So, we can't connect a DC motor directly to a microcontroller's pin. We need a motor driver to amplify the voltage and current.Moreover, DC motors also produce back EMF, which may burn the GPIO, so in order to protect the board, we should have a motor driver in between.
We have designed the circuit in the above section and now it's time to get our hands on Python code. We will be using the Thonny IDE in Raspberry Pi 4.
In this code, we will write a simple code to drive the motor forward for 5 seconds, then backward for another 5 seconds at a 50% duty cycle. You can alter any of these values as you see fit.
I will explain the code line by line for better understanding:
Motors from the DC series are commonly employed in electric locomotives and fast transit systems, as well as trolley vehicles. Because of their high starting torque, they're also found in cranes, hoists, and conveyors.
The use of DC shunt motors in rolling mills is due to their ability to accurately manage speed. They're used for driving lathes at a fixed speed, used in reciprocating and centrifugal pump drives, and also used in blowers, machines, and reciprocating pumps.
They can be found in a wide variety of machinery, including elevators, conveyors, heavy planers, shears, and punches, as well as intermittently high torque loads and air compressors.
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 DC motor's speed and direction. In the next tutorial, we will have a look at how to Control a Stepper Motor with Raspberry Pi 4 using Python. Till then, take care. Have fun !!!
Hello friends, I hope you all are doing great. It's the 8th tutorial in our Raspberry Pi programming course. In the previous lectures, we interfaced LCD 16x2 and Keypad 4x4 with Raspberry Pi 4. In this chapter, we are not going to interface any external module with Pi, instead, we'll create a PWM signal in the raspberry pi using Python. Let's get started:
We are going to use the below components in today's PWM project:
Before going forward, let's first understand what is PWM:
Let's understand the working of PWM with an LED example. We can change the brightness of an LED using PWM. If we provide +5V, the LED will have full brightness, but if we provide +2.5V to the LED, its brightness will fade. We achieve +2.5V from a +5V signal by turning it ON and OFF continually. So, in a signal of 1 sec, if we turn it ON and OFF 100 times, the overall power of the signal will be halved as it's in an OFF state for 50% of the duration. This process is called Pulse Width Modulation(PWM).
The percentage for which the signal remains in the ON state during one cycle is called the duty cycle.
To get an ideal square wave, you need a duty cycle of 50%. The signal is always on(full-scale) with a 100% duty cycle, while the signal is always off(Ground) with a 0% duty cycle.
The inverse of the period is the frequency of the signal, which is the number of times a periodic change is accomplished per unit of time. Speed is determined by how quickly a signal goes from high to low i.e. how quickly a PWM completes a cycle. Constant voltage output is achieved by continually turning the digital signal on and off at a high frequency.
The 'PWM resolution' refers to the degree of control over the duty cycle. The more 'brightness' levels we can display, the greater our PWM resolution needs to be. Pprecise microcontroller timing is required because the duty cycle is normally around 50Hz. The more powerful the microcontroller, the shorter the time intervals it can keep track of. The microcontroller must not only time the 'interrupt,' which generates the pulse but also run the code that controls the LED output, which must be completed before the next interrupt is called, which is another limiting issue. It's also likely that you'll want your microcontroller to accomplish activities other than controlling the brightness of the LEDs, so you'll need some spare execution time between interrupts.
The fundamental benefit of greater PWM resolutions for LED PWM control is that it reduces the difference between 'off' and the LED's lowest achievable brightness. Suppose we have a duty cycle of 20,000 microseconds and a resolution of 10,000 microseconds. In that case, the difference in brightness between "off" and the lowest possible brightness will be 50 percent of the total brightness. The difference would be 10% at a resolution of 2,000 microseconds. The "PWM resolution" determines the number of brightness levels that we can support between 0% and 100% when it comes to brightness levels. (100 percent). Again, the better the resolution, the more precise the timing, and the more computing power is needed to process the information.
The above diagram shows a PWM resolution of 10%.
Depending on the nature of your application, the resolution and overall duty cycle requirements may be different. There is no need for precision control for simple displays; nevertheless, the ability to manage the brightness level may be crucial (think of the issue of mixing colors using an RGB LED, for example). More control and accuracy necessitate more microcontroller resources; thus, the trade-off is straightforward.
Even though hardware PWM is the preferred approach for generating PWM from the Raspberry Pi, we will use software PWM in this article.
Pins 2 and 6 of the Pi board can be used to supply the circuit with Vcc and ground.
The thorny Python IDE on raspberry pi will be used here to write our Python script. If you haven't already done so, please go back to Chapter 4 and read about how to get started with this IDE before reading on.
To keep things simple, we'll create a file called PMW.py and save it to our desktop.
We're using a 50 Hz software PWM signal to generate a customized sine wave with RPi. It has a 20-millisecond window at this frequency. During the application, the frequency does not fluctuate.
Increasing the software PWM duty cycle from 0 to 100 is required to produce a rectified sine wave. The PWM signal is applied to the LED in five-pulse trains every 0.1 seconds, with each train lasting 0.1 seconds.
As a result, the duty cycle is lowered from 100 to 1 in steps of minus one. Five PWM pulse trains, each lasting 0.1 seconds, are applied to each increment. Iteration continues indefinitely until a keyboard interrupt is received, at which point the user program terminates.
Import RPi.GPIO then time libraries. Then a simple script is run to begin. The GPIO.setwarnings() method is used to disable the warnings.
To set the RPi's PINs to the number of board, use the GPIO.setmode() function to set the pin numbering. The GPIO.setup() method configures pin 40 of the board as an output. However, the GPIO.PWM() technique is used to instantiate board pin 40 as a software PWM.
It is possible to write a user-defined setup() function to ensure that the software PWM has no duty cycle when it is first started. Only one instance of this function is ever called.
The duty cycle of the PWM signal is altered from 0 to 100 and then back to 0 in a user-defined loop() function. This occurs in increments of one, with a 0.1-second gap between each. For an endless number of times, the LED lights up and fades back down.
The PWM signal is turned off when a keyboard interrupt is received by calling the endprogram() method. The GPIO of the Raspberry Pi is then wiped clean.
Setup() and loop() are the two methods in a try-exception statement, and they are each called once.
A PWM instance can be created with the help of this function. This is a two-step process:
The syntax for this method is:
The number of the channel must be given in accordance with the user-Board program or BCM numbering.
This technique can be used with a PWM software instance. PWM duty cycle is all you need to know about this.
PWM instances can be accessed by calling this method from a Python program. A software PWM signal with the specified duty cycle is started at the supplied channel.
This technique can be used with a PWM software instance. There's only one thing needed: a new Hertz value for the PWM signal's frequency.
The frequency of the PWM output is changed when this method is used on a PWM object in Python.
The syntax is as follows:
An instance of PWM software can use this technique. One reason is all that is required: the launch of a new cycle of service.
The duty cycle ranges from 0.0 to 100.0. The duty cycle of the PWM signal is changed when this method is called on a PWM instance in Python.
Here is the syntax of the method:
This technique can be used with a software PWM instance. It doesn't need a response. An instance's PWM signal is paused when this method is called on it.
The syntax for this method is:
Congratulations! You have made it to the end of this tutorial. We have seen how PWM is generated in the raspberry pi. We have also seen how to set up our raspberry pi pins with LEDs to be controlled and wrote a python program that controls the output of these pins. The following tutorial will learn how to control a DC motor with Raspberry Pi 4 using Python.