Thank you for being here for today's tutorial of our in-depth Raspberry Pi programming tutorial. The previous tutorial taught us how to install a PIR sensor on a Raspberry Pi 4 to create a motion detector. However, this tutorial will teach you how to connect a single seven-segment display to a Raspberry Pi 4. In the following sections, we will show you how to connect a Raspberry Pi to a 4-digit Seven-Segment Display Module so that the time can be shown on it.
Seven-segment displays are a simple type of Display that use eight light-emitting diodes to show off decimal numbers. It's common to find it in gadgets like digital clocks, calculators, and electronic meters that show numbers. Raspberry Pi, built around an ARM chip, is widely acknowledged as an excellent Development Platform. Its strong processing power can do amazing things in the hands of electronics enthusiasts and students. If we can figure out how to have it talk to the outside world and process data via an output, then we'll have a real chance of accomplishing all this. We analyze the data by viewing it on an LCD screen or other Display. Numerous sensors can detect specific parameters in the physical world and convert them to the digital world. It would never make sense to utilize a PI LCD panel to display a minimal quantity of information. Here, a 7-Segment or 16x2-Alphanumeric LCD panel is the preferred method of presentation.
There are few uses for a 7-segment display that don't need an LCD panel, even though a 16x2 LCD is preferable in most. If all you need to do is show some numbers, then an LCD, which has the downside of having a small character size, is excessive. Compared to a regular LCD screen, seven segments have the upper hand in dim environments and can be seen from wider angles. Let's get started.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Breadboard | Amazon | Buy Now | |
2 | Jumper Wires | Amazon | Buy Now | |
3 | Raspberry Pi 4 | Amazon | Buy Now |
Jumper wires
Seven segment display
1KΩresistors
Breadboard
The seven segments of a 7 Segment Display are each lit up by an individual LED to show the digits. To show the number 5, for example, you would make the glow pins for segments a, f, g, c, and d on the 7-segment high. This particular 7-segment display is a Common Cathode version, although there is also a Common Anode version.
The wiring diagram for connecting a 7-segment display to a Raspberry Pi is shown below. Here, 7-Segment Common Cathode has been utilized.
So, we'll simulate an 8-bit PORT on PI using its eight GPIO pins. Here, GPIO12 is the Most Significant Bit (MSB), while GPIO13 is the Least Significant Bit (LSB) (Most Significant Bit).
If we wish to show the number 1, we must activate both segments B and C. We must supply voltage to GPIO6 and GPIO16 to power segments B and C. Accordingly, the hexadecimal value of "PORT" is "06," and the byte value of "PORT" is "0b00000110." If we raise both pins to their highest positions, the number "1" will be shown.
The value for every displayable digit has been recorded and saved in a Character String with the label 'DISPLAY .'We have then used the Function 'PORT' to call those values one at a time and display the relevant digit.
Once everything is wired up according to the schematic, we can power up the PI and begin using PYTHON to write the program. Below is a function that allows us to program the GPIO pins on the PI, and we'll go over the few commands we'll be using in the PYTHON program to do so. We are also changing the name of the GPIO pins in the hardware from "GPIO" to "IO," which will be used throughout the code.
import RPi.GPIO as IO
The general-purpose input/output (GPIO) pins we need to use may be occupied with other tasks. If that's the case, the program's execution will be interrupted by warnings. The below command instructs the PI to continue running the software regardless of the warnings.
IO.setwarnings(False)
Pin numbers on the board and pin functions can be used to refer to PI's GPIOs. This GPIO5 is similar to the one labeled "PIN 29" on the board. Here we specify whether the number 29 or the number 5 will stand in for the pin.
IO.setmode (IO.BCM)
To use the LCD's data and control pins, we have assigned those functions to eight of the GPIO pins.
IO.setup(13,IO.OUT)
IO.setup(6,IO.OUT)
IO.setup(16,IO.OUT)
IO.setup(20,IO.OUT)
IO.setup(21,IO.OUT)
IO.setup(19,IO.OUT)
IO.setup(26,IO.OUT)
IO.setup(12,IO.OUT)
If the condition between the brackets evaluates to true, the looped statements will be run once. The value of PIN13 would be HIGH if and only if bit0 of the 8-bit 'pin' is true. There are eight 'if else' conditions, one for each of bits 0 through 7, so that each LED in the seven-segment Display can be set to either the High or Low state, depending on the value of the corresponding bit.
if(pin&0x01 == 0x01):
IO.output(13,1)
else:
IO.output(13,0)
As x increases from 0 to 9, the loop will be run 10 times for each command.
for x in range(10):
The following command can create an infinite loop, with which the statements included within the loop will be run repeatedly.
While 1:
All other commands and functions have been commented on in the following code.
import RPi.GPIO as IO # calling for the header file, which helps us use GPIO's of PI
import time # calling for time to provide delays in the program
DISPLAY = [0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x67] # string of characters storing PORT values for each digit.
IO.setwarnings(False) # do not show any warnings.
IO.setmode (IO.BCM) # programming the GPIO by BCM pin numbers. (like PIN29 as‘GPIO5’)
IO.setup(13,IO.OUT) # initialize GPIO Pins as outputs
IO.setup(6,IO.OUT)
IO.setup(16,IO.OUT)
IO.setup(20,IO.OUT)
IO.setup(21,IO.OUT)
IO.setup(19,IO.OUT)
IO.setup(26,IO.OUT)
IO.setup(12,IO.OUT)
def PORT(pin): # assigning GPIO logic by taking the 'pin' value
if(pin&0x01 == 0x01):
IO.output(13,1) # if bit0 of 8bit 'pin' is true, pull PIN13 high
else:
IO.output(13,0) # if bit0 of 8bit 'pin' is false, pull PIN13 low
if(pin&0x02 == 0x02):
IO.output(6,1) # if bit1 of 8bit 'pin' is true, pull PIN6 high
else:
IO.output(6,0) #if bit1 of 8bit 'pin' is false, pull PIN6 low
if(pin&0x04 == 0x04):
IO.output(16,1)
else:
IO.output(16,0)
if(pin&0x08 == 0x08):
IO.output(20,1)
else:
IO.output(20,0)
if(pin&0x10 == 0x10):
IO.output(21,1)
else:
IO.output(21,0)
if(pin&0x20 == 0x20):
IO.output(19,1)
else:
IO.output(19,0)
if(pin&0x40 == 0x40):
IO.output(26,1)
else:
IO.output(26,0)
if(pin&0x80 == 0x80):
IO.output(12,1) # if bit7 of 8bit 'pin' is true, pull PIN12 high
else:
IO.output(12,0) # if bit7 of 8bit 'pin' is false, pull PIN12 low
While 1:
for x in range(10): # execute the loop ten times incrementing x value from zero to nine
pin = DISPLAY[x] # assigning value to 'pin' for each digit
PORT(pin); # showing each digit on display
time.sleep(1)
The process of displaying a single number character on a 7-segment display is complete. However, we'd need more than a single 7-segment display to express information with more than one digit. Therefore, we will use a 4-digit seven-segment display circuit for this session.
Four individual Seven-Segment Displays have been linked up here. For a 4-digit 7-segment display, we know that each module will have 10 pins, so there will be 40 pins total. Soldering that many pins onto a dot board would be a hassle for anyone; thus, I recommend that anyone using a 7-segment display do so by purchasing a module or creating their PCB. See below for a diagram of the relevant connections:
In the preceding diagrams, we can see that the A-lines of all four displays are linked together as one A, and the same is true for B, C.... up until DP, which is essential for understanding how the 4-digit seven-segment module functions. Put another way, if trigger A is activated, the state of all 4 A's should be high.
Nonetheless, this never occurs. The four extra pins labeled D0 through D3 (D0, D1, D2, and D3) let us select which of the four displays is driven high. As an illustration, if I want my output to appear solely on the second Display, I would set D1 to high and leave D0, D2, and D3 at low. Using pins D0–D3 and A–DP, we can easily choose which displays should be on and which characters should be shown.
Let's check the many options for interfacing this 4-digit seven-segment Display with the Raspberry Pi. As can be seen in the diagram below, there are 16 pins on the 7-segment module. Even if your module's resources are limited, it will provide at least the following.
Segmented pins, either 7 or 8 segments (pins 1 to 8)
Pin holder to the ground (here pin 11)
A 4-digit code to unlock the door (pins 13 to 16)
See below for the wiring diagram of a digital clock built with a Raspberry Pi and a 4-digit Seven-segment display module:
You can also use the following table to ensure your connections are correct and follow the diagrams.
Locating the module's pins is the first step in making electrical connections. Identifying the Raspberry Pi's GPIO pins can be tricky; I've included an image to help.
Here, RPi is programmed in the Python programming language. The Raspberry Pi can be programmed in a wide variety of ways. Since Python 3 has become the de facto standard, we've opted to use that version as our integrated development environment (IDE). At the bottom of this guide, you'll find the whole Python code.
We'll go over the PYTHON instructions we'll be using for this project: first, we'll import the library's GPIO file; next, using the below function, we'll be able to program the Pi 4's GPIO pins. We are also changing the name of the GPIO pins in the hardware from "GPIO" to "IO," which will be used throughout the code. We've brought in time and DateTime to get the current time from Rasp Pi.
import RPi.GPIO as GPIO
import time, DateTime
The GPIO pins we're trying to use are already being used for something else. The program's execution will be interrupted with warnings if this is the case. The PI will be instructed to disregard the errors and continue with the software using the below command.
IO.setwarnings(False)
The physical pin number and the corresponding function number can refer to PI's GPIOs. As with 'PIN 29,' GPIO5 is a physical component on the circuit board. In this case, we specify whether the number "29" or "5" will stand in for the pin. GPIO. In BCM notation, GPIO5 pin 29 will be represented by a 5.
IO.setmode (GPIO.BCM)
As is customary, we'll start by setting the pins to their default values; in this case, both the segment and digit pins will be used as outputs. In our code, we organize the segment pins into arrays and set their values to zero by declaring them to be GPIO.OUT.
segment8 = (26,19,13,6,5,11,9,10)
for segment in segment8:
GPIO.setup(segment, GPIO.OUT)
GPIO.output(segment, 0)
We do the same thing with the digital pins, but we set them to output and set them to zero by default.
#Digit 1
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, 0) #Off initially
#Digit 2
GPIO.setup(8, GPIO.OUT)
GPIO.output(8, 0) #Off initially
#Digit 3
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, 0) #Off initially
#Digit 4
GPIO.setup(24, GPIO.OUT)
GPIO.output(24, 0) #Off initially
Numbers on a seven-segment display must be formed into arrays. To show a single digit, we need to toggle the on/off status of all but the dot pin of the 7-segment Display. For the numeral 5, for instance, we can use this setup:
For all alphabets and numerals, there is an equivalent sequence number. You can write on your own or utilize the handy table provided.
Using this information, we can create arrays for each digit in our Python code, as demonstrated below.
null = [0,0,0,0,0,0,0]
zero = [1,1,1,1,1,1,0]
one = [0,1,1,0,0,0,0]
two = [1,1,0,1,1,0,1]
three = [1,1,1,1,0,0,1]
four = [0,1,1,0,0,1,1]
five = [1,0,1,1,0,1,1]
six = [1,0,1,1,1,1,1]
seven = [1,1,1,0,0,0,0]
eight = [1,1,1,1,1,1,1]
nine = [1,1,1,1,0,1,1]
Let's bypass the function in the code that would otherwise be executed before entering the while loop and begin displaying characters on our 7-segment Display. If you hook up a Raspberry Pi to the internet, it will read the current time and divide it into four separate variables. For instance, when the time is 10.45, the values assigned to h1 and h2 will be 1 and 0, while m1 and m2 will be 4 and 5, respectively.
now = DateTime.DateTime.now()
hour = now.hour
minute = now.minute
h1 = hour/10
h2 = hour % 10
m1 = minute /10
m2 = minute % 10
print (h1,h2,m1,m2)
These four numbers will be displayed on one of our four digits. The lines below can be used to convert a variable's value to a decimal. Here, we show the value in variables on the 7-segment Display by using the function print segment (variable) with the digit 1 set to the highest possible value. You may be asking why we turn off this digit and why there's a delay after that.
GPIO.output(7, 1) #Turn on Digit One
print_segment (h1) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(7, 0) #Turn off Digit One
This is because the user will only be able to see the full four-digit number if all four digits are shown at once, and we all know that this isn't possible.
How, then, can we simultaneously show all four digits? With luck, our MPU is considerably quicker than the human eye. Therefore we offer one number at a time but exceptionally quickly. The MPU and segment display are given 2ms (variable delay time) to process each digit before we go on to the next. A human being cannot detect this 2ms lag; therefore, it appears as though all four digits illuminate simultaneously.
Understanding how to use print segment(variable) is the final puzzle piece. Arrays that have been declared outside of this function are used within it. As a result, the value of any variable passed to this function must be inside the range (0-9) so that the character variable can use in a meaningful comparison. Here, we check the variable against the value 1. The same is true for all comparisons with numbers between zero and nine. Assigning each value from the arrays to the appropriate segment pins is what we do if a match is found.
def print_segment(character):
if character == 1:
for i in range(7):
GPIO.output(segment8[i], one[i])
Use the provided schematic and code to connect your components and set up your Raspberry Pi. Once you've finished setting everything up, you can open the software and check the 7-segment Display to see the time. However, before doing this, you should check a few things.
If you want to be sure your Raspberry Pi isn't stuck in the past, you should update its time.
If you want to utilize a 7-segment display on your Raspberry Pi, you'll need to plug it into an adapter rather than a computer's USB connection because of the large amount of current it consumes.
import RPi.GPIO as GPIO
import time, DateTime
now = datetime.datetime.now()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#GPIO ports for the 7seg pins
segment8 = (26,19,13,6,5,11,9,10)
for segment in segment8:
GPIO.setup(segment, GPIO.OUT)
GPIO.output(segment, 0)
#Digit 1
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, 0) #Off initially
#Digit 2
GPIO.setup(8, GPIO.OUT)
GPIO.output(8, 0) #Off initially
#Digit 3
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, 0) #Off initially
#Digit 4
GPIO.setup(24, GPIO.OUT)
GPIO.output(24, 0) #Off initially
null = [0,0,0,0,0,0,0]
zero = [1,1,1,1,1,1,0]
one = [0,1,1,0,0,0,0]
two = [1,1,0,1,1,0,1]
three = [1,1,1,1,0,0,1]
four = [0,1,1,0,0,1,1]
five = [1,0,1,1,0,1,1]
six = [1,0,1,1,1,1,1]
seven = [1,1,1,0,0,0,0]
eight = [1,1,1,1,1,1,1]
nine = [1,1,1,1,0,1,1]
def print_segment(charector):
if charector == 1:
for i in range(7):
GPIO.output(segment8[i], one[i])
if charector == 2:
for i in range(7):
GPIO.output(segment8[i], two[i])
if charector == 3:
for i in range(7):
GPIO.output(segment8[i], three[i])
if charector == 4:
for i in range(7):
GPIO.output(segment8[i], four[i])
if charector == 5:
for i in range(7):
GPIO.output(segment8[i], five[i])
if charector == 6:
for i in range(7):
GPIO.output(segment8[i], six[i])
if charector == 7:
for i in range(7):
GPIO.output(segment8[i], seven[i])
if charector == 8:
for i in range(7):
GPIO.output(segment8[i], eight[i])
if charector == 9:
for i in range(7):
GPIO.output(segment8[i], nine[i])
if charector == 0:
for i in range(7):
GPIO.output(segment8[i], zero[i])
return;
while 1:
now = DateTime.DateTime.now()
hour = now.hour
minute = now.minute
h1 = hour/10
h2 = hour % 10
m1 = minute /10
m2 = minute % 10
print (h1,h2,m1,m2)
delay_time = 0.001 #delay to create the virtual effect
GPIO.output(7, 1) #Turn on Digit One
print_segment (h1) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(7, 0) #Turn off Digit One
GPIO.output(8, 1) #Turn on Digit One
print_segment (h2) #Print h1 on segment
GPIO.output(10, 1) #Display point On
time.sleep(delay_time)
GPIO.output(10, 0) #Display point Off
GPIO.output(8, 0) #Turn off Digit One
GPIO.output(25, 1) #Turn on Digit One
print_segment (m1) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(25, 0) #Turn off Digit One
GPIO.output(24, 1) #Turn on Digit One
print_segment (m2) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(24, 0) #Turn off Digit One
#time.sleep(1)
A similar section should appear below if everything is functioning as it should.
Typically, only 16 hexadecimal digits can be shown on a seven-segment display. Some show the digits 0-9, whereas others can show more. Seven-segment displays can only show a maximum of 16 values due to a lack of input leads. However, LED technology does allow for more than this. Even with the help of integrated circuit technology, the possible permutations of the seven parts on the screen are very few.
This guide taught us how to connect a 7-segment screen to a Raspberry Pi 4. The seven-segment Display, which we learned is employed in digital timers, clocks, and other electrical gadgets, are a cheap, basic electrical circuit and reliable module. Seven-segment displays can either be "common-anode" (where the common point is the power input) or "common-cathode" (where the common end is grounded). After that, we coded some python scripts to show numbers on a single seven-segment model and the time across four such screens. Next, we'll see how to use a Raspberry Pi 4 as the basis for a low-power Bitcoin miner.
Hello friends, I hope you all are doing well. Today, I am going to share the 4th chapter of Section-III in our Raspberry Pi programming course. In the previous lecture, we studied the Interfacing of IR sensor with Raspberry Pi 4. In this guide, you'll learn how to interface a PIR sensor with Raspberry Pi to create a motion detector. A passive infrared (PIR) sensor is a straightforward yet effective tool for motion detection.
As a bonus, a piezo speaker will play an audio clip whenever motion is detected. GPIO pins are required for both of these accessories. This tutorial is a great starting point for those who have never worked with electronic components and circuits.
These sensors are used in traditional, old-generation security systems. In contrast, video is used in most of today's monitoring systems. So, let's get started:
Today, we are going to design a security project, where we will sound an alarm using a piezo speaker, if any motion is detected by the PIR Sensor. We will use Raspberry Pi 4 for today's tutorial.
Here's the video tutorial:
Here's the list of components, used to design this motion detector:
As their name implies, passive motion sensors don't put out any rays of their own but instead pick up the infrared radiations emitted by other objects, making them ideal for use in intruder alarm devices. However, active detectors may produce and detect infrared light at the same time.
The PIR motion sensor has three pins:
In PIR Sensor, crystals sensitive to infrared light are used as sensors. As its a passive IR sensor, the sensor doesn't emit any IR waves, instead, it waits for the infrared-emitting object.
The IR sensing component consists of two subassemblies, A and B.
When there is no motion, the two detectors pick up identical infrared readings, which cancel out one another. Sensing element A will pick up the presence of infrared light, when an infrared-emitting object, such as a dog, enters the sensor's field of vision. Since the intensity of the infrared light striking sensing element B is still relatively low, the resulting differential change is positive.
As the object moves past the sensor, the intensity of the infrared light falling on sensing element B will be greater than that falling on sensing element A, resulting in a negative differential change. The BISS0001 logic chip onboard detects and amplifies this potential difference before outputting it as a digital signal.
When the infrared detector detects movement, it sends a signal to the microcontroller through the data input, which goes HIGH.
The Motion Sensor also has two potentiometers that may be adjusted to fine-tune the PIR sensitivity and the amount of time its output signal stays high after detecting motion.
As shown in the above figure, the left potentiometer allows you to adjust the sensor's sensitivity. Distances between 3 to 8 meters are adjustable. The Potentiometer can be turned clockwise to enhance the detection range and counterclockwise to decrease it.
The second Potentiometer controls the duration of the motion sensor's HIGH output. Times might be anything from 0.3s to 600s. The POT can be adjusted by turning it clockwise(to increase time) or counterclockwise (to decrease time).
We will design a simple Motion Detection Project using PIR Sensor & Piezo Speaker with Raspberry Pi 4. It's a simple security system where the PIR sensor will detect motion and Piezo Speaker will trigger the alarm.
A piezo buzzer is an easy-to-use speaker that makes noise whenever an electric current passes through it. The buzzer will sound an audible alert when the motion is detected.
Here's the circuit diagram of PIR Sensor with RPi4:
Just follow these steps to build the circuit.
We begin by importing the GPIO and time Python libraries, allowing us to communicate with the GPIO rail and halt the script. For our first two variables, which I have aptly dubbed "pins," we provide a reference to our physical ports. Our sensors' states will be kept in the now-valued state variable. If this value is zero, it is not turned on; if it is one, it is turned on. We'll change our GPIO mode to use the real PINs rather than the physical ones. Since each pin is given a unique number, this system is a tad simpler. We also configured our GPIO pins as inputs or outputs. To do things like detect motion, we'll plug in a PIR sensor. On the flip side, we need our piezo buzzer to function as an output.
import RPi.GPIO as GPIO
import time
pir_sensor = 11
piezo = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(piezo,GPIO.OUT)
GPIO.setup(pir_sensor, GPIO.IN)
current_state = 0
A while loop that never ends appears below. Due to the inherent permanence of the conditional statement, this loop can always be maintained. (You can still hit ctrl + c on the terminal to abort the script). To begin, we'll pause the script for 0.1 seconds. The next step is to retrieve the sensor's current state; if that state is 1 (for instance, the motion has been detected), the code within the if statement will be executed. If the value is not 1, we enter an infinite loop in which the sensor is repeatedly checked.
The if statement executes code that sets the piezo buzzer's output high, causing it to sound. This will occur for a split second before the script silences the buzzer. As soon as that timer expires, the if statement will leave, and the sensor will be rechecked after another five seconds. We have also used a try, except, finally, block with a nested outer block. Since stopping the script will require using the keyboard, we have included this. Finally, we must verify our script is tidy by calling GPIO.cleanup(). With the help of the try, except finally, coding construct, we can accomplish this.
try:
while True:
time.sleep(0.1)
current_state = GPIO.input(pir_sensor)
if current_state == 1:
print("GPIO pin %s is %s" % (pir_sensor, current_state))
GPIO.output(piezo,True)
time.sleep(1)
GPIO.output(piezo,False)
time.sleep(5)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
After you have completed all of your changes to the script, you may run it and see how it performs. Put the following command into your keyboard to accomplish this.
sudo python motion_sensor.py
The piezo buzzer should activate and make a noise if the PIR sensor detects motion in its field of view. If it doesn't, it's probably because you connected wires to the incorrect pins or because of a bug in the program. The Raspberry Pi's terminal will show an error message if it's a coding mistake.
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
pir_sensor = 11
piezo = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(piezo,GPIO.OUT)
GPIO.setup(pir_sensor, GPIO.IN)
current_state = 0
try:
while True:
time.sleep(0.1)
current_state = GPIO.input(pir_sensor)
if current_state == 1:
print("GPIO pin %s is %s" % (pir_sensor, current_state))
GPIO.output(piezo,True)
time.sleep(1)
GPIO.output(piezo,False)
time.sleep(5)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
This section is meant to test your understanding of this programming series so far, so I am leaving it as some homework for you. Build the circuit and comment below what the output will be. I will give an idea of the circuit and Python code.
Based on the success of GSM/EDGE and UMTS/HSPA, the Long-Term Evolution (LTE) standard was developed to ensure the continued development of wireless broadband communication. My LTE modem is a USB add-on for the Raspberry PI, giving it 3G or 4G (LTE) cellular data access. The modem is not used for cellular access in this project; instead, it is used to notify my phone of motion through text messages. The AT commands and serial connectivity allow me to command the modem and relay messages to my phone.
Begin by loading the required software onto your Raspberry Pi. Enter the terminal of the Raspberry Pi:
sudo apt install python3 python3-gpiozero python-serial -y
The TRM240 LTE modem requires a SIM card, which can be inserted here. To improve the modem's signal, attach the antenna to the top of the device.
Plug the LTE modem into a free USB port on the Raspberry Pi and power it on. The /dev directory should now list four additional USB ports. Just type this into the terminal to verify:
ls /dev/ttyUSB*
These gadgets should now be visible to you.
Sending AT commands to the device will be done through the ttyUSB2 port.
The sensor output pin should be connected to the 8-pin to the Raspberry Pi, and the VCC and GND pins should be connected to the appropriate pins on the Pi.
The cathode of the LED should be connected to a ground pin, the anode (longer leg) should be connected to a current-limiting resistor, and the other portion of the resistor should be connected to a GPIO pin to cause the indicator LEDs to illuminate when motion is detected. Input the green LED into the 40-pin connector and the red LED into the 38-pin connector on the board. This is a discretionary procedure. You can disable the LED sections in the sample code below if you don't want them to light up in response to the motion.
from gpiozero import MotionSensor, LED
from time import sleep, time
from sys import exit
import serial
import threading
# Raspberry Pi GPIO pin config
sensor = MotionSensor(14)
green = LED(21)
red = LED(20)
# Modem configuration
device = '/dev/ttyUSB2'
message = ''
phone_number = ''
sms_timeout = 120 # min seconds between SMS messages
def setup():
port.close()
try:
port.open()
except serial.SerialException as e:
print('Error opening device: ' + str(e))
return False
# Turn off echo mode
port.write(b'ATE0 \r')
if not check_response('OK', 10):
print('Failed on ATE0')
return False
# Enter SMS text mode
port.write(b'AT+CMGF=1 \r')
if not check_response('OK', 6):
print('Failed on CMGF')
return False
# Switch character set to 'international reference alphabet'
# Note: this still doesn't support all characters
port.write(b'AT+CSCS="IRA" \r')
if not check_response('OK', 6):
print('Failed on CSCS')
return False
return True
def check_response(string, amount):
result = ''
try:
result = port.read(amount).decode()
except:
return False
if not string in result:
try:
# Write 'ESC' to exit SMS input mode, just in case
port.write(b'\x1B \r')
except:
return False
return string in result
def send_sms():
global currently_sending, last_msg_time
currently_sending = True
try:
port.write('AT+CMGS="{}" \r'.format(phone_number).encode())
if not check_response('>', 6):
print('Failed on CMGS')
currently_sending = False
return
# Write the message terminated by 'Ctrl+Z' or '1A' in ASCII
port.write('{}\x1A \r'.format(message).encode())
while True:
result = port.readline().decode()
if 'OK' in result:
print('> SMS sent successfully')
last_msg_time = time()
currently_sending = False
return
if 'ERROR' in result:
print('> Failed to send SMS [{}]'.format(result.rstrip()))
currently_sending = False
return
except:
# Initiate setup if the got while the program was running
setup()
currently_sending = False
def on_motion():
print('Motion detected!')
green.off()
red.on()
if time() - last_msg_time > sms_timeout and not currently_sending:
print('> Sending SMS...')
threading.Thread(target=send_sms).start()
def no_motion():
green.on()
red.off()
print('* Setting up...')
green.on()
red.on()
port = serial.Serial()
port.port = device
port.baudrate = 115200
port.timeout = 2
last_msg_time = 0
currently_sending = False
if not setup():
print('* Retrying...')
if not setup():
print('* Try restarting the modem')
exit(1)
print('* Do not move, setting up the PIR sensor...')
sensor.wait_for_no_motion()
print('* Device ready! ', end='', flush=True)
green.on()
red.off()
sensor.when_motion = on_motion
sensor.when_no_motion = no_motion
input('Press Enter or Ctrl+C to exit\n\n')
As mentioned above, I will not give the output for this program; instead, let me know if you were successful.
This is a basic introduction to the PIR sensor and merely scratches the surface of its potential uses. Simple things like a counter (which adds up as people, cars, or other objects pass by) can trigger far more complex actions, such as turning on a Pi camera or running a new script. I'm hoping you've learned a lot from this Pi 4 motion sensor tutorial and that you've been able to put together a beautiful circuit and make it work with some code. Feel free to leave a remark below with your views, questions, or complaints. In the subsequent tutorial, we'll learn how to interface an ultrasonic sensor with Raspberry Pi 4. Till then, take care. Have fun!!!
Hello friends, I hope you all are doing great. Welcome to the 11th lecture of Section-III in the Raspberry Pi 4 Programming Series. In the previous tutorial, we discussed the interfacing of the Fingerprint sensor with Raspberry Pi 4. Today, we are going to discuss another sensor named the Pulse rate sensor and will interface it with Raspberry Pi 4.
The field of healthcare monitoring has long been seen as a potential use case for IoT i.e. examining the health instead of regular checkups and local doctors. Using sensors, your vital signs can be monitored and transmitted in real time, allowing a physician on the other side or even an AI to analyze the data and provide an accurate diagnosis. That does seem somewhat futuristic. However, we are making steady progress in that direction and will soon have an autonomous IoT robotic arm operating on us.
In today's tutorial, we'll design a heart rate monitor to keep tabs on a patient's heart rate, using Pulse Rate Sensor and Raspberry Pi. We will display the data(ECG graph) in the Processing IDE.
Here is all, you'll need to put together a Raspberry Pi-based patient monitoring system yourself:
A human vein is positioned directly in front of the sensor's LED. The tip of your finger or the inside of your ear can serve this purpose, but it must be positioned directly over a vein.
The sensor outputs three wires:
We'll use the 3.3V pin on the Raspberry Pi 4 to power up the sensor.
We will use ADS115 to transmit the analog signal from Heart Rate Sensor to Raspberry Pi 4, as the Pi can't read analog signals. Both ADS1015 and ADS1115 are high-precision, low-power analog-to-digital converters. These chips are commonly used with the Raspberry Pi because they operate at 3V3.
Any value from 8-860 samples/sec can be entered into ADS1115's sampling rate field. The shorter time an ADC needs to capture and transform an analog signal, the higher its sampling rate. A gain amplifier is included in the chip and can boost low-voltage signals by a factor of two to sixteen.
Here's the pinout diagram of ADS1115:
Here's the ADS1115's functional block diagram shown below:
A multiplexer takes the analog signals from the inputs and routes them to a programmable gain amplifier. An I2C bus transmits the results of the ADC's conversion of the amplified signal to a microcontroller.
Here are the pin connections of the above circuit:
Since the Analog-to-digital module uses I2C for communication, and we'll be using UART for serial communication, we'll need to activate UART and I2C on the Raspberry Pi by running raspi-config in the terminal.
To proceed, click the Interfacing Options button.
Select I2C and hit Enter.
Now, click the Yes button and hit Enter.
Now, select Ok to proceed.
Pressing the Enter key after selecting Serial will activate the serial port.
Select "no" and hit "enter" to turn off the serial login shell.
To activate the serial, click Yes and then hit Enter.
Choose ok and hit enter to continue.
Click Finish and hit Enter to confirm.
When prompted, type "Yes" and hit enter to reboot.
Now proceed to install the i2c packages.
sudo apt-get install -y python-smbus
sudo apt-get install -y i2c-tools
To determine which device is currently connected and to obtain its I2C address, run the following command:
sudo i2cdetect -y 1
Follow the below lines to install the Python library for the ADC module.
sudo apt-get update
sudo apt-get install build-essential python-dev python-smbus git
cd ~
git clone https://github.com/adafruit/Adafruit_Python_ADS1x15.git
cd Adafruit_Python_ADS1x15
sudo python setup.py install
Now, use the following command to add Processing to your current installation:
curl https://processing.org/download/install-arm.sh | sudo sh
We can now access Processing from the Raspberry Pi's main menu:
We'll use Python and processing codes for the pulse sensor to get the job done.
This code uses I2C communication to connect an ADC module that provides analogue pulse sensor output. Once the pulse sensor's analogue raw production is obtained, the sensor's higher maximum and minimum peak are located. Then calculate the beats per minute by subtracting the times of two extremes. Additionally, the BPM and raw analogue output are transmitted to a serial port, which is then read by the processing IDE. The complete python code for the heartbeat sensor on the Raspberry Pi is provided below.
While developing this code, we used several modules that we imported at the outset for various applications.
import Adafruit_ADS1x15
import serial
import time
We now have variables upon which to perform analyses and take appropriate measures. Also, we made a serial object.
rate = [0]*10
amp = 100
GAIN = 2/3
curState = 0
statechanged = 0
ser = serial.serial("/dev/ttys0",9600)
Now we use this chunk of code to transmit information to the processor.
def send_to_prcessing(prefix,data):
ser.write(prefix)
ser.write(str(data))
ser.write("\n")
Now we have a pre-programmed function to read the pulse sensor and calculate the heart rate.
def read_pulse();
firstBeat=True
seecondBeat=False
ssamplecounter=0
lastBeatTime=0
lastTime=int(time.time()*1000)
th = 525
P = 512
T = 512
IBI=600
pulse=False
adc=Adafruit_ADS1x15.ADS1015()
while True:
signal=adc.read_adc(0,gain=GAIN)
curTime=int(time.time()*1000)
send_to_pressing("S",signal)
samplecounter += curTime - lastTime
lastTime=curTime
N=samplecounter-lastBeatTime
if signal>th and signal>P:
P=signal
if signal(IBI/5.0)*3.0:
if signal
T=signal
The complete Python script for this post is provided for you at the end.
As we saw above, the python code sends a loopback signal to the serial port of raspberry, and the processing code receives that signal. Now we can see the unprocessed analogue input and the beats per minute. Also, the BPM value will be displayed alongside the analogue-value-based graph. We've loaded a few crucial library modules into the processing code.
import processing.serial.*;
PFont font;
serial port
A few factors have been taken into account after this.
char letter;
string words="";
int sensor;
int IBI;
int BPM;
int[] RawY;
int[] scaledY;
int[] rate;
float offset;
color eggshell=color(255,2)
int pulsewindowwidth;
int pulsewindowheight;
int zoom_val=70;
long beat_rec_time;
Then, we set up the serial port and the default graph in the setup method.
void setup()
{
size(500,400); // stage size
PulseWindowWidth=Width -20;
PulseWindowHeight=height -70;
frameRate(100);
textAlign(CENTER);
rectMode(CENTER);
ellipseMode(CENTER);
RawY=new int[PulseWindowWidth];
scaledY=new int[PulseWindowHeight];
We have parsed the received information at this point in the serialEvent method.
void serialEvent(serial port)
{
string inData=port.readstringuntil('\n');
inData=trim(inData);
if(inData.charAt(0)=='S'){
inData=inData.substring(1);
sensor=int(intData);
}
if (inData.charAt(0)=='B'){
inData=inData.substring(1);
BPM=int(inData);
beat_rec_time=millis()/1000;
}
if (inData.charAt(0)=='Q'){
inData=inData.substring(1);
IBI=int(inData);
}
}
We've plotted the graph by mapping the incoming numbers to the graph's dimensions in the draw function.
void draw()
{
background(0);
nostroke();
fill(eggshell); // color for the window background
rect(250,height/2,PulseWindowWidth,PulseWindowHeight);
RawY[RawY.length=1]=(1023=sensor)=212;
offset=map((float)zoom_val/100.0,0.5,1,100,0);
stroke(250,0,0);
nofill();
beginshape();
endshape();
if(millis()/1000>=beat_rec_time=5)
{
BPM=0;
IBI=0;
}
The following lines of code are required to display the BPM over the graph.
fill(255,0,0);
textsize(24);
text("Pulse Sensor Graph",width/2,25);
fill(0,0,255);
textsize(18);
text("IBI:" + IBI + "ms",width -70, height -10);
text("BPM:" + BPM, 50, height-10);
textsize(12);
text("zoom:" + zoom_val + "%", width -50,50);
Here, the code also includes a zoom function, allowing the user to selectively enlarge or reduce the size of the shown plot. The pulse plot can be panned around by pressing - to zoom out and + to zoom in. To adjust the setting, we must first click anywhere on the graph and then use the minus and plus buttons.
void Keytyped()
{
if(key == '+')
{
zoom_val++;
printIn(zoom_val);
}
else if(key == '-')
{
zoom_val--;
printIn(zoom_val);
}
if(zoom_val>100)
zoom_val=100;
else if(zoom_val<=0)
zoom_val=0;
}
Thus, using a Raspberry Pi, one may monitor a patient's heart rate and graph the results. This serial data can also be sent to IoT platforms like ThingSpeak for global data sharing if necessary.
import Adafruit_ADS1x15
import serial
import time
rate = [0]*10
amp = 100
GAIN = 2/3
curState = 0
stateChanged = 0
ser = serial.Serial ("/dev/ttyS0", 9600)
def send_to_prcessing(prefix, data):
ser.write(prefix)
ser.write(str(data))
ser.write("\n")
def read_pulse():
firstBeat = True
secondBeat = False
sampleCounter = 0
lastBeatTime = 0
lastTime = int(time.time()*1000)
th = 525
P = 512
T = 512
IBI = 600
Pulse = False
adc = Adafruit_ADS1x15.ADS1015()
while True:
Signal = adc.read_adc(0, gain=GAIN)
curTime = int(time.time()*1000)
send_to_prcessing("S",Signal)
sampleCounter += curTime - lastTime
lastTime = curTime
N = sampleCounter - lastBeatTime
if Signal > th and Signal > P:
P = Signal
if Signal < th and N > (IBI/5.0)*3.0 :
if Signal < T :
T = Signal
if N > 250 :
if (Signal > th) and (Pulse == False) and (N > (IBI/5.0)*3.0) :
Pulse = 1;
IBI = sampleCounter - lastBeatTime
lastBeatTime = sampleCounter
if secondBeat :
secondBeat = 0;
for i in range(0,10):
rate[i] = IBI
if firstBeat :
firstBeat = 0
secondBeat = 1
continue
runningTotal = 0;
for i in range(0,9):
rate[i] = rate[i+1]
runningTotal += rate[i]
rate[9] = IBI;
runningTotal += rate[9]
runningTotal /= 10;
BPM = 60000/runningTotal
print("BPM:" + str(BPM))
send_to_prcessing("B", BPM)
send_to_prcessing("Q", IBI)
if Signal < th and Pulse == 1 :
amp = P - T
th = amp/2 + T
T = th
P = th
Pulse = 0
if N > 2500 :
th = 512
T = th
P = th
lastBeatTime = sampleCounter
firstBeat = 0
secondBeat = 0
print("no beats found")
time.sleep(0.005)
read_pulse()
By collecting data from a wide variety of sources and transmitting it across a global network of the internet as well as other communication devices that are, in turn, linked to cloud services, the system improves the quality of care provided to patients. It allows doctors to respond to medical emergencies more quickly. In the suggested system, a doctor can do a checkup on a patient at any time, from any location. If the patient's value rises over the level, they should see a doctor, and an urgent message will be sent to them through email. Paralyzed patients and those ordered strict bed rest can benefit from this method since it allows their doctors to keep an eye on them from afar using a Raspberry Pi camera. More sensors can be integrated into the system, and the Internet of Things can be expanded so that everything can be accessed instantly. The model can be improved upon and made available as a mobile application so that users anywhere in the world can access it with minimal effort. In the following lesson, we will learn how to connect a PIR sensor to a Raspberry Pi 4.
Hi, my friends. Welcome to share a new tutorial in our ladder logic programming series. Today we will discuss counters in ladder logic programming using an expert’s view. So let’s wear the glasses of an expert in ladder logic programming and look deeply into counters, the types of counters, their variables and bits. In addition, techniques of using counters to solve a different kinds of problems that need counting. And without questions like every time, we will enjoy practicing programming and simulating all about counters. So with no further delay, let’s jump into our tutorial and nail that counters.
Tell me, guys, if you can imagine an industrial project or machine that does not need to count parts, products, or processing cycles. Actually, in most cases in industry and practical operations, you will find counters everywhere you visit production lines or operating machines. So now, what are the types of counters and what is inside or belongs to counters, their variables and bits? Also, what are the techniques for utilizing counters in ladder logic programming?
As regards functionality, counters can be divided into count up and count down, as shown in figure 1. Counter-up and down instruction blocks are shown in CTU and CTD. One is to count up, and the other is used to count down. They are different in functionality. However, they have the same variables, parameters, and data bits. So let’s discuss all this data belonging to counters.
Figure 2 images the data of counters. On the left tree, you guys notice the counters in the data files and on the right, see many counters that you can use in your ladder logic program. Also, the main variables are the preset value and the accumulator value by which you tell the program the counter will count up or down to what value. Also, you should know the left side of the rung is the input to the counter to activate it and let it counts when the input is high. While the right side is the output data bit of the counter which is the enable EN bit that tells the counter block has run okay. And the done bit DN that informs the counter reached the desired preset value by turning into high when the accumulator variable ACCUM goes equal to the PRESET value.
Figure 3 shows the best practice for utilizing counters and handling their logic. In the first rung, we used input I:1/0 to control the CTU counter set to count up to 10. So every time the input to the counter turns from low to high, the counter will count up by incrementing the ACCUM. Also, we have used the RES instruction to reset the counter at any time by having the input I:1/1. So by having the input I:1/1 turned to high, the counter’s accum will reset to zero. Now moving to the important part that provides the clue to process and handle counters. Starting from rung 3, the comparison instructions are used to check the ACCUM and control the outputs according to the logic we designed for. For example, in rung number 3, the EQU instruction compares the accumulator C5:1.ACC to zero to check if they are equal and if so, it energizes output O:20/0. In contrast, the NEQ compares instructions to check the inequality of the source C5:1.ACC and zero to decide the next state of output O:2/0. Furthermore, Runge 004 combines greater than GTR and less than instructions to check if the accumulator value is between two values and decide the state of the output on the right. Continuing further, the greater than or equal GTE and less than or equal LTE are used to check the accumulator as well but considering the boundary values.
Figure 4 demonstrates an example of the counter in which input I:1/1 has been used to control the counter input, and input I:1/2 is used to reset the counter. Also, in the third runge, the done bit of the counter controls the state of output O:4/0.
Figure 5 shows the simulation of the counter’s example. It shows the counter counts up every transition from low to high of the input I:1/1. Also, it shows that the output’s state of O:4/0 has come to high when the counter’s accumulator has reached the value of the preset value.
Also, as you see, friends, when input I:1/2 has clicked, the counter accumulator has been reset to zero thanks to utilizing the reset instruction RES.
Figure 7 demonstrates how using the comparison instructions to handle counters by comparing the accumulator of the counters, checking its value and controlling outputs accordingly. For example, in rung 002, output O:4/0 will go high when the counter’s done bit goes high or when it counts to 10. Also, output O: 4/4 will be turned to high in rung 004 when the accumulator of the counter is something between 3 and 7 but not 3 and 7 themselves. To include boundaries 3 and 7, the comparison instruction less than or equal LTE and greater than or equal GTE are used as rung 005 to control O:4/7. Also in rung 005. The compare instruction EQ is used to decide the state of output Q:4/6. In the simulated running example, when the counter’s accumulator was equal to 3, outputs O:4/7 and O:4/6 turned to true based on the results of the comparison instructions.
Exploring the data files on the left part of the view, you can also see the values and states of the counter’s variables and data bits. The value PRE is 10; the accumulator variable ACC is 10. So, the done bit DN is true or 1. Also, the function of the counter with cunting up is shown as 1.
After showing how to use the comparison instructions and introducing the counter variables and data bits, it is time to do something with counters. And here it is in figure 9; you can see a funny example of singers. In that example, we use two counters, CTU and CTD, to count up and down. The program utilizes flag B3:0/1 to manage which counter will be activated. As you see in rung number 1, when b3:0/1 is false, the counter CTU will be active to count up. By the time the counter reaches 10, its done bit turns high to activate flag B3:0/1. Then, the counter CTD is active to count back down to zero. And finally, when the CTD counts down until reaching zero, the flag B3:0/1 has turned off using unlatch (U) instruction to repeat the process again and again. So let’s see some tests for the implemented code to check if it is correct or if something needs to be amended.
Figure 10 shows the counter CTU is counting up every chance the input I:0/1 turns from OFF to ON.
Figure 11 shows how the logic turns to activate CTD after counter CTU reaches its preset value by flipping flag B3:0/1.
Figure 12 shows that the process has returned to count up after the accumulator has reached zero.
Now, guys, we have nailed counters showing the variables and related data bits and techniques of utilizing the comparison instructions to handle the counters logically. Thanks, guys, for following me up here . I hope you have enjoyed learning and practicing the counters in ladder logic programming. I hope to meet again with an interesting tutorial of our series of ladder logic programming.
Believing in the essence of timers in ladder logic programming, we come today with a new tutorial in which we are going to show you all about timers, the types of timers, what’s inside timers’ block of parameters, variables, and bits. In addition, techniques for using timers will be explored, and for sure, we are going to practice what we learn using the simulator. So let’s get started with our tutorial.
Guys, this is not the first time we’ve talked about timers. However, this time we are going to look into timers deeply and use the glasses of practical approach. So figure 1 shows the most important types of timers in ladder logic from left to right: the on-delay, off-delay, and retentive timers. There are differences in functionality. However, they all have the same parameters, variables, and bits. For example, the on-delay timer (TON) works by starting counting by getting the high logic state of its input. And bit goes ON when and only when the counter reaches the preset value. While the off-delay timer (OFF-DELAY) employs starting with the high logic of its Done bit once it has a high logic of its input. And when its high input stat is gone and turns to low. It starts counting until reaching the preset value, and then the done bit goes off. On the other hand, the retentive timer keeps accumulating the time while the input is energized until it reaches the preset value, at then the Done bit goes on. You can see, my friends, how are different in functionality to help you get a way for every problem related to timers. Despite that variety in behavior, they have the same data, as you can see in each timer block. So now, what are these data, and how can we utilize them in ladder logic programming? that is what we are going to learn together in this tutorial.
Well! Timer data can be demonstrated in figure 2. You can see guys in the tree view windows below; the data section shows the timers data in which there are dozens of timers you can use through long your program. But what does the data include? Well! The data has timer bits and variables, as shown on the right side of the window. The most important variables are the preset variable (PRE), in which we set the value of the time at which we require the timer to act ON. The other variable is the accumulator variable ACC that we use to know what the counted time is so far. The logic says the timer keeps increments accumulator until reaching the preset value. Okay, then what happens when the accumulator reaches the preset value? Exactly, the timer needs to indicate that he reaches the target. There are so-called timer bits like the timing bit TT that reports the timer is timing, and the DONE bit that tells the accumulator has reached the preset value. And also the EN bit that shows the completion of execution of the timing instruction.
Well, timers can be categorized based on their functionality and the way they work. For instance, the ON-DELAY timer starts timing when it gets a trigger signal which is the high state of its input. By reaching the preset value, the output will have been energized as long as the input is high. Please, guys, see the timing diagram in Figure 3 which depicts the timing diagram of the input and output of the ON-DELAY timer. It shows the timer contact goes on after counting the preset time value since it receives a high logic on its input coil.
The second but same important kind of timer is the OFF-DELAY timer. This timer starts energizing its contact or output from the moment it receives high logic input. Then after that input goes low, the output remains high in the logic state for as long as the preset value has been specified. Please, my friends, find the operation cleared in figure 4 below, which demonstrates the operation by the language of the time. In this example, the timer coil has been energized, and its contact goes high. And when the coil de-energized, the contact remained high for 5 seconds which is the preset amount of time of the timer.
The third timer we are going to show today is the retentive timer. So what does that timer do? Well, that timer accumulates the time whenever its coil is ON. The timing diagram is shown below in figure 5. More details about the timing diagram of retentive timers, what figure 5 demonstrates. You can notice, my friends, as long as the input is high, the timer accumulator keeps accumulating the time until one reset signal appears, then it resets the time. But it returns back, accumulating the time whenever the input is true.
Now we will show some examples to let you understand how to employ the timer variables and bits as well. Figure 6 shows the timer block of an OFF-DELAY timer. You can see, guys, the timer’s name is T4:1, the time base is set to 00.1, and the preset value is set to 100, meaning it is designed to time for 10 seconds that can be determined by multiplying the time base to the preset value. Also, you can see that the first rung used input I:1/0 to enable the timer by energizing its coil. Rungs 1 to 3 show how you guys might use the timer bits. For example, in rung number 1, the enable bit of the timer is used to energize output O:2/0. Similarly, the timing bit TT of the timer is utilized to turn on output O:2/1 in rung 002. While the done bit DN energizes output O:2/2 as in rung 003.
Here it is the simulation of one example to show how the timers bits and variables can set and used. In figure 7, the timer of type on-delay T4:4 is used and set to time for 10 seconds by setting the preset to 100 and the time base to one-tenth 0.1. the timer’s bits are used as you can see my friends to activate different outputs.
Example showing timers types
Another example demonstrated in figure 8 to show the on-delay and off-delay timers working together to fulfill the requested logic.
Figure 10 shows an example to demonstrate the utilization of a retentive timer type. You can see the timer block of the retentive timer RTO and how it is accumulating the time whenever the input is high without resetting when the input is turned off.
Going to one of the most important parts of our tutorial is how professionally you guys can use the timers to solve whatever problem you have. The techniques to use timers that come with experience. For example, figure 11 shows the cascading timing technique in which you can use multiple timers based on each other in a cascading way. You see, guys, how timer T4:2 depends on the Done bit of timer T4:1 in cascading approach. Why do we need to use two timers in such a way when we can use only one with a preset value equal to the sum of the two timers? That’s smart to be asked. But the answer also is intelligent, which tells us we might need to do some action in between. For example, when timer number one has done timing, we might energize one output, and after the second, we perform another action depending on the first timer.
Figure 12 shows the technique to reset the timer by having one normal close contact in the way of its input to control energizing the timer coil. In that very example demonstrated by figure 12, the timer Done bit itself is used to reset the timer, meaning that when the time contact acted ON, it is the time to reset the timer and like that, we can guarantee the timer keeps repeating the process forever.
And at that point, I would like to thank all my friends for following me till the end of that tutorial, and I hope you have learnt some knowledge and enjoyed practicing one of the most important topics in ladder logic programming, Timers. For recapping have nailed the timers by demonstrating the variables and bits of the timers and the types and techniques of using the timers to flexibly and professionally can deal with different situations and solve any problems related to using the time.
The traffic light is one of the most important applications we see everyday everywhere we go back and forth. Controlling traffic signs was managed by people which was very problematic and headache on travelers and the officers as well. But nowadays, most traffic lights are controlled by automatic control systems. The brain that handles the complicated logic behind the traffic light control system is a PLC and one programmer like you guys has written its logic. So today we have come back to enjoy programming such a critical and large project by using ladder logic programming and for sure will apply the code and the logic we write into the simulator to check its correctness.
First of all, the scene we captured below by figure 1 shows two ways to cross a traffic signal, the biggest and most complicated traffic sign you might see anywhere you go. We need to go through the logic and requirements and then list these alongside with the restrictions for realizing the safety which is very critical and crucial right here for saving people and vehicles traveling in each way in the cross traffic light. The complete project will be divided into two tasks to simplify the project and each task will be an exercise for you guys to do. So without any further delay let’s jump into our project’s exercises.
As you can see in figure 2, there are two faces of three traffic lights, one for each side way to control the cross traffic light. Each traffic light side has three indicators RED, green, and Ampere to represent the stop, ready-to-cross, and about-to-change that tells the car drivers and pedestrians when to stop and what time they can continue crossing. Each lamp has assigned to one output as you can see guys in the image. Our task is to control the timing of lighting each indicator to achieve the whole process. As we have mentioned earlier we are going to work the project into couple of milestones. So let we names two milestones in the first one we are going to control one way and will complement the work by adding the code to manage the two crossways by reaching that point we will have completed our mission. So let’s getting into the work.
Table 1 below lists the required amount of time and the sequence of the lighting of each indicator for controlling one way of the cross traffic light control project. As listed in the table below, the red light is connected to output O:2/00 and it is required to light it for 12 seconds. Then the green light that is connected to output O:2/02 should be lit for 8 seconds and finally the Amber light for 4 seconds which is connected to output O:2/01. Remember my friends, we need to repeat the process forever.
RED |
GREEN |
AMBER |
12 Sec. |
8 Sec. |
4 Sec |
Figure 3 shows the program of the first part to control one way. You notice guys the program is mainly based on utilizing timers. The idea is simply to start with an on-delay timer of the whole period which is 24 seconds. As it is clear the first rung energizes the timer T4: 0 to start timing for 24 seconds. Then by comparing the accumulating time, the second rung activate the green light for 8 seconds by using the comparing instruction LES in the way like keep energize the red light that connected to O:2/0 as long as the the accumulator of T4:0 which is is T4:0.acc less than 12 seconds. In the same way, in the period between 12 to 20 seconds the green light is activated for 8 seconds thanks to using the comparing instructions GRT and LES. And finally command the amper light to energize after 4 sec to the end. Notice my friend to let the process repeat forever, the timer is cleared or restarted by enabling the flag B3:1/0. Let us test the logic we have just implemented to see if it can work fulfilling the requirements or not.
The evaluation of the first part is depicted by figure 4. See guys the red sign is lit for 12 seconds and the green light follows for 8 seconds as shown in figure 5.
And figure 6 below depicts the ampere lighting for 4 seconds. Now you can see we have completed the first part.
But wait my friends as we can not proceed with the project and let it be working at this stage do you know why? Exactly, it is not safe because the control has not been programmed for the other way so the results would be sad as shown in figure 7.
As we mentioned earlier, the project has been achieved by dividing it into two parts. In the first part that we have just demonstrated above including the ladder logic program and testing using our simulator. That very part, part one can control one way traffic but we have two running traffic lights that should be considered. From here we are going to show the second part of the project. Let us start with the requirements.
Table 2 below asks you guys to control both traffic ways to have the red light on one side for a 12 seconds period time in which you need to allow the green light of the other way to light for 8 seconds and then the Amber light will be permitted for the next 4 seconds. The same logic will be applied on the reverse side. On another word, side number one is red with green and amper of side number two. Also, red of side number two with green and amper of side number one. Let us see the ladder logic and description of the implemented logic in the following section.
Red = O:2/00 |
Green = O:2/02 |
Amber = O:2/01 |
|
Green = O:2/06 |
Amber = O:2/05 |
Red = O:2/04 |
|
8 Sec. |
4 Sec. |
8 Sec. |
4 Sec. |
For the length of the program” We have divided it into two pieces. The first one is shown in the figure 8. You can see guys, it is similar to utilize the timers and compare instructions to accomplish the project. Like part one but adding amendments to combine the second part requirements. in the third rung you notice my friends we have added just restriction to not letting the green and amber light of one side while the green or amber does in the other side and vise versa. So what we are doing in the first four rungs is to handle one way traffic signal with restricting the other side when it is needed. Now let us move to the second part of code.
Figure 9 demonstrates the control of the other side by adding the logic for the green of the other side as in rung 5 considering the restriction of the green and amber of the side one at that time. Then in rung 7, the control for the amber light of side 2 considers inhibiting the amber and green of the side one for avoiding the crash to happen. And at last the red light is energized for 12 seconds in which the green and amber of the other side are not prohibited. Now time to test our logic has come so let us go testing that program.
Here you can see friends the test of the completed project in figure 10. Notice that one side has the green light on and the other side shows the red is lighted. As a result, the side with green light on allows the vehicles to pass while the side with red sign lighted in bit cars from passing.
More testing to check the opposite scenario for checking the cross traffic logic. Figure 11 shows the other side amber sign is on while the red of the opposite side is on. Therefore, the cars are allowed with the side that has the amber light on. On the other hand, the side that has the red light is one prevent cars from passing.
My friends, I really appreciate you following up to that very point and hoping you have got to learn and enjoy practicing one of the most important projects that you might see in everywhere you go in your daily life. Please know one thing which is very important that, the code we have implemented just right here is not the only way to solve such project. There are dozens of way to code such a project so please try your way without hesitation and keep trying to increase your knowledge and boost professionally in ladder logic programming. Thanks again guys and let us meet in another tutorial and project of the real life problem to learn and enjoy practicing ladder logic programming together.
Engineering projects are a crucial part of a student's engineering degree. Writing a project report is an essential part of any engineering project. The final step provides a summary of the project and its results. A good project report can help students get better grades and advance their career prospects. In this article, we will discuss the importance of engineering project writing and the steps involved in writing a successful project report.
Engineering project writing is a form of academic writing used to document an engineering project's progress. This type of report usually includes findings, conclusions, and recommendations. It should provide a clear and concise overview of the project and its impact on society. The report should be written in an organized and professional manner.
Engineering project writing is important because it plays an essential role in the success of an engineering project. It provides detailed documentation of the project, its findings, and its results. This helps project managers and stakeholders to evaluate the success of the project. It also helps to demonstrate to potential employers and clients the skills and knowledge of the engineering team.
https://codete.com/ provides comprehensive IT services and solutions that help companies innovate and increase their competitive advantage.
Writing an engineering project report can seem like a daunting task. However, following a few simple steps can make it easier and more effective.
1. Gather the Necessary Information: Before you start writing your project report, it is important to gather all the necessary information. This includes details about the project, its goals, the team, its progress, and the final results.
2. Outline the Report: Once you have all the necessary information, it is time to create an outline for the report. This will help you organize your thoughts and ensure that your report is structured and coherent.
3. Write the Introduction: The introduction should provide a brief overview of the project and its purpose. It should include an explanation of the project's objectives, the team's involvement, and the results achieved.
4. Write the Body: The body of the report should provide a detailed description of the project and its results. It should include information about the team, the methods used, the results achieved, and the conclusions.
5. Write the Conclusion: The conclusion should provide a summary of the project and its results. It should also include recommendations for future action.
6. Proofread and Edit: Once you have written the report, it is important to proofread and edit it. This will help ensure that the report is error-free and that it communicates the project's results effectively.
Writing an engineering project report is essential to any engineering project. The final step provides a summary of the project and its results. A good project report can help students get better grades and advance their career prospects. By following the steps outlined above, you can create a successful engineering project report that will help you demonstrate your skills and knowledge. Encouraging students to use their engineering project writings to showcase their technical prowess is also a good idea. It will also help in the post-graduation job search.
In the end, it is important to remember that engineering project reports should be clear, concise, and organized. With the right approach, you can create a report that will help you stand out from the crowd and advance your career prospects.
Thank you for being here for today's tutorial of our in-depth Raspberry Pi programming tutorial. The previous tutorial demonstrated the proper wiring of the photoresistor sensor to the GPIO pins. Finally, we learned how it might be included in a Python script for data collection and analysis needs. We also looked at the functions of each component in the circuit. However, I'll walk you through installing a Pi 4 Print Server in this guide. While installing the program is straightforward, setting it up so that a Windows network can locate the print server requires a little more effort. Rather than spending hundreds of dollars upgrading to a laser printer, you may easily upgrade your current USB printer to laser quality by installing a print server.
Because of this software, you no longer have to have the printer physically linked to a single computer, and you may place it wherever you choose and share it with as many computers as you like. In addition, it's a fantastic method of printer sharing that eliminates the need for a pricey tower computer to be on and active all the time. CUPS is the program we'll be using to make this happen. Common Unix Printing System, or CUPS, is the foundation of Linux printing applications. But, the program facilitates communication between your computer and printer. It would help if you visited available printing to verify that the CUPS printing software supports your printer model.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | Raspberry Pi 4 | Amazon | Buy Now |
Raspberry Pi 4
Wi-Fi
USB Printer
Since the Raspberry Pi print server is included in the Debian Jessie distribution, setting it up is a breeze. In this lesson, I'll be using Raspbian, so if you're unfamiliar with it and would like to learn how to set it up, check out my guide on how to do so.
We must ensure the Raspberry Pi is up-to-date with the most recent software to get started. Just type in the appropriate instructions into the terminal to accomplish this.
sudo apt update
sudo apt upgrade
We can begin setting up the print software after the Pi 4 has been upgraded. Here, we will be setting up CUPS.
CUPS, short for Common Unix Printing System, is a printing system designed for computers running UNIX-like operating systems. The software transforms the host computer into a print server. A CUPS-enabled server may receive print jobs from various client devices, sort them, and send them to the correct printer for output. Conveniently, this program can handle the administration of your printers, whether they're linked locally through USB or remotely via the network. Using the terminal, enter the following command to install the software. Considering HP has CUPS that support its open source project, HP printers, in particular. Even if your specific printer model isn't listed as being directly supported by CUPS, you may still be able to find a compatible generic driver online that will get the job done. These links will take you to a list of CUPS-compatible printers.
sudo apt install cups
We still have some work to do after CUPS's installation is complete. The first step is to include the pi user in the lpadmin set of users. With this group, the pi user can manage CUPS settings without logging in as the superuser.
sudo usermod -a -G lpadmin pi
To make sure it functions properly on your home network, there is one more thing we must do to CUPS: make it available to every computer on your network. At this time, Cups is configured to refuse connections from addresses outside the local network. By entering the following two commands, we can make it listen to all incoming connections:
sudo cupsctl --remote-any
sudo systemctl restart cups
After this, any machine on the network can send prints to the Pi 4 print server. The following command can be used if you need to know your Raspberry Pi's local IP Address.
hostname -I
If you know your Raspberry Pi's IP address, you can use it to access the website at the address below. Be sure to replace "192.168.1.105" with your IP address.
We'll examine how to configure SAMBA so that Windows can find the Raspberry Pi print server. Furthermore, we will demonstrate how to install a printer using the CUPS interface.
A proper SAMBA configuration is required if you use your print server in conjunction with Windows. To get SAMBA up and running with the CUPS print drivers, we'll have to install it and tweak its settings.
First, check that SAMBA is installed; to do so, we can use the terminal's built-in install command. Just by typing this into the terminal, we can accomplish our goal.
sudo apt install samba
Now that SAMBA is installed on our Pi 4, we can access its config file and make some changes. The following command will cause the file to be opened in the nano text editor:
Sudo nano /etc/samba/smb.conf
Once the file has been opened, it must be scrolled to the end. To do this quickly, press the Control key plus the V key. The following lines should be added or edited once you reach the very end of the file. The file already contained the "[printers]" and "[print$]" sections; all I had to do was update the values to reflect the following.
[printers]
comment = All Printers
browseable = no
path = /var/spool/samba
printable = yes
guest ok = yes
read only = yes
create mask = 0700
[print$]
comment = Printer Drivers
path = /var/lib/samba/printers
browseable = yes
read only = no
guest ok = no
To save the file, hit CTRL+X, Y, and ENTER. SAMBA needs to be restarted to pick up the updated settings. The following command, when entered into the terminal, will restart SAMBA.
sudo systemctl restart smbd
It's easy to set up a printer using CUPS, but first, we need to open the program's graphical user interface. For the IP address of your Raspberry Pi, enter "hostname" into the terminal.
hostname -I
To access the IP configuration page for your Raspberry Pi, type the following into your web browser and enter the IP address you just jotted down. Replace "192.168.1.105" with your IP address when entering this address.
The following homepage is what you should see. Here, we'll go to "Administration" on the main menu.
You'll be directed to Cups's control panel when you click here. On this page, select the "Add Printer" option.
The "Add Printer" screen has been brought up, allowing us to choose the printer we wish to configure Cups with. That printer is a Canon MG2500 series machine. When you've made your print choices, click the "Continue" button.
Ensure the printer is turned on and plugged into the Raspberry Pi through a USB connection if it does not appear here. If your Raspberry Pi still doesn't show up, try restarting it while ensuring your printer is on and connected.
Choose your printer's model from the dropdown menu here. CUPS will automatically identify the printer model and install the appropriate driver when possible. However, this may only sometimes work, so you may need to sift through the list to locate the proper driver manually. Once you've double-checked everything and are pleased, click the "Add Printer" button.
After completing the steps on this screen, the printer will have been added successfully. Here, you can give it a name and a summary that mean whatever you choose. If you have more than one printer in your residence, specifying its location will make your life easier. If you want other computers to be able to use the printer, you must also turn on "Share This Printer." If everything looks good, hit the "Continue" button.
After finishing the printer setup process, you will see the screen shown in the image below. Several of the printer's more nuanced settings are accessible through this panel—the number of pages printed, the quality of the printout, and so forth.
Having finished setting up our Raspberry Pi print server, we will now discuss how to add it to Windows. Having SAMBA set up earlier in the course should make this step less painless.
Installing a CUPS printer on Windows requires selecting the driver that will allow Windows to communicate with and comprehend the printer. Launching "My Computer" or "This PC" and then clicking "network" in the left-hand navigation pane is a quick method to get to Windows' network page, where you can get started. When you get there, you should see a screen like the one below, where your Raspberry Pi's hostname (in my instance, RASPBERRYPI) is displayed. If you double-click your Raspberry Pi's share, it may prompt you to log in. If entering anything other than "enter" fails to log you in, try "pi."
The printers used with your Pi 4 print server should now be displayed on the screen. Select the printer you wish to use by double-clicking on it.
You'll see the cautionary message below if you try to double-click this. Select "OK" to proceed with the tutorial.
Select your printer brand on the left, and then select your printer model from the available drivers for that brand on the right. If your printer isn't listed here, you can identify its model online and install the necessary drivers. For me, that meant tracking down the Canon MG2500 series. When you've decided which printer to use, you may move forward by clicking the "Ok" button.
The procedure will now initiate a link to your printer. Select "Printer" > "Set as Default Printer" to make this the system's default printer.
Now that the printer has been installed on your computer, you can use it with any application that supports printing. By printing a test page, you may verify that the printer is configured correctly.
If you're having trouble printing a file, check to see if you've picked the correct printer driver in CUPS and Windows. Ensure the printer is turned on as well; the Canon MG2500 series, for example, do not immediately restart when a print job is delivered. Adding Apple AirPrint capability to your Pi 4 print server is a great way to expand its capabilities.
Apple's AirPrint printing technology eliminates the requirement for users of Apple products to acquire and install the separate printing software. By adding AirPrint functionality, you may quickly and effortlessly print from your iOS smartphone to any nearby printer. You can run an AirPrint server from your Raspberry Pi, and Cups is the software that will power it. It will take care of talking to your printer on your Raspberry Pi's behalf.
The "Avahi daemon" must be set up before AirPrint may be used on your computer. The following command will install the package onto your Raspberry Pi.
sudo apt install avahi-daemon
Using this package, you can make Apple's Zeroconf design a reality. Bonjour has become widely used to refer to this type of network architecture. Using Bonjour, AirPrint can link disparate gadgets like an iPhone and a Raspberry Pi. Once you've selected the files you'd like to print, the Bonjour daemon will forward them to the designated printer.
Let's restart the machine to see whether the AirPrint server has worked appropriately, and everything is ready. Execute this command to force the Raspberry Pi to restart.
sudo reboot
After rebooting your Raspberry Pi, you can check to see if anything went wrong. This should get you to the point where you can print from any AirPrint-enabled device.
Have you succeeded in following this guide and setting up a Pi 4 network print server? If you've followed these steps carefully, your Raspberry Pi should be ready to function as a network AirPrint server. We were able to accomplish this by putting the Avahi daemon in place. This daemon implements the bonjour protocol used by AirPrint. Feel free to leave a message below if you have any thoughts, suggestions, or problems you'd want to discuss. The following tutorial will review the steps for monitoring a patient's heart rate with a Raspberry Pi 4.
Hello students! Welcome to the new tutorial on Python. We all know that Python is one of the most popular programming languages, and there are hundreds or thousands of developers that are earning a handsome amount with the help of this easy programming language. In the previous lecture, we studied the range in the sequence, and in the present class, our concern is having the command on the sets in Python. We know you are curious about the set's details, but before this, I want to share the list of topics that will be covered in this class.
What is a set in the Python programming language?
What are some properties that distinguish the set from other data types?
What is the mutable data type, and how is it related to the set?
Introduction of the Jupyter notebook.
Can we have duplicate elements in the set?
How to add, remove, and update the elements in the set while using the Jupyter notebook.
How can we access the elements using a loop?
Give an example of how to use the length function with sets and why it is important.
All of these are important interview questions, and we will not only find the answer to them but also elaborate on them with the help of simple but understandable examples taken from daily life routines. Your duty is to perform each and every code, not only by copying it from the lecture but also test your knowledge and practising more and more by making your own examples.
Since the last few tutorials on Python, we have been studying a lot about the sequence, which is basically the representation of a collection of data types with homogeneity or heterogeneity in the elements. If we talk about the sets, these have the same properties and procedures as their other group, such as list and range, but a slight difference in their property makes them a different data type. This can be elaborated with the help of its basic definition:
“The set is the type of sequence that contains the group of different data types, and it is the collection of unordered or unindexed data types together.”
Until now, the sequence discussed had been represented exactly as it was written by the programmers in the code. Yet, in the sets, the order is not exactly the same all the time. If you are thinking it is strange, then you must know, in the higher level of programming, this property of the set works great because we get the elements in random orders.
Another difference between the set and the other sequences is the usage of the bracket, or, in other words, the declaration of the sequences. To tell the compiler that we want a set in the sequence, the programmers use curly brackets. You must have noticed that it is very rare to use curly brackets in Python, and therefore we can say that the representation of the set in Python is unique.
As we have a lot of information about the sequences, we can openly discuss the properties of the set, and the reader will easily understand them by comparing them with others. So, here are some of the properties that can be compared:
Sets are represented with curly brackets.
The elements of the set can not be duplicated; that is, all the elements are uniquely defined, and no element should be repeated; otherwise, the compiler will show the output in which the duplicate values are shown only once.
The set is a heterogeneous collection of elements, and therefore, the programmers can add one or more data types to a single set according to their choice.
The set can be empty, that is, declared with zero elements.
The set can be updated after its formation if the programmer wants to make some changes to it afterwards.
There are certain built-in functions of the set that, when used with the sets, have great applications in Python programming.
Each of these properties can be explained well with the help of TensorFlow. We have been using the Jupyter lab of TensorFlow since the start of this tutorial, and now, I want to tell you a better and more professional way to run the code with the help of TensorFlow. For this, you do not have to install any other software but the Jupter notebook already installed on your PC. Simply go to your search bar and run the Jupyter notebook. It will add a new tab with the label "home." Here, go to the “New” dialogue box and select Python 3. This will add the new project to a new tab. You can name it, but by default, it is named "untitled."
If you are practising all the codes with us by hand, you will observe that the Jupyter notebook has a better user experience, and it adds the ending of common syntaxes such as the double quotation and parentheses by itself when the programmer starts them. We will talk more about it in later lectures, but for now, we are moving towards the codes and properties.
The first thing that we want to revise here is the definition of mutable elements:
“In programming languages, mutable objects are those that are used to group different items and can change their value according to the instruction of the programmer.”
We have learned many mutable sequences, such as lists, and here, the point is to revise it to a set and not use the mutable sequences as the elements. Only data types such as strings, integers, etc. can be used as the elements in the set; otherwise, the programmer will face an error. This can be explained with the help of the code given below:
#Starting new list
myList=["Physics", "chemistry", "biology"]
#declaring a new set
mySet={myList,'a','e','i','o','u'}
print(mySet)
As a result, it is demonstrated that programmers can combine simple data types into sets, but it is not possible to create collections of mutable objects or collections of collections within sets.
In the properties, we have mentioned that the process of feeding the duplicate elements into the set is not useful because it checks for each and every element while providing the output, and if the element is being repeated, the sets ignore them. As a result, if we have the element more than once in our input, the number of elements in the input and output are not the same.
#Declaring the set
MySet={21,23.6,55,'Peach', 'Almond', 23.6,21,'Almond'}
#using iteration to print the set
for item in MySet:
print(item, end=" ")
print()
#calculating the length
length=len(MySet)
print('Numbers of elements = ',length)
This property will be more clear with the help of the following screenshot:
Hence, out of eight elements, the two duplicate elements are removed by the compiler, and we only get five elements that were calculated by the length function.
This is an interesting method that is compatible with the set in Python. Consider the situation where the programmer has declared a set and then needs to add an element to the same pre-defined set. In such cases, the addition method is useful, with the help of which the programmer simply uses the syntax of the add method and there is no need to recreate the whole set again.
NameOfSet.add(element to be added)
If the question arises about the position of the element, this will be clear with the help of an example that we are going to check:
#Initializing the set
mySet={'eggs', 'bread', 'jam',23,67,132,55}
print('Elements of my set is= ', mySet)
#adding a new element
mySet.add("oats")
#printing the set with the added element
print('Elements of my set with new element= ', mySet)
Keep the scenario in your mind that we have discussed above, but this time, there is a need to remove the lament from the set, and for this, Python has another method that simply searches for the required element from the set and removes it. Afterwards, the results can be printed on the screen to check whether the task is complete or not. The keyword to remove the element is "discard,” and it is used in the same way as the add keyword.
#Initializing the set
mySet={'eggs', 'bread', 'oat','jam',23,67,132,55}
print('Elements of my set is= ', mySet)
#removing the element "oat"
removeValue=mySet.discard('oat')
#printing the set with the removed element
print('Elements of my set with discarded element= ', mySet)
So, the removal process is also very simple and understandable but the syntax must be kept in mind and before using the final set in this case, always check for the results by printing the elements on the screen as we are doing here because a little mistake on the syntax results in no removal and it may cause the problem in the code. So it is a good practice to have an eye on the elements.
The updating process of the set may include different types of updates, such as increasing the size or changing the elements' sizes. For a better understanding, the best way is to learn how two or more sets can be merged into one large set. In the previous lectures, we have seen this type of process where merging is done with the help of a method. To discuss a new method with you, here we are using the update method. The process and syntax are the same as we have seen in the previous two methods.
setToBeAdded.update(setToBeUpdated)
As a result, the final set has elements from both of these sets. But it is important to notice that both sets have to be declared first, and in the third step, we get the merged or updated search with the help of the command given above.
#Initializing the first set
myFirstSet={'eggs', 'bread', 'oat', 'jam',23,67,132,55}
print('Elements of first set is= ', myFirstSet)
#Initializing the second set
mySecondSet={'Python', 'Java', 'C++'}
print('Elements of second set is= ', mySecondSet)
#Updating the sets
myFirstSet.update(mySecondSet)
#printing the final set
print('Elements of final set= ', myFirstSet)
Hence both of these are merged together and as we are using the sets, the order of the final set is different and unarranged. Well, it is a good practice to check for the numbers of elements using the length function all the time.
We hope by now you have an idea of the for loop and how we use it with different data types in Python. Similar to the list, the programmers can access each and every element with the help of iterations (loops). So, let us review the elements of a set with the help of the for loop.
#declaring our set with the name to-do list.
ToDoList={'assignment', 'coding', 'prayer', 'washing cloths', 'doing dishes'}
#starting for loop
for work in ToDoList:
print(work, end=" ")
If we look at the output, we get the following results:
Hence, it was an interesting tutorial on the sets where we learned a lot about the topic and the details were interesting and related to our daily life. At the start, we saw the basic definition and a brief introduction to the topic. We have seen some properties of the sets that were resembling the types of sequences but these were also different in many ways and we not only studied them in detail but practically proved them in the Jupyter notebook. It was nice to use the Jupyter notebook that we are going to use onward in this series. In the next tutorial, we will put light on some other features so stay tuned with us because we are preparing our next lecture on Python.
Hey peeps! Welcome to the new lecture on the sequence data type, where we are discussing the range data type. We are interested in working on deep learning, and for this, we are learning the Python programming language from scratch. If we talk about the previous episode, we saw the byte and byte array methods that were amazing for converting the different data types into bytes. The current lecture will discuss the range data type, which is slightly different from the other types of sequences, so students will learn new and interesting concepts in the lecture; however, before we get into the details of our topic, take a look at today's highlights:
What is the range function?
How can you elaborate on the syntax of the range function in detail?
What are the three types of range functions?
Give us some examples of range functions in Python.
What are some basic questions the answer of which should be kept in mind while using the range function?
The answer to each question above will be provided before the end of this lecture. All the examples will be tried on TensorFlow for better understanding.
The range is a type of sequence in the data type that also represents the group or collection of the items together in different ways, just like other types of sequences. It is also the built-in function in Python, and while using it, the programmer gets the range object. The range is one of my favorite data types because it is easy to use and, in just a few simple steps, it provides us with the sequence of the integers according to our choice. Usually, the loops play an important role while dealing with the range function. Right now, as we have not learned about loops, you will simply have an idea of the workings and output of this data type.
The good thing about using the range function is that, unlike loops, the programmer does not have to use the logic behind the series but just has to put the values in the range function, and the results are great. Keep in mind that the range function is used with the loops, and there is less versatility in the range function when compared with the simple logical loops, but for basic workings, it is important to learn about the range, and this function is great.
The syntax of the range function is also easy, just like its group mates. You have to know about the three parameters and will determine all of them according to your requirements:
MyRange=range(start,stop,step):
for i in range(MyRange)
print(i)
Here, the semicolon at the end indicates that the syntax of the range function is complete, and the compiler now has to calculate the range arguments. Furthermore, if the programmer wants the result to appear on the same line as the interval, he can add end=" " at the end of the print. In this way, the compiler will not jump to the next line, but the results will be printed on the same line with a space between each element. Of course, the programmer has to save the result of the range function into a variable so that it can be used in the other functions. But here, it is important to mention that all of these parameters are not compulsory, but the range function gives you the independence to use one, two, or three of them.
The for loop is the iteration in the programming languages and you will learn them in detail in the coming lectures but for now, keep in mind that the range function alone can not do anything but it is fed into the for loop so that compiler can work on the iterations. The variable (usually i) is used in this loop and the results of the range function are input in this loop.
Another thing that must be mentioned here is the programmer has to choose the number of arguments according to the complexity of the series of numbers he or she wants. So here are the details of each case:
This is the most basic type of range function, in which the programmer simply specifies the point where the compiler has to stop making the range series. In all types of range functions, there is always a need for a stop parameter. Three things are to be mentioned here:
By default, the range starts at zero, and if the user does not have any particular choice for the start, the range function can be used with the only stop parameter.
Only whole numbers are printed on the screen.
The stop number, which is the limit of the range function, will not be printed on the screen.
When you put this value equal to zero, the result will be an empty range and you will get nothing.
for i in range(3):
print(i,end=" ")
Just think about the case where the default value, which is zero, is not to be used. Instead, the programmer has the option of printing the series of numbers without missing any of them and then specifying the start and stop ranges in the range function. But, as in the previous case, the stop number will not be printed on the screen, so you have to give the range of stops that you do not want on the screen, but the number before it is required there.
for i in range(3,34):
print(i,end=" ")
The third function, as expected, is the complete range function, into which the programmer feeds another step parameter. With the help of this, the programmers are able to get the series of numbers that starts from the point they want and have uniform intervals between the numbers and the ending point that is expected by the number. In short, the whole series is under the control of the programmer, but you have to notice that the steps are always uniform. The step function must not be zero and you will get the reason for this statement soon in this lecture. We can put the step value in the code discussed above and in this way, if 2 is the step value, the programmers will have half of the series as given above.
for i in range(3,34,2):
print(i,end=" ")
Here comes the action because, till now, the examples you have seen are simple examples with a simple series, but now, we are dealing with some exceptional cases that will clear some related concepts in your mind. We have divided the examples into some questions, and we will try to get the answers with the help of codes:
Till now, integers are being used in the range function but we know that integers and floats are the two most related data types and will try to attempt the range function with the help of floating values as the parameters.
for i in range(3.5,77):
print(i,end=" ")
As you can see, the compiler is throwing the error that it is not possible to use the float in the range function because it is designed only for integers. The same program will run when you remove the decimal part from the first value, which is the starting point.
Let me tell you the interesting way to get the range series with the help of inter tool chain method. But before this, you have to look at the basic definition of this tool.
“The iter-tool iterator is the pre-define module in python that provides the complex applications of the iteration in simple ways. The methods are defined in this module, and the programmers have to import them before using them.”
So, the chain method is also saved in this method, and when the programmers need to use them in a different way, they simply use the import keyword and use it in programs. As we are dealing with the range function, the iter-tool chain function is used to connect the results of two or more results in the form of a single series. Have a look at the code given next, and then read this paragraph again to get the point.
#import the chain method from the iter-tool library
from itertools import chain
# Printing two methods in a row
print("Concatenating the result")
MyChain = chain(range(4,7), range(34,55,2))
#using the method in the range
for i in MyChain:
print(i, end=" ")
The extraction of the concepts used in this program:
We can import the chain method from the library of itertools that have the iteration tools in it.
To import the method, we use from and import keywords that are represented with the green bold colour in the program.
Concatenation is the process of connecting two or more data types into a single line.
When using concatenation, the for loop is used by making a variable and saving the results of two connected ranges together in the variable.
The independence to use the number of arguments between one to three is the same in the concatenation as in all cases.
In the for loop, when using concatenation, only a variable is used.
The other way to get the same results is by using both ranges with the for loop, but the code will not be very clear in that case.
If the programmer wants to get the results in column form, he or she can simply delete the “end” part in the code.
The simple answer to the question is yes, and when we go into the details, the range function simply gets the indexes the programmer wants and can provide them with the single values they require. In simple words, the programmer tells the range function its stop value, and it assumes the whole series and picks the one number demanded by the programmer. The stop range is described in parentheses when the index to be picked is mentioned in the square bracelets.
#Give the range and pick the element through the index
MyRange = range(5)[2]
print("3rd element out of 5 =", MyRange)
print()
MyRange = range(3,34)[23]
print("23rd element of this range with start and stop value =", MyRange)
print()
MyRange = range(28)[5]
print("5th element of this range with start, stop, and step value =", MyRange)
Hence, the programmer can make a range of choices and then pick one element.
During the discussion of step, we saw the basic discussion of the step argument but keep in mind, if the programmer does not want the step function, he can simply ignore it. There is not need to input the step function as zero because, in such cases, the error will be shown on the screen.
for i in range(3,23,0):
print(i,end=" ")
Hence, from the above code, it is clear that the range of the stop argument is always greater than zero. Moreover, in the same code, if the value of the step argument is greater than the stop argument, it just shows the starting point of the range and does not give the other values or any errors because logically, it is true.
Truss, in this lecture, we saw many interesting concepts about the type of sequence called range function. This is a pre-defined function that is used to represent the group of numbers, and we can control the starting, ending, and interval values between the series of this number according to our wishes. This is always used with the for loop, and different cases of range functions were discussed in this lecture. Stay with us for more Python tutorials.