Interface DS18B20 with Raspberry Pi 4

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

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

Project Description

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

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

Components Required

Here's the list of components:

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

DS18B20 Sensor: A Quick Overview

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

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

Types of Temperature Sensors

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

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

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

Circuit Diagram of DS18B20 with Raspberry Pi 4

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

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

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

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

Installation of Python Libraries

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

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

Adafruit LCD library

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

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

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

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

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

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

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

Enabling 1-Wire Protocol in Raspberry Pi

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

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

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

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

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

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

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

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

Using Python on a Raspberry Pi

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

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

DS18B20 Python Code Explanation

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

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

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

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

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

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

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

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

Output

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

DS18B20 Applications

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

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

Conclusion

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

Interface DHT11 Sensor with Raspberry Pi 4

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

So, let's get started:

Components

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

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

What is a DHT11 sensor?

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

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

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

DHT11 Pinout

DHT11 has 4 pins in total, which are:

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

  • Here's the Pinout of the DHT11 Module:

DHT11 Working Principle

The DHT11 timing diagram is shown in the below figure:

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

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

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

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

Types of Temperature and Humidity Sensors

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

Grove – AHT20

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

DHT11

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

DHT22

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

BMP280

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

BME280

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

DS18B20

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

AF5485

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

AM2311A

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

Circuit Diagram of DHT11 with Raspberry Pi 4

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

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

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

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

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

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

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

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

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

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

Python Code for DHT11 Sensor with Raspberry Pi 4

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

DHT11 Adafruit Library

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

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

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

Now let's design our Python code:

Python Code to read DHT11 data

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

Let's understand the code line by line:

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

Reading DHT11 Output with RPi4

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

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

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

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

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

DHT11 Applications

Networked IoT Environment Monitoring

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

Weather Station

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

Climate Control

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

Conclusion

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

Interface Ultrasonic Sensor with Raspberry Pi 4 using Python

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

Components:

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

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

What are Ultrasonic Sensors?

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

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

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

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

Ultrasonic Sensor Pinout

The Ultrasonic Sensor has four connections:

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

Ultrasonic Sensor Working Principle

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

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

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

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

How is the distance calculated?

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

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

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

Interface Ultrasonic Sensor with Raspberry Pi 4

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

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

Voltage Divider at Echo Pin

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

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

Circuit Diagram

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

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

Now let's design it with real hardware:

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

  • Now connecting Jumper wires to Raspberry Pi 4:

  • Connected Ultrasonic Sensor & Raspberry Pi 4 via Breadboard:

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

  • The second resistor used is of 2k ohm:

  • Here's our Raspberry Pi 4:

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

Python Code for Ultrasonic Sensor

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

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

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

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

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

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

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

  • Assigning GPIO Pins to Trig and Echo pins:

>

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

Python Code for Distance Calculation

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

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

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

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

  • Here are the results:

Ultrasonic Sensors: Drawbacks

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

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

Conclusion

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

5 Great Tools for Designers

In the past, graphic designers had limited choice of graphic design tools. There were only 3-5 great design tools for professional work. This has all changed with free and open-source platforms making it easy to design what you want, wherever you want it. Also, many of these tools are cross-platform too, meaning you can whip up some quick designs on your Android or iOS device. Because the sheer number of available tools makes it harder to pick the best one, we are going to look at 5 great ones that you should be using right now.

Adobe Illustrator

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

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.

Picsart Sticker Maker

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

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

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.

Control Servo Motor with Raspberry Pi 4 using Python

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

Components Required:

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

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

What is a servo motor?

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

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

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

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

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

Types of Servo Motors

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

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

DC Servo Motors

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

AC Servo Motors

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

Positional Rotation Servo Motor

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

Linear Servo

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

Servo Motor Working Principle

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

  • DC Motor.
  • Feedback.
  • Control Electronics.

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

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

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

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

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

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

How to Control a Servo Motor?

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

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

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

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

Circuit Diagram of Raspberry Pi Servo Motor Interface:

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

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

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

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

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

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

Python Code for Servo Control with Raspberry Pi 4

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

Importing libraries

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

GPIO board mode

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

Configuring PWM GPIO

  • Now, set Pin11 to be the output:

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

Start PWM

Rotate the Servo shaft

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

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

