Interface DS18B20 with Raspberry Pi 4

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

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

Project Description

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

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

Components Required

Here's the list of components:

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

DS18B20 Sensor: A Quick Overview

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

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

Types of Temperature Sensors

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

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

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

Circuit Diagram of DS18B20 with Raspberry Pi 4

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

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

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

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

Installation of Python Libraries

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

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

Adafruit LCD library

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

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

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

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

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

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

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

Enabling 1-Wire Protocol in Raspberry Pi

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

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

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

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

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

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

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

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

Using Python on a Raspberry Pi

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

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

DS18B20 Python Code Explanation

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

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

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

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

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

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

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

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

Output

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

DS18B20 Applications

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

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

Conclusion

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

Interface DHT11 Sensor with Raspberry Pi 4

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

So, let's get started:

Components

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

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

What is a DHT11 sensor?

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

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

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

DHT11 Pinout

DHT11 has 4 pins in total, which are:

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

  • Here's the Pinout of the DHT11 Module:

DHT11 Working Principle

The DHT11 timing diagram is shown in the below figure:

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

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

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

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

Types of Temperature and Humidity Sensors

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

Grove – AHT20

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

DHT11

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

DHT22

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

BMP280

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

BME280

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

DS18B20

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

AF5485

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

AM2311A

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

Circuit Diagram of DHT11 with Raspberry Pi 4

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

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

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

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

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

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

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

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

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

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

Python Code for DHT11 Sensor with Raspberry Pi 4

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

DHT11 Adafruit Library

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

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

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

Now let's design our Python code:

Python Code to read DHT11 data

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

Let's understand the code line by line:

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

Reading DHT11 Output with RPi4

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

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

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

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

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

DHT11 Applications

Networked IoT Environment Monitoring

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

Weather Station

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

Climate Control

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

Conclusion

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

Interface Ultrasonic Sensor with Raspberry Pi 4 using Python

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

Components:

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

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

What are Ultrasonic Sensors?

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

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

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

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

Ultrasonic Sensor Pinout

The Ultrasonic Sensor has four connections:

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

Ultrasonic Sensor Working Principle

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

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

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

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

How is the distance calculated?

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

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

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

Interface Ultrasonic Sensor with Raspberry Pi 4

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

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

Voltage Divider at Echo Pin

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

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

Circuit Diagram

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

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

Now let's design it with real hardware:

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

  • Now connecting Jumper wires to Raspberry Pi 4:

  • Connected Ultrasonic Sensor & Raspberry Pi 4 via Breadboard:

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

  • The second resistor used is of 2k ohm:

  • Here's our Raspberry Pi 4:

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

Python Code for Ultrasonic Sensor

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

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

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

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

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

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

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

  • Assigning GPIO Pins to Trig and Echo pins:

>

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

Python Code for Distance Calculation

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

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

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

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

  • Here are the results:

Ultrasonic Sensors: Drawbacks

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

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

Conclusion

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

Control Servo Motor with Raspberry Pi 4 using Python

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

Components Required:

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

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

What is a servo motor?

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

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

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

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

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

Types of Servo Motors

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

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

DC Servo Motors

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

AC Servo Motors

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

Positional Rotation Servo Motor

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

Linear Servo

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

Servo Motor Working Principle

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

  • DC Motor.
  • Feedback.
  • Control Electronics.

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

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

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

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

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

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

How to Control a Servo Motor?

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

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

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

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

Circuit Diagram of Raspberry Pi Servo Motor Interface:

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

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

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

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

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

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

Python Code for Servo Control with Raspberry Pi 4

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

Importing libraries

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

GPIO board mode

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

Configuring PWM GPIO

  • Now, set Pin11 to be the output:

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

Start PWM

Rotate the Servo shaft

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

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

Let's turn the shaft back

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

Clean up

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

Final Servo Output

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

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

Working on the setup

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

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

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

Applications of servo motors

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

Cameras, telescopes, and antennas

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

Elevator

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

Robotics

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

Industrial production

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

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

Conclusion

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

Control Stepper Motor with Raspberry Pi 4 using Python

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

Here's the video demonstration of this project:

Let's get started:

Components Required

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

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

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

What is Stepper Motor?

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

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

Stepper Motor Working Principle

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

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

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

L293D Motor Driver IC

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

  • L293D Pinout is shown in the below figure:

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

Stepper Motor with RPi4 Circuit Diagram

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

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

.

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

 

Python Code for Stepper Control with RPi4

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

  • Set the mode of GPIO pins to the board:

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

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

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

  • Take user input for the number of rotations:

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

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

Conclusion

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


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.

Cloud Computing Services

Hi Friends! Hope you’re well today. I welcome you on board. In this post today, I’ll walk you through Cloud Computing Services.

The requirement to process and store data varies from business to business. Some organizations can handle data in on-site data centers. They have a team of experts who handle IT infrastructure and install, maintain and upgrade hardware based on the availability of data. This approach is expensive, no doubt. Some companies, however, don’t accept this model. They prefer cloud computing which is the availability of on-demand IT infrastructure over the internet. This model sets them free from handling and managing on-site data centers, instead, everything is managed and controlled by the cloud service providers. End users only pay for the computing services they use. This IT solution is not only cost-effective but also reliable and secure as your data is managed and stored over the cloud with globally managed data center.

I suggest you read this entire post as I’ll cover cloud computing services and how they can improve the efficiency of any business.

Scroll on.

Cloud Computing Services

Cloud services are the availability of software, platform, and infrastructure by the cloud service providers over the internet. Cloud computing services come with the following features:

Cloud computing services are maintained and hosted by cloud service providers. The end users don’t have to purchase or install software or hardware on-site since the service providers host, maintain and purchase the necessary IT infrastructure on their premises.

Service providers offer these services with the pay-as-you-go model which means the end-users only pay for the services and computing resources they use. This is the most economical approach for businesses since they don’t have to install and maintain the entire hardware and software system instead they only pay for the computing resources they use.

Cloud computing offers unlimited storage capacity. The virtual office you create with cloud computing gives you accessibility to almost limitless data to store and manage. This is very difficult to incorporate into traditional data centers since the more storage capacity and bandwidth you need the more hardware and software setup you have to install.

Cloud computing services are mainly divided into three types:

  • SaaS (Software as a Service)
  • IaaS (Infrastructure as a Service)
  • PaaS (Platform as a Service)

No matter the service model businesses opt for, the cloud service providers host and manage the entire IT infrastructure in their onsite facility. The end users only get only IT resources as a service instead of businesses using them directly.

All three services are different in terms of resource pooling and storage though, they can form a comprehensive model of cloud computing by interacting with each other.

In the following, we’ll discuss these services one by one.

1: SaaS (Software as a Service)

In this service model, the service providers host the software on their own IT system and offer it to organizations based on the subscription fees. This way software is not installed in an individual’s system, instead, users can access the software installed on the cloud data centers over the internet with log-in usernames and passwords.

The services in this SaaS model include calendaring, email, and collaboration. Other business applications that enterprises can get on rent from the service providers include document management, ERP (enterprise resource planning), and CRM (customer relationship management).

Know that cloud software or SaaS is a full web application that requires huge capital investment since cloud service providers offer the full-fledge online app dedicated to the customers of an enterprise. The organizations get these services with a pay-as-you-go plan and more often this type of application or cloud software can be accessed directly from the web browsers without any installation or downloads. The reason, it is commonly called on-demand software, web-based software, or hosted software.

Advantages of SaaS

 

Economical: It works on the pay-as-you-go model which means you only pay for the computing resources you use.

Reduced time: Most SaaS apps can be accessed directly from the web browser. No downloads or installations are required. This means less time is required to run this app which you would otherwise spend on the installation and configuration of apps on an individual system.

Mobility: You can access this cloud software from anywhere in the world.

Automatic Updates: You don’t purchase the entire software. Only the services from that software on rent. This sets you free from manual updates, instead service providers will automatically update the software to avoid any potential threats.