Let's turn the shaft back

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

Clean up

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

Final Servo Output

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

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

Working on the setup

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

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

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

Applications of servo motors

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

Cameras, telescopes, and antennas

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

Elevator

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

Robotics

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

Industrial production

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

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

Conclusion

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

Control Stepper Motor with Raspberry Pi 4 using Python

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

Here's the video demonstration of this project:

Let's get started:

Components Required

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

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

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

What is Stepper Motor?

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

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

Stepper Motor Working Principle

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

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

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

L293D Motor Driver IC

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

  • L293D Pinout is shown in the below figure:

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

Stepper Motor with RPi4 Circuit Diagram

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

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

.

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

 

Python Code for Stepper Control with RPi4

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

  • Set the mode of GPIO pins to the board:

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

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

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

  • Take user input for the number of rotations:

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

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

Conclusion

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


How to Protect Your Servers from Natural Disasters?

According to NASA, areas in the north of the U.S will experience higher rainfall, increasingly extreme hurricanes, and sea levels will rise by about eight feet by 2100. With climate change, extreme weather events have become much more frequent, and their magnitude has increased globally. This scenario presents a significant risk to server rooms and data centers by increasing the likelihood of water and fire damage.

Can Your Data Center and Business Recover After a Natural Disaster?

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.

Tips To Protect Your Servers From Natural Disasters

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.

1. Fire

Whether you wish to set up a new server room or bolster an existing one, here are several tips to fireproof the area and prevent data loss.

Include fire-resistant materials during construction

Three levels of fire protection exist.

  • Building level. Your data center should install systems that will safeguard the entire structure. These include extinguishers, fire sprinklers, and secondary protection like firewalls and floor assemblies, which ought to slow down the fire and prevent it from spreading.
  • Room level. If your data center is in the U.S., you are probably aware of National Fire Protection Association (NFPA) standards 75 and 76 which help safeguard tech equipment and telecommunication facilities.
  • Rack level. This protection level focuses on the server room and equipment inside.

Install suppression systems

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.

Schedule regular inspections

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.

2. Flooding

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:

  • Air conditioning units leakage
  • Condensation resulting from increased humidity
  • Groundwater leakage

Before taking action, you’ll need to perform a risk assessment to determine areas that require water leakage detection.

Install leakage monitoring systems

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.

Set up cable runs

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.

3. Earthquakes

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

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

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.

4. Hurricanes

Preventing power outages in your server room is perhaps the primary focus when preparing for hurricanes.

Here’s what you can do.

  • Install uninterrupted power supply(UPS). As a preventive measure, raise the UPS to prevent contact with water (limits the risk of sparking).
  • Have a dedicated support team available 24/7 to ensure you receive alerts in real-time.
  • Have standby generators. UPS is only ideal for a short-term outage. Generators might come in handy if the blackout is a longer-term occurrence. Ensure you enclose the structure with steel to offer added protection from the weather elements.
  • Implement the 3-2-1 rule. The 3-2-1 is a backup strategy that entails having three data copies and transferring two to 2 storage media, e.g., cloud and disk, to a remote location. Ensure to schedule test backup regularly.

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.

What Data Engineers Should Know About Non-Traditional Data Storage?

The rapid adoption of digital transformation across industries has seen several organizations implement AI and Big Data capabilities to enhance their competitive advantage. Businesses, large and small, now leverage data to guide business operations and make critical company decisions.

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.

Non-Traditional Data Storage Options

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.

  • Search engines – compared to the text matches in SQL databases, search engines have superior text queries. The higher query capabilities and the enhanced performance makes them an attractive option, especially when accessing a huge set of stored data. An example of search engine storage is Elasticsearch, developed in Java.
  • Columnar Stores – this type stores data by columns instead of rows, making it suitable for analytical query processing. Columnar stores are often considered the future of business intelligence. An example of columnar storage is Amazon Redshift, which is based on PostgreSQL.
  • Document stores – unlike traditional databases, document stores provide better data schema capabilities. They store data as individual document objects, represented as JSON, so they don’t require schema predefining. An example of document storage is MongoDB. To efficiently handle data using MongoDB, you’ll need to learn a language like Java or C++ and C#.

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.

Elasticsearch Storage

Indexing Capability

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.

Sharding Capability

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.