Disadvantages of SaaS

  • SaaS comes with a limited range of solutions.
  • To access SaaS service internet connectivity is necessary.
  • End users have less control over the data and service providers act as the main authority.

2: IaaS (Infrastructure as a Service)

IaaS service is the availability of on-demand IT infrastructure to businesses over the internet. This infrastructure includes operating systems, networks, storage, virtual machines, and servers. The cloud service provider offers this service to the organizations on a pay-as-you-go model.

The IaaS is an ideal solution for small and medium-sized businesses looking for an economical approach for their business growth. This gives them better control over the computing services and removes the need for intricate hardware installation as companies can access this model over the internet.

3: PaaS (Platform as a Service)

PaaS is the availability of on-demand IT platforms to businesses over the internet. With PaaS, cloud service providers create an online environment by incorporating multiple technologies including orchestration, containerization, security, routing, management, automation, and application programming interfaces.

Using this service, developers can develop, test, manage and deploy software applications without the need for the underlying infrastructure of the network, storage, servers, and databases required for the development.

Common Cloud Service Examples

Many cloud computing services we already use regularly. Common PaaS services include OpenShift, Apache Stratos, Google App Engine. Similarly Cisco WebEx, DropBox, SalesForce fall under the SaaS service model. And Microsoft Azure, Amazon Web Services, and Cisco Metapod belong to the IaaS service model. End users don’t need hardware and software installation on-premises instead they can access these services with a computer and a strong internet connection.

Know that the cloud computing service models are different from the cloud computing types. The four cloud computing types include Public Cloud, Private Cloud, Hybrid Cloud, and Community Cloud. While cloud computing services, on the other hand, include IaaS, PaaS, and SaaS service models. In the public cloud, services are delivered to the general public. For instance, several organizations can use the public cloud. While in a private cloud, services are delivered to a single organization.

That’s all for today. Hope you’ve enjoyed reading this article. Feel free to reach out in the section below about any questions regarding cloud computing. I’m willing to help in the best way possible. Thank you for reading this post.

Installing Thonny IDE for Raspberry Pi Pico Programming

Hello readers, I hope you all are doing great. In our previous tutorial, we discussed the installation procedure of Visual Studio Code for programming Raspberry Pi Pico.

We have already mentioned in our previous tutorials that RP2040 or Raspberry Pi Pico supports multiple programming languages like C/C++, Circuit python, MicroPython cross-platform development environments. Raspberry Pi Pico module consists of a built-in UF2 bootloader enabling programs to be loaded by drag and drop and floating-point routines are baked into the chip to achieve ultra-fast performance.

There are multiple development environments to program a Raspberry Pi Pico board like Visual Studio Code, Thonny Python IDE, Arduino IDE etc.

So, in this tutorial, we will learn how to install Thonny Python IDE to program the Raspberry Pi Pico board using Micropython programming language.

Downloading Thonny Python IDE for Windows

Thonny Python IDE (Integrated development environment) is a development tool designed for beginners. The major feature of using Thonny is that it is easy to operate and this development environment also provides a faithful representation of function calls. The Thonny IDE is compatible with Linux, MacOS and Windows OS.

  • To download the Thonny Python IDE follow the given link: https://thonny.org/
  • This is the official website of Thonny where we have different download versions for different OS.
  • Click on ‘Windows’ to download the installation setup for Windows OS (as shown below).

Fig. 1 Download thonny

Installing Thonny Python IDE

  • Once the installation setup is downloaded successfully for Windows next step is the installation of the IDE.
  • To install the Thonny Python IDE in your system, double-click on the downloaded file.
  • Select “Install for all users”.

Fig. 2 Choose Installation Mode

  • Follow the basic installation procedure.
  • Accept the license agreement and press next.

Fig. 3 Accept the agreement

  • Select the installation/destination location.
  • You can keep the default location or you can also change the location by clicking on

Fig. 4 installation location

  • Now, select the “Start menu folder” and press ‘Next’.
  • If you want to create a desktop icon for Thonny then check the respective icon and press Next (as shown below).

Fig. 5 Desktop icon

  • Finally, press Install to install the setup.

Configuring the Raspberry Pi Pico for programming with MicroPython

MicroPython is a programming language that runs directly on embedded hardware, for example, ESP and Raspberry Pi Pico. It is a full implementation of the Python (3) programming language.

Programming Raspberry Pi Pico is a very easy process. Users can program the board by connecting it via USB port, and then just drag and drop the file into Raspberry Pi Pico.

Download the MicroPython UF2 file

    • To download the micropython UF2 file for raspberry Pi Pico programming follow the given link :

https://www.raspberrypi.com/documentation/microcontrollers/micropython.html

  • Scroll down the page for MicroPython UF2 file and download the file to your system, as shown below:

Fig. 6 Download Micropython UF2 file

Connecting Raspberry Pi Pico board with laptop/computer

  • Press and hold the BOOTSEL button from the Raspberry Pi Pico development board.
  • Connect or plug the Raspberry Pi Pico board to your system/computer via USB cable and release the BOOTSEL button once the Pico is connected to the computer.
  • Now you should see a new volume in your system i.e., RPI-RP2.
  • Drag and drop the downloaded MicroPython UF2 file into RPI-RP2 This UF2 file will reboot your system.
 

Select Interpreter and Install MicroPython Firmware

  • Open the Thonny IDE.
  • Go to Run >> Select Interpreter.

Fig. 7 Select Interpreter

  • Select the necessary/required interpreter which is MicroPython (Raspberry Pi Pico) as shown below:

Fig. 8 MicroPython for Raspberry Pi Pico

  • Press “Install or update firmware”.
  • Again press Install.
  • Make sure that your system is connected to internet.

How to check whether Micropython firmware is installed successfully or not and whether it is working or not?

  • Go to View >>
  • In the file list (on left side of the screen) a complete list of all the local files and document saved on your system will be displayed and along with that your should see Raspberry Pi Pico file in the same list (this is the file saved in Pico).
  • Again go to View >> Shell.
  • In shell type some command like printing a message as shown below:

Fig. 9 Printing a message with MicroPython (Pi Pico)

  • If the command is executed successfully means the firmware is successfully installed or updated and we are ready to program our Raspberry Pi Pico with Thonny integrated development environment.

Conclusion

So, this concludes the tutorial and the installation procedure of Thonny Python IDE (Windows) for raspberry Pi Pico programming.

In our next tutorial we will discuss how to write a program for raspberry Pi Pico programming to control GPIOs using MicroPython programming language.

Types of IoT(Internet of Things)

Hi Guys! Glad to have you on board. Thank you for clicking this read. In this post today, I’ll walk you through the Types of Internet of Things (IoT).

IoT has been around for a while and has started making the headlines over the past couple of years. Some people experience IoT in their everyday life but are not aware of what it actually is. When physical objects “things” interact with the digital world, IoT is born. In simple words, it’s the network of connected devices integrated with sensors that work to exchange and share data over the internet. It is a rapidly growing technology with more than 18 billion connected IoT devices today and with the inception and boost of 5G technology this figure is expected to touch 125 billion by 2030. Experts say we may witness the stage when everything around us will be a thing in IoT. This is crazy.

I suggest you read this post all the way through as it aims to cover the types of Internet of Things.

Scroll on.

Types of Internet of Things (IoT)

IoT is used to improve efficiency and services, making humans’ lives easy and productive. The connected IoT devices range from simple kitchen appliances and thermostats to heart monitors and cooling systems. And when used in sophisticated industrial tools, IoT can enhance the productivity of the manufacturing and production processes.

The Internet of Things is commonly divided into eight major types:

1: Internet of Things (IoT)

2: Internet of Everything (IoE)

3: Internet of Nano Things (IoNT)

4: Internet of Mobile Things (IoMT)

5: Internet of Mission-Critical Things (IoMT)

6: Industrial Internet of Things (IIoT)

7: Infrastructure Internet of Things

8: Commercial Internet of Things

We’ll discuss each one in the section below.

1: Internet of Things (IoT)

IoT is a network of things embedded with sensors that connect to the internet for acquiring and sharing data with other connected devices. IoT is applied to make sure which data is important and which is useless to monitor the patterns and find out issues even before they occur. The main purpose of IoT technology is to automate processes, especially that are time-consuming, repetitive, and dangerous.

You might have heard the term “smart home” that has recently soared to popularity and is the main application of the IoT. A smart home is a home with a smart system that is mainly connected with the home appliances to automate certain tasks and can be remotely controlled. From commercial and domestic purposes to industrial and military use, you’ll find IoT everywhere.

2: Internet of Everything (IoE)

Internet of Everything (IoE) is the extension of the Internet of Things. The Internet of Things includes a connected network of things (physical objects) while the Internet of Everything, on the other hand, is about things, processes, data, and people. It covers the Internet for Everyone/Everything.

The IoE plays a key part to monitor and analyze real-time data obtained from a network of thousands of sensors connected to it. This data is then applied to accelerate people-based and automated processes. The IoE is beneficial to support modern business trends and can be incorporated into programs like m-learning and e-learning to allow students to learn new technologies.

3: Internet of Nano Things (IoNT)

Nanotechnology is on the rise. Big tech industries strive to make new devices compact, precise and small that can perform similar tasks to regular electronic devices.

The Internet of Nano Things is a network of Nanodevices connected with the internet to share and acquire information. The presence of Nano components in this technology makes it separable from the general Internet of Things technology.

4: Internet of Mobile Things (IoMT)

We are connected through smartphones. We use these devices to ease our lives and improve the way we communicate with each other. The IoMT is mainly geared towards the mobility of things where change occurs in connectivity, context, privacy, and energy availability.

The connectivity identifies how mobile device is connected using connectivity protocol either WiFi, 3G/4G or wired network. The context refers to the current location of the mobile. Energy availability means how a mobile phone is charged and the privacy issue may occur because of the wide use of cell phones thus the mobile phone locations are connected with the human possessors.

5: Internet of Mission-Critical Things (IoMT)

The Internet of Mission-Critical Things (IoMT) is used in critical missions like surveillance, critical structure monitoring, search and salvage, border patrol, battleground, etc. In simple words, it’s the use of IoT in battlefield situations or military settings. The main aim of this technology is to accelerate situational awareness, monitor surrounding risks, and improve response time. The main IoMT applications include tanks, planes, connecting ships, drones, and soldiers.

6: Industrial Internet of Things (IIoT)

The IoT plays a vital role in industries. This technology is commonly used in industries to automate production and manufacturing processes.

Automation guarantees the accuracy of the processes and removes the possibility of error which is very difficult to attain by using traditional processes and human workforce. Common industries that deploy IIoT include automotive, agriculture, logistics, and healthcare.

7: Infrastructure Internet of Things

Infrastructure IoT is focused on the development of modern infrastructure that uses IoT for maintenance, cost-saving, and operational efficiency. It is concerned to analyze and monitor the operations occurring in rural and urban infrastructures including railway tracks, bridges, and wind farms.

8: Commercial Internet of Things

Commercial Internet of Things mainly focuses on the use of IoT in commercial settings including stores, supermarkets, buildings, entertainments venues, healthcare facilities, and hotels. The main purpose of this technology is to improve business conditions, boost customer experience and monitor environmental conditions.

Developing your own IoT device is a no-brainer. There are platforms out there that are open source and offer you the opportunity to create your own IoT devices. Common platforms include Arduino.cc which is open source which means the code is developed to be accessible for the general public – anyone can edit, modify and distribute the code as they like better. And the other platform is Raspberry Pi which comes with a built-in Ethernet port allowing network communications a walk in the park.

That’s all for today. Hope you’ve enjoyed reading this article. If you’re unsure or have any questions regarding IoT, ask me in the section below. I’d love to assist you the best way I can. Thank you for reading this post.

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