Aggregating Capability

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

Indexing Capability 

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.

Sharding Capability

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.

Aggregating Capability

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.

Amazon Redshift

Indexing Capability

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.

Sharding Capability

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.

Aggregating Capability

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.

Choosing an Alternative Storage Option

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.

Control DC Motor with Raspberry Pi 4 using Python

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:

  • Design a Circuit Diagram.
  • Write Python code.

Components Required

We will use the following components to control the DC motor speed:

  • Raspberry Pi 4.
  • DC Motor.
  • Motor driver IC(L293D).
  • Breadboard.
  • Jumper wires.

Controlling DC Motor speed with Raspberry Pi 4

  • In order to control the DC motor with any microcontroller, we need to use the motor drivers i.e. L298, ULN2003 etc.
  • In our project, DC motors are controlled by the L293D motor driver, an intermediate integrated circuit.
  • Raspberry Pi 4 will send the signal to the motor driver, which in turn will control the speed or direction of the DC motor.
  • To regulate the DC motor's speed, we will write Python programs in Raspberry Pi, to control the GPIO pins and will send signals to the motor driver IC.

Control DC motor using PWM

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.


Motor Driver L293D

  • We will use the L293D Motor driver, it will get the signals from Raspberry Pi through its GPIO pins and will control the motor.
  • The Raspberry Pi's low-current signal is amplified by this motor driver into a high-current signal used to drive a motor.

L293D Pinout

The L293D pinout is shown in the following diagram.

  • As you can see in the L293D pinout, it has 4 input/output channels.
  • In order to control the speed of 1 DC motor, we need to use 2 channels of L293D.
  • So, a single L293D IC can control 2 DC motors at a time.
  • It also has 2 Enable Pins and are used as master control pins for these channels.
  • Enable Pin 1 is used to control the first two channels(left side), while Enable Pin 9 is used to control the last two channels(right side).
  • Vss(Pin16) is the reference voltage pin, it should be provided with 3.3V or 5V. It's the reference to the signals provided at Input pins. In our case, we are using RPi4 and its GPIO pins provide 3.3V, so we will give 3.3V at Vss pin.
  • Vs(Pin8) is the source voltage pin, normally a 9V or 12V power is applied at this pin. The voltage at Vs pin is provided to all the output pins by the L293D.

Why do we need a Motor Driver L293D?

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.

L293D Working

  • The PWM signal generated by the Raspberry Pi will be provided to Input1 and Input2.
  • If Input1 is at a High state, while Input2 is at a LOW state, the motor will rotate in one direction, let's say clockwise.
  • If we changed the states i.e. Input1 at a LOW state, while Input2 at a HIGH state, the motor will change its direction and will rotate in the anti-clockwise direction.
  • The motor won't run if you simultaneously supply highs or lows to both inputs.

Controlling DC Motor with Raspberry Pi4

  • As shown in the above figure, we will use three GPIO pins of Raspberry Pi 4, connected to Enable1, Input1 and Input2 of the L293D motor driver.
  • Vss Pin of L293D is provided with 3.3V from RPi4.
  • We will also connect the GND of L293D with that of RPI4(Pin6).
  • Vss of L293D is provided with +9V from the battery and that will be provided at the output and will control the motor's speed.

Python Code for DC Motor Speed Control

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:

  • To use the GPIO pins, you must first import the GPIO module using the import command.

  • We also need to include a sleep instruction, required while making changes to the PWM duty cycle or the direction of the motors.

  • To access the GPIO pins, you'll first need to put them into board mode. To do so, run this command.

  • As we need to send PWM signals to the motor driver, so we need to make these pins OUTPUT, using the below command:

  • Let's create a PWM object by using the PWM GPIO pin, using the below command:

  • LEt's start the PWM object with a 0% duty cycle.

  • Initiating a clockwise movement of the motor by making the first pin HIGH and the second one LOW.

  • Setting the 25% duty cycle to the PWM object:

  • Setting the Enable Pin HIGH:

  • Delay of 5 seconds:

  • Enable Pin is set to LOW to stop the motor.

  • Reverse the motor's polarity:

  • By setting the duty cycle to 50%, the motor will now run at 50% speed in the opposite direction.

  • The enable pin should be set to HIGH.

  • Keep the code running for another five seconds:

  • Reset the Enable pin to turn off the motor.

  • After that, clean up and reset the GPIO channels after disabling the PWM object. It's always recommended to clean up the GPIO pins so that the next program could use them without getting an error, saying the pin you selected is not available to use.

  • If you followed all of the steps correctly, your engine will run for five seconds in the forward direction and then for five seconds in the reverse direction.

  • A variable whose value changes with each iteration of the loop is called an iterative variable. You may adjust the duty cycle such that your motor's speed grows in steps as you observe it.

  • Now as we lowered the duty cycle to 25%, the DC motor speed gets lowered as well.

  • Here's the complete code and the hardware images:

Application of DC motor control systems

DC Series Motor:

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.

DC Shunt motor:

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.

Synchronous Motors:

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.

Conclusion

Congratulations! You have made it to the end of this tutorial. We have seen how PWM is used with a motor driver IC to control a 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 !!!

Create PWM Signal in Raspberry Pi 4 using Python

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:

Components Required

We are going to use the below components in today's PWM project:

  1. Raspberry Pi 4.
  2. LED.
  3. A resistor of 330 ohms.
  4. Breadboard.
  5. Jumper wires.

Before going forward, let's first understand what is PWM:

What is PWM?

  • In PWM(Pulse Width Modulation), we simply turn on and off our power supply at regular intervals and thus reduce the average power of the signal.
  • We have shared a detailed tutorial on Introduction to PWM(Pulse Width Modulation), you should read it once to understand 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).

What is a "duty cycle"?

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.

PWM Signal's Frequency

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.

PWM Resolution

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.

Applications of PWM

  1. Using PWM, you may adjust the screen's brightness.
  2. Use a variety of loudness levels for the buzzer.
  3. Control the motor's speed i.e. DC, Servo, Stepper etc.
  4. Provide a physical outlet for analog signals.
  5. Create an audio output.
  6. Communication: encoding of the message.

Raspberry Pi PWM Signal

  • Raspberry Pi 4 has two PWM channels, PWM0 and PWM1.
  • Four PWM pins are available on the Raspberry Pi, GPIO12 and GPIO18 share the PWM0 channel, whereas GPIO13 and GPIO19 share the PWM1 channel.
  • The following are the pinouts for the PWM channels on the 40-pin header:

  • The Raspberry Pi 40-pin Header's PWM pins are illustrated in the following figure.

  • On a Raspberry Pi, all of the PWM pins are used by the audio subsystem. As a result, we can choose either PWM or Audio output.
  • Hardware PWM signals can only be generated by importing the Pigpio library. The RPi.GPIO library, on the other hand, can be used to generate PWM signals.

Software PWM in Raspberry Pi

  • There are two ways to generate PWM signals with the Raspberry Pi i.e. hardware PWM and software PWM.
  • It is possible to use all 26 GPIO pins on the RPi to generate PWM frequencies of up to a few thousand Hertz using software PWM. The software PWM signals' duty cycle can be adjusted anywhere from 0% to 100%.
  • Software PWM is more adaptable than hardware PWM. However, software-based PWM has the major disadvantage of being less accurate than a hardware-based PWM channel. Because software PWM generation consumes CPU resources, your Raspberry PI's processing capacity will be limited.

Raspberry Pi PWM Circuit Diagram

Even though hardware PWM is the preferred approach for generating PWM from the Raspberry Pi, we will use software PWM in this article.

  • Connect the anode of the LED with GPIO21. After that, connect the LED's cathode to a 330 Ohm series resistor and ground the resistor's other end.
  • Pins 2 and 6 of the Pi board can be used to supply the circuit with Vcc and ground.

Python Code for PWM Signal Generation

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.

Putting the project into action

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.

Code

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.

Code Syntax

The GPIO.PWM() method

A PWM instance can be created with the help of this function. This is a two-step process:

  • PWM signal must be generated on a specific channel number
  • The frequency in Hertz of the PWM signal. The method must be assigned to a variable before an instance can be generated.

The syntax for this method is:

The number of the channel must be given in accordance with the user-Board program or BCM numbering.

The start() method

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.

The syntax is as follows:

The ChangeFrequency() method

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:

The ChangeDutyCycle() method

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:

The stop() 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:

Output

Conclusion

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.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir