SlideShare a Scribd company logo
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Inventor Of Raspberry Pi
• Eben Christopher Upton (born 5 April 1978) is a
British technical director and ASIC architect for
Broadcom.
• He is also a founder of Raspberry Pi Foundation,
and now CEO of Raspberry Pi (Trading) Ltd.
• He is also responsible for the overall software
and hardware architecture of the Raspberry Pi
device
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
GPIO - Header
Raspberry PI 3 GPIO Header
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Hardware Required
• A monitor with the correct cable and adapter.
• A micro USB power supply/USB C-type Power
port.
• A wired keyboard and mouse, or a
wireless keyboard and mouse with a Bluetooth
adapter.
• A micro SD card.
• A micro SD card reader.
• A Raspberry Pi.
Software Required
• SD card Formatter
– SD card must be formatted before using to boot
Raspberry PI.
• NOOBS
– NOOBS is an easy operating system installer
which contains Raspbian and LibreELEC. It also provides
a selection of alternative operating systems which are
then downloaded from the internet and installed.
Steps to Boot Raspberry Pi
• Format SD card
• Extract NOOBS in New Folder
– Copy the inside contents of New Folder to SD card
– Place the SD card on the slot of Raspberry Pi
– Power Up Raspberry Pi
– Connect USB Mouse, USB Keyboard and HDMI to
VGA cable to Monitor
– Install Raspbian OS
Command for Update or Upgrade OS
• sudo apt-get update
• sudo apt-get upgrade
Commands to Install Software
To install Arduino
sudo apt-get install arduino
To remove Arduino
sudo autoremove arduino
To install pyfirmata
sudo apt-get install pyfirmata
Or
sudo apt-get install python-pip python-serial
sudo pip install pyfirmata
Run Some Basic Terminal Commands
• pwd
• ls
• ls -l
• cd
• cd..
• mkdir foldername
• rmdir –r foldername
• touch filename
• cat filename
Reserved Keywords
Raspberry PI 3 GPIO Header
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Q1. Does RPi have an internal memory?
a) True
b) False
c) Don’t know sir
Q2. What do we use to connect TV to RPi?
a) Male HDMI
b) Female HDMI
c) Male HDMI and Adapter
d) Female HDMI and Adapter
e) Don’t know sir
Q3. How power supply is done to RPi?
a) USB connection
b) Internal battery
c) Charger
d) Adapter
e) Don’t know sir
• Program to toggle the LED connected to BCM-18 pin
Toggle LED
#Program to toggle the LED connected to BCM-18 pin
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)
Toggle LED Infinite
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
while True:
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)
Toggle Led N times
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
for x in range(0,5):
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)
Toggle Led According to User Input
import RPi.GPIO as GPIO
import time
x=int(input(“Enter the value : ”))
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
for x in range(x):
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Pulse Width Modulation (PWM)
• To create an analog signal, the microcontroller uses a technique
called PWM. By varying the duty cycle, we can mimic an
“average” analog voltage.
• A PWM signal is a digital square wave, where the frequency is constant, but
that fraction of the time the signal is on (the duty cycle) can be varied
between 0 & 100%
PWM has several uses:
• Dimming an LED
• Providing an analog output; if the digital output is filtered,
it will provide an analog voltage between 0% and 100% .
• Generating audio signals.
• Providing variable speed control for motors.
PWM Example
import RPi.GPIO as IO #calling header file which helps us use GPIO’s of PI
import time #calling time to provide delays in program
IO.setwarnings(False) #do not show any warnings
IO.setmode (IO.BCM) #we are programming the GPIO by BCM pin numbers. (PIN35 as ‘GPIO19’)
IO.setup(19,IO.OUT) # initialize GPIO19 as an output.
p = IO.PWM(19,100) #GPIO19 as PWM output, with 100Hz frequency
p.start(0) #generate PWM signal with 0% duty cycle
while 1: #execute loop forever
for x in range (50): #execute loop for 50 times, x being incremented from 0 to 49.
p.ChangeDutyCycle(x) #change duty cycle for varying the brightness of LED.
time.sleep(0.1) #sleep for 100m second
for x in range (50): #execute loop for 50 times, x being decremented from 49 to 0.
p.ChangeDutyCycle(50-x) #change duty cycle for changing the brightness of LED.
time.sleep(0.1) #sleep for 100m second
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
IR Sensor
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21,GPIO.IN)
try:
while True:
x=GPIO.input(21)
if(x==1):
print(“Object Detected”)
t.sleep(1)
else:
print(“No Object Detected”)
t.sleep(1)
except KeyboardInterrupt:
print(“User Interrupted”)
GPIO.cleanup()
Ultrasonic Sensor
• An Ultrasonic sensor is a device that can measure the distance to an object
by using sound waves.
• It measures distance by sending out a sound wave at a specific frequency
and listening for that sound wave to bounce back.
• By recording the elapsed time between the sound wave being generated
and the sound wave bouncing back, it is possible to calculate the distance
between the sonar sensor and the object.
• Since it is known that sound travels through air at about 344 m/s (1129 ft/s).
• Sound wave to return and multiply it by 344 meters (or 1129 feet) to find the
total round-trip distance of the sound wave.
• Round-trip means that the sound wave traveled 2 times the distance to the
object before it was detected by the sensor.
• To find the distance to the object, simply divide the round-trip distance in
half.
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
• The Trig pin will be used to send the signal and
• The Echo pin will be used to listen for returning signal
Ultrasonic Sensor
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
trigger=18
echo=23
GPIO.setwarnings(False)
GPIO.setup(trigger,GPIO.OUT)
GPIO.setup(echo,GPIO.IN)
while True:
GPIO.output(trigger,False)
time.sleep(1)
GPIO.output(trigger,True)
time.sleep(0.00001) #keep trigger_pin high for 10 micro_seconds
GPIO.output(trigger,False)
while(GPIO.input(echo)==0): #check, when the echo_pin goes low
starttime=time.time() #and, note down this time stamp
while(GPIO.input(echo)==1): #check, when the echo_pin goes high
stoptime=time.time() #and, note down this time stamp
totaltime=stoptime-starttime
distacne=(totaltime*34400)/2
print(distance)
time.sleep(2)
Key Interfacing
• The Button is wired in such a way that when it
is pressed, it will connect GPIO 23 to the
Ground(GND).
• Each GPIO pin in Raspberry Pi has software
configurable pull-up and pull-down resistors.
• When using a GPIO pin as an input, you can configure
these resistors so that one or either or neither of the
resistors is enabled, using the
optional pull_up_down parameter to GPIO.setup
• If it is set to GPIO.PUD_UP , the pull-up resistor is
enabled; if it is set to GPIO.PUD_DOWN , the pull-
down resistor is enabled.
• After running the code, when you push the Button, LED
should turn ON and in terminal window you will see
the text "Button Pressed...".
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup (23, GPIO.IN,pull_up_down=GPIO.PUD_UP) #Button to GPIO23
GPIO.setup(24, GPIO.OUT) #LED to GPIO24
try:
while True:
button_state = GPIO.input(23)
if button_state == False:
GPIO.output(24, True)
print('Button Pressed...')
#time.sleep(0.2)
else:
GPIO.output(24, False)
except:
GPIO.cleanup()
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Introduction
• The 7-segment display, also written as “seven
segment display”, consists of seven LEDs arranged in
a rectangular fashion as shown in the Figure.
• Each of the seven LEDs is called a segment.
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Introduction
• Each one of the seven LEDs in the display is given a positional segment which is
controlled by one pin.
• These LED pins are labeled a, b, c, d, e, f, and g representing each individual
LED.
• The other LED pins are connected together and wired to form a common pin.
• By forward biasing the appropriate pins of the LED segments, some segments
will be light and others will be dark allowing the desired character pattern of
the number to be generated on the display.
• This allows us to display each of the ten decimal digits 0 through to 9 or hexa
decimal numbers 0 through to F , on the same 7-segment display.
• An additional 8th LED is sometimes used within the same package thus allowing
the indication of a decimal point, (DP) when two or more 7-segment displays
are connected together to display numbers greater than ten.
Types of 7-Segment Displays
• The displays common pin is generally used to
identify which type of 7-segment display it is.
• As each LED has two connecting pins, one called the
“Anode” and the other called the “Cathode”.
• Therefore , there are two types of LED 7-segment
display:
– 1. Common Cathode (CC)
– 2. Common Anode (CA)
Common Cathode (CC)
• In the common cathode display,
– all the cathode connections of the LED segments
are joined together to logic “0″ or ground.
– The individual segments are illuminated by
application of a “HIGH”, or logic “1″ signal via a
current limiting resistor to forward bias the
individual Anode terminals (a-g).
Common Anode (CA)
• In the common anode display,
– all the anode connections of the LED segments are
joined together to “HIGH”, or logic “1″.
– The individual segments are illuminated by
application of a logic “0″ or ground signal via a
suitable current limiting resistor to the Cathode of
the particular segment (a-g).
Displaying Digital Digits
• Depending upon the decimal digit to be
displayed, the particular set of LEDs is forward
biased.
• The various digits from 0 through 9 can be
displayed using a 7-segment display as shown.
Displaying Decimal Digits (Cont..)
• Table 1: Display decimal digits using the 7-segments (Common Cathode)
Decimal Digit G F E D C B A
0 0 1 1 1 1 1 1
1 0 0 0 0 1 1 0
2 1 0 1 1 0 1 1
3 1 0 0 1 1 1 1
4 1 1 0 0 1 1 0
5 1 1 0 1 1 0 1
6 1 1 1 1 1 0 1
7 0 0 0 0 1 1 1
8 1 1 1 1 1 1 1
9 1 1 0 1 1 1 1
A
B
C
D
E
F G
Driving a 7-Segment Display
• Although a 7-segment display can be thought of as a single
display, it is still seven individual LEDs within a single package
and as such these LEDs need protection from over-current.
• LEDs produce light only when it is forward biased with the
amount of light emitted being proportional to the forward
current.
• This means that an LEDs light intensity increases in an
approximately linear manner with an increasing current.
• So this forward current must be controlled and limited to a
safe value by an external resistor to prevent damaging the LED
segments.
Driving a 7-Segment Display (Cont..)
• The forward voltage drop across a red LED segment is very low at
about 2-to-2.2 volts.
• To illuminate correctly, the LED segments should be connected to a
voltage source in excess of this forward voltage value with a series
resistance used to limit the forward current to a desirable value.
• Typically for a standard red colored 7-segment display, each LED
segment can draw about 15mA to illuminated correctly, so on a 5
volt digital logic circuit,
– the value of the current limiting resistor would be
about 200Ω (5v – 2v)/15mA, or
– 220Ω to the nearest higher preferred value.
Driving a 7-Segment Display (Cont..)
• So to understand how the segments of the display are
connected to a 220Ω current limiting resistor consider the
circuit below.
Driving a 7-Segment Display (Cont..)
• In this example,
– the segments of a common anode display are illuminated using
the switches.
– If switch a is closed, current will flow through the “a” segment of
the LED to the current limiting resistor connected to pin a and to
0 volts, making the circuit.
– Then only segment a will be illuminated.
– If we want the decimal number “4″ to
illuminate on the display, then switches
b, c, f and g would be closed to light the
corresponding LED segments.
Interfacing 7-Segment Display to Arduino
• The 7-Segment Display (shown in Figure below) can be interfaced to the
Arduino Uno Board as shown in the next two slides.
• Power supply of 5V DC is provided, either through Vcc1 pin or Vcc2 pin.,
with respect to a resister connected across.
Pin configuration of the 7-Segment
display with common anode
G F Vcc1 A B
E D Vcc2 C DP
CommonAnode(CA):
Com: Vcc=5V (through a Resistor)
A – G : Vcc=5V i.e. bibary ‘1’ => LEDs (A – G) will be OFF
A – G : Gnd=0V i.e. bibary ‘0’ => LEDs (A – G) will be ON
CommonCathode(CC):
Com: Gnd=0v (through a Resistor)
A – G : Vcc=5V i.e. bibary ‘1’ => LEDs (A – G) will be ON
A – G : Gnd=0V i.e. bibary ‘0’ => LEDs (A – G) will be OFF
0 – 9 using format()
#CA_SSD
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
data=[0x01,0x4f, 0x12, 0x06, 0x4c, 0x24, 0x20, 0x0f, 0x00, 0x04]
for i in range (2,9):
GPIO.setup(i,GPIO.OUT)
while True:
for j in range(0,10):
c=format(data[j],'08b')
print("c is:",c)
for k in range(2,9):
GPIO.output(k,int(c[k-1]))
time.sleep(1)
0 – 9 without format()
import RPi.GPIO as GPIO
Import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
a,b,c,d,e,f,g=4,17,18,27,22,24,25
char = [[0,0,0,0,0,0,1],[1,0,0,1,1,1,1],[0,0,1,0,0,1,0],[0,0,0,0,1,1,0],
[1,0,0,1,1,0,0],[0,1,0,0,1,0,0],[0,1,0,0,0,0,0],[0,0,0,1,1,1,1],[0,0,0,0,0,0,0],
[0,0,0,1,1,0,0]]
pins = [a,b,c,d,e,f,g]
for k in range(0,7):
GPIO.setup(pins[k],GPIO.OUT)
while True:
for i in range(0,10):
for j in range (0,7):
GPIO.output(pins[j],char[i][j])
time.sleep(1)
00 – 99
import RPi.GPIO as x
import time
x.setmode(x.BCM)
x.setwarnings(False)
data = [0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10]; # dp g f e d c b a
y=[24,23,22,27,18,17,4]
z=[25,5]
for i in range(len(y)):
x.setup(y[i],x.OUT)
for j in range(len(z)):
x.setup(z[j],x.OUT)
00 – 99 (Cont..)
while True:
for j in range(100):
a=j%10
b=j//10
c=format(data[a],'08b’)
g=format(data[b],'08b’)
for i in range(20):
x.output(z[1],1)
x.output(z[0],0)
for k in range(len(y)):
x.output(y[k],int(c[k+1]))
time.sleep(0.01)
x.output(z[1],0)
x.output(z[0],1)
for f in range(len(y)):
x.output(y[f],int(g[f+1]))
time.sleep(0.01)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Introduction
• Liquid crystal displays (LCDs) offer a convenient and
inexpensive way to provide a user interface for a
project.
Introduction (Cont..)
• Here, we are going to install and use the library from Adafruit.
• First, clone the required git directory to the Raspberry Pi by running the
following command in terminal window.
 git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git
• Next change into the directory, we just cloned and run the setup file.
 cd ./Adafruit_Python_CharLCD
 sudo python setup.py install (or) sudo python3 setup.py install
• Once it’s finished installing, you can now call the Adafruit library in any Python
script on the Pi.
• To include the library just add the following line at the top of the Python script.
– import Adafruit_CharLCD as LCD
• And to initialize the LCD python library, add the following.
– lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
some of the methods that are available, under Adafruit
library:
home() – This method will move the cursor back to home which is the first column on
the first line.
clear() – This method clears the LCD so that it’s completely blank.
set_cursor(col, row) – This method will move the cursor to a specific position. You
specify the position by passing the column and row numbers as parameters.
Eg. set_cursor(4,1)
enable_display(enable) – This enables or disables the display. Set it to True to enable it.
show_cursor(show) – This either shows or hides the cursor. Set it to True if you want
the cursor to be displayed.
blink(blink) – Turns on or off a blinking cursor. Set this to True if you want the cursor
to be blinking.
move_left() or move_right() – Moves the cursor either left or right by one position.
set_right_to_left() or set_left_to_right() – Sets the cursor direction either left to right or
right to left.
autoscroll(autoscroll) – If autoscroll is set to True then the text will right justify from
the cursor. If set to False it will left justify the text.
message(text) – Simply writes text to the display. You can also include new lines (n) in
your message.
#!/usr/bin/python
# Example using a 16x2 character LCD connected to a Raspberry Pi
import time
import Adafruit_CharLCD as LCD
# Raspberry Pi pin setup
lcd_rs = 26
lcd_en = 24
lcd_d4 = 23
lcd_d5 = 17
lcd_d6 = 18
lcd_d7 = 22
lcd_backlight = 2
# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows = 2
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
lcd.message('Hellonworld!')
# Wait 5 seconds
time.sleep(5.0)
lcd.clear()
text = input("Type Something to be displayed: ")
lcd.message(text)
# Wait 5 seconds
time.sleep(5.0)
lcd.clear()
lcd.message('GoodbyenWorld!')
time.sleep(5.0)
lcd.clear()
Connecting the LCD using I2C Protocol
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
DC Motor Interfacing
L293D Motor Driver IC
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
DC Motor connections to L293D
connections to L293D
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Sulphur
Sulphur
dioxide/Hydroge
dioxide/Hydroge
n Sulphide gas
n Sulphide gas
sensor
sensor
Temperature/
Temperature/
Humidity
Humidity
Sensor
Sensor
Thermal
Thermal
mass flow
mass flow
sensor
sensor
Data Types
1. list
2. tuple
3. dictionary
4. set
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Pre-define (Built-in) math functions
Import math
1.math.ceil(x)
2.math.floor(y)
3.math.fmod(x,y)
4.math.exp(x)
5.math.factorial(x)
6.math.sqrt(x)
7.math.pow(x,y)
Mathematical constants
Import math
1.math.pi
2.math.e
Pre-defined random numbers
generator functions
Import random
1.random.random()
2.random.uniform(a,b)
3.random.randint(a,b)
4.random.getrandbits(k)
5.random.choice(seq.)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Strings
• Initialization
• Concatination
• Repetetion
Split function:
• string_name.split()
Built-in string functions:
1. input_string_name.capitalize()
2. input_string_name.center(width,fill_char)
3. input_string_name.count(sub_string,beginning_index, end_index)
4. input_string_name.endswith(sub_string,beginning_index, end_index)
5. input_string_name.find(sub_string,beginning_index, end_index)
Built-in string functions (Cont..):
6. input_string_name.index(sub_string,beginning_index, end_index)
7. input_string_name.isupper()
8. input_string_name.islower()
9. input_string_name.istitle()
10. len(input_string_name)
Built-in string functions (Cont..):
11. input_string_name.lower()
12. input_string_name.upper()
13. max(input_string_name)
14. min(input_string_name)
15. input_string_name.startswith(sub_string,beginning_index,
end_index)
Built-in string functions (Cont..):
16. input_string_name.rfind(sub_string,beginning_index, end_index)
17. input_string_name.rindex(sub_string,beginning_index, end_index)
18. input_string_name.swapcase()
19. input_string_name.title()
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Python input/output
• Input(prompt)
• N= input(“Enter the number”)
• Print()
• Print (“statement”)
• >>> print(1,2,3,4,5,sep='@')
1@2@3@4@5
• >>> print(1,2,3,4,5,sep='*',end='&')
1*2*3*4*5&
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Decision making
• Sequential structure
i=i+1, j=j+1
• Selection structure
if(x<y):
i=i+1
else:
j=j+1
• Iteration structure
for I in range(5):
print(i)
• Encapsulation structure
If statement
if test expression:
statement(s)
Ex: num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
if test expression:
Body of if
else:
Body of else
Cont…
Ex: num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Cont…
Ex: num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Iteration - Looping
• While Loop:-
while test_expression:
Body of while
Ex: n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)
Cont…
Ex: counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Cont…
Ex: i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Ex: i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Cont…
• For loop:-
for val in sequence:
Body of for
Ex: numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
Cont…
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like", genre[i])
Cont…
Ex: digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Ex: student_name = 'Soyuj’
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Functions:
• Function definition:
• Function call
• No function declaration
Functions (Cont..):
Eg.
/* Function to add two numbers*/
def add(a,b):
sum=a+b
return sum
a=int(input(“Enter 1st
no. for a”))
b=int(input(“Enter 2nd
no. for b”))
result=add(a,b)
print(“Result=”, result)
Local and Global variables in
Functions:
Eg.
a=20
def display():
b=30
print(“Inside the user defi. fun.:”, a)
print(“Local variable:”, b)
display()
c=40
print(“Outside the user defi. fun.:”, a)
print(“Local variable:”, b)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Type of arguments:
Different ways, that the arguments could be passed to the system call are:
1.Required arguments
2.Keyword arguments
3.Default arguments
4.Variable length arguments
1. Required arguments:
Eg.
def display(a,b):
print(“a=”,a,”b=”,b)
display(10,20)
/*display(20,10)*/
2. Keyword arguments:
Eg.
def display(a,b):
print(“a=”,a,”b=”,b)
display(a=10,b=20)
/*display(b=10,a=20)*/
3. Default arguments:
Eg.
def display(name=“abc”,courses=“b.tech”):
print(“name=”, name)
print(“courses=”, courses)
display(name=“abc”, courses=“m.tech”)
display(name=“pqr”)
4. Variable length arguments:
Eg.
def display(*subjects):
for i in subjects:
print(i)
display(“b.tech”,”m.tech”,”mba”,”mca”)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Recursion Function:
1. Base case
2. Recursive case
Recursion Function (Cont..):
Eg.
def factorial(n):
if(n==0 or n==1)
return 1
else:
return n*factorial(n-1)
n=int(input(“Enter a value for n”))
result=factorial(n)
print(“Factorial of”,n,”is:”,result)
Anonymous/Lambda Function:
• Do not define by “def” keyword
– Will be defined by using “lambda” keyword
• Will return expression but not value
• Are one line functions
• Can take any number of arguments
• Can not access global variables
• Does not have any specific name
– Syntax: lambda argument(s):expression
Anonymous/Lambda Function:
Eg. /* Function to add two numbers*/
sum=(lambda x,y:x+y)
a=int(input(“Enter a value for a:”)
b=int(input(“Enter a value for b:”)
Print(“sum=”, sum(a,b))
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Command line Arguments:
• input()  takes the i/p in runtime (string format)
– Another way to accept the i/p’s. i.e. i/p’s will be processed to the
program as an arguments from the command prompt directly
• “sys” module
• All the arguments will be formed/saved as a LIST in
argv (argument’s value)
• By using sys.argv  we can access the command
prompt
• Arguments passing from command prompt will also
be considered as string
Command line Arguments (Cont..):
• Elements will be having by “sys.argv(LIST)”
• Elements of argv can be accessed using INDEX values
– sys.argv[0] is our file name, then from sys.argv[1] on wards
are the arguments/elements
• So we have to import “sys” module before using argv
Eg. Import sys
print(sys.argv)
print(len(sys.argv))
for ele in sys.argv:
print(“Arguments:”,ele)
Command line Arguments (Cont..):
• Eg. Program to add two add two numbers:
# sum of all the elements inputed from command line
Import sys
sum=0
for i in range(0,length(sys.argv)):
sum+=int(sys.argv[i])
print(“result=”, sum)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Meta-Characters:
[ ]  return a match if string contains characters specified in [ ]
^  return a match if string starts with given pattern
$  return a match if string ends with given pattern
.  accept any character except new line
*  return a match if there is zero or more occurrences of given pattern
+  return a match if there is one or more occurrences of given pattern
{ }  return a match if the string contains specified no. of occurrences
Spatial Sequences:
d  return a match if the given string having digits
D  return a match if the given string does not have digits
w  return a match if the given string having word characters
W  return a match if the given string does not have word characters
s  return a match if the given string having spaces
S  return a match if the given string does not have spaces
Z  return a match if the given string ends with specified character
Meta-Characters/Spatial sequences (Cont..):
Meta-Characters (Cont..):
import re
str = “Example for metacharacters in regular expression”
result=re.findall(“[a]”, str)
print(result)
result =re.findall(“^Example”, str)
result =re.findall(“expression$”, str)
result =re.findall(“Exam..”, str)
result =re.findall(“m*”, str)
Spatial Sequences (Cont..):
import re
str = “Example for metacharacters in regular expression”
Str2=“123 friend in need is a friend in deed”
result=re.findall(“s”, str2)
print(result)
res=re.findall(“d”, str2)
res=re.findall(“expression$”, str)
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING
Date and Time Module:
Time-Delta Function:
Any Query ???
RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING

More Related Content

PPTX
Python-in-Embedded-systems.pptx
PDF
Raspberry Pi GPIO Tutorial - Make Your Own Game Console
PDF
RaspberryPi_Workshop and Programming with python.
PDF
Intro to the raspberry pi board
PPTX
Raspberry Pi Introductory Lecture
PDF
4. GPIO Access
PPTX
Raspberry pi led blink
PPTX
Python and the Raspberry Pi
Python-in-Embedded-systems.pptx
Raspberry Pi GPIO Tutorial - Make Your Own Game Console
RaspberryPi_Workshop and Programming with python.
Intro to the raspberry pi board
Raspberry Pi Introductory Lecture
4. GPIO Access
Raspberry pi led blink
Python and the Raspberry Pi

Similar to RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING (20)

PDF
IoT Physical Devices and End Points.pdf
PPTX
M.Tech Internet of Things Unit - III.pptx
PPTX
910383538.pptxnnnnnnnnnnnnnnnnnnnnnnnnnnnn
PPTX
Custard pi 7 user information
ODP
Introduction to Raspberry Pi and GPIO
PDF
Ins and Outs of GPIO Programming
 
PDF
Raspberry Pi - best friend for all your GPIO needs
PDF
Embedded Systems: Lecture 9: The Pi Control ARM
PDF
Getting Started with Raspberry Pi - DCC 2013.1
PPTX
Raspberry Pi Using Python
PPTX
ScratchGPIO, Raspberry Pi & BerryClip
PDF
workshop slide.pdf
PDF
Arduino learning
PPTX
Fun with arduino
PPTX
Not so hard hardware
PPTX
Electronz_Chapter_2.pptx
PDF
workshop slide.pdf
PDF
Sensor and Actuators using Rasberry Pi controller
PPTX
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
PPTX
Raspberry Pi with Java 8
IoT Physical Devices and End Points.pdf
M.Tech Internet of Things Unit - III.pptx
910383538.pptxnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Custard pi 7 user information
Introduction to Raspberry Pi and GPIO
Ins and Outs of GPIO Programming
 
Raspberry Pi - best friend for all your GPIO needs
Embedded Systems: Lecture 9: The Pi Control ARM
Getting Started with Raspberry Pi - DCC 2013.1
Raspberry Pi Using Python
ScratchGPIO, Raspberry Pi & BerryClip
workshop slide.pdf
Arduino learning
Fun with arduino
Not so hard hardware
Electronz_Chapter_2.pptx
workshop slide.pdf
Sensor and Actuators using Rasberry Pi controller
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
Raspberry Pi with Java 8
Ad

More from Asif Iqbal (20)

PPTX
IOT WITH NODEMCU13231244425435465645.pptx
PPTX
first day presentation related to iot.pptx
PDF
5415Microprocessor-Lecture-11.pdf
PPT
11815939.ppt
PPTX
Chandrayaan 3.pptx
PPTX
Memory unit 6
PPTX
instruction
PPTX
OPTICAL COMMUNICATION Unit 5
PPTX
OPTICAL COMMUNICATION Unit 4
PPTX
optical communication Unit 3
PPTX
OPTICAL COMMUNICATION Unit 2
PPTX
OPTICAL FIBER COMMUNICATION UNIT-1
PPTX
Synchronous Sequential Logic Unit 4
PPTX
Combinational Logic Unit 2
PPTX
Unit-1 Digital Design and Binary Numbers:
PPTX
voltage regulater
PPTX
special diode
PPTX
oscillator unit 3
PPTX
Nunit 2 feedback
PPTX
digital to analog (DAC) & analog to digital converter (ADC)
IOT WITH NODEMCU13231244425435465645.pptx
first day presentation related to iot.pptx
5415Microprocessor-Lecture-11.pdf
11815939.ppt
Chandrayaan 3.pptx
Memory unit 6
instruction
OPTICAL COMMUNICATION Unit 5
OPTICAL COMMUNICATION Unit 4
optical communication Unit 3
OPTICAL COMMUNICATION Unit 2
OPTICAL FIBER COMMUNICATION UNIT-1
Synchronous Sequential Logic Unit 4
Combinational Logic Unit 2
Unit-1 Digital Design and Binary Numbers:
voltage regulater
special diode
oscillator unit 3
Nunit 2 feedback
digital to analog (DAC) & analog to digital converter (ADC)
Ad

Recently uploaded (20)

PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Construction Project Organization Group 2.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Welding lecture in detail for understanding
PPTX
web development for engineering and engineering
PPT
Project quality management in manufacturing
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Digital Logic Computer Design lecture notes
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Sustainable Sites - Green Building Construction
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
additive manufacturing of ss316l using mig welding
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Construction Project Organization Group 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Welding lecture in detail for understanding
web development for engineering and engineering
Project quality management in manufacturing
OOP with Java - Java Introduction (Basics)
Digital Logic Computer Design lecture notes
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Sustainable Sites - Green Building Construction
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
additive manufacturing of ss316l using mig welding

RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING

  • 2. Inventor Of Raspberry Pi • Eben Christopher Upton (born 5 April 1978) is a British technical director and ASIC architect for Broadcom. • He is also a founder of Raspberry Pi Foundation, and now CEO of Raspberry Pi (Trading) Ltd. • He is also responsible for the overall software and hardware architecture of the Raspberry Pi device
  • 6. Raspberry PI 3 GPIO Header
  • 8. Hardware Required • A monitor with the correct cable and adapter. • A micro USB power supply/USB C-type Power port. • A wired keyboard and mouse, or a wireless keyboard and mouse with a Bluetooth adapter. • A micro SD card. • A micro SD card reader. • A Raspberry Pi.
  • 9. Software Required • SD card Formatter – SD card must be formatted before using to boot Raspberry PI. • NOOBS – NOOBS is an easy operating system installer which contains Raspbian and LibreELEC. It also provides a selection of alternative operating systems which are then downloaded from the internet and installed.
  • 10. Steps to Boot Raspberry Pi • Format SD card • Extract NOOBS in New Folder – Copy the inside contents of New Folder to SD card – Place the SD card on the slot of Raspberry Pi – Power Up Raspberry Pi – Connect USB Mouse, USB Keyboard and HDMI to VGA cable to Monitor – Install Raspbian OS
  • 11. Command for Update or Upgrade OS • sudo apt-get update • sudo apt-get upgrade
  • 12. Commands to Install Software To install Arduino sudo apt-get install arduino To remove Arduino sudo autoremove arduino To install pyfirmata sudo apt-get install pyfirmata Or sudo apt-get install python-pip python-serial sudo pip install pyfirmata
  • 13. Run Some Basic Terminal Commands • pwd • ls • ls -l • cd • cd.. • mkdir foldername • rmdir –r foldername • touch filename • cat filename
  • 15. Raspberry PI 3 GPIO Header
  • 17. Q1. Does RPi have an internal memory? a) True b) False c) Don’t know sir Q2. What do we use to connect TV to RPi? a) Male HDMI b) Female HDMI c) Male HDMI and Adapter d) Female HDMI and Adapter e) Don’t know sir Q3. How power supply is done to RPi? a) USB connection b) Internal battery c) Charger d) Adapter e) Don’t know sir
  • 18. • Program to toggle the LED connected to BCM-18 pin
  • 19. Toggle LED #Program to toggle the LED connected to BCM-18 pin import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18,GPIO.OUT) GPIO.output(18,GPIO.HIGH) time.sleep(3) GPIO.output(18,GPIO.LOW) time.sleep(3)
  • 20. Toggle LED Infinite import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18,GPIO.OUT) while True: GPIO.output(18,GPIO.HIGH) time.sleep(3) GPIO.output(18,GPIO.LOW) time.sleep(3)
  • 21. Toggle Led N times import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18,GPIO.OUT) for x in range(0,5): GPIO.output(18,GPIO.HIGH) time.sleep(3) GPIO.output(18,GPIO.LOW) time.sleep(3)
  • 22. Toggle Led According to User Input import RPi.GPIO as GPIO import time x=int(input(“Enter the value : ”)) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18,GPIO.OUT) for x in range(x): GPIO.output(18,GPIO.HIGH) time.sleep(3) GPIO.output(18,GPIO.LOW) time.sleep(3)
  • 24. Pulse Width Modulation (PWM) • To create an analog signal, the microcontroller uses a technique called PWM. By varying the duty cycle, we can mimic an “average” analog voltage. • A PWM signal is a digital square wave, where the frequency is constant, but that fraction of the time the signal is on (the duty cycle) can be varied between 0 & 100% PWM has several uses: • Dimming an LED • Providing an analog output; if the digital output is filtered, it will provide an analog voltage between 0% and 100% . • Generating audio signals. • Providing variable speed control for motors.
  • 25. PWM Example import RPi.GPIO as IO #calling header file which helps us use GPIO’s of PI import time #calling time to provide delays in program IO.setwarnings(False) #do not show any warnings IO.setmode (IO.BCM) #we are programming the GPIO by BCM pin numbers. (PIN35 as ‘GPIO19’) IO.setup(19,IO.OUT) # initialize GPIO19 as an output. p = IO.PWM(19,100) #GPIO19 as PWM output, with 100Hz frequency p.start(0) #generate PWM signal with 0% duty cycle while 1: #execute loop forever for x in range (50): #execute loop for 50 times, x being incremented from 0 to 49. p.ChangeDutyCycle(x) #change duty cycle for varying the brightness of LED. time.sleep(0.1) #sleep for 100m second for x in range (50): #execute loop for 50 times, x being decremented from 49 to 0. p.ChangeDutyCycle(50-x) #change duty cycle for changing the brightness of LED. time.sleep(0.1) #sleep for 100m second
  • 27. IR Sensor import RPi.GPIO as GPIO import time as t GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(21,GPIO.IN) try: while True: x=GPIO.input(21) if(x==1): print(“Object Detected”) t.sleep(1) else: print(“No Object Detected”) t.sleep(1) except KeyboardInterrupt: print(“User Interrupted”) GPIO.cleanup()
  • 29. • An Ultrasonic sensor is a device that can measure the distance to an object by using sound waves. • It measures distance by sending out a sound wave at a specific frequency and listening for that sound wave to bounce back. • By recording the elapsed time between the sound wave being generated and the sound wave bouncing back, it is possible to calculate the distance between the sonar sensor and the object.
  • 30. • Since it is known that sound travels through air at about 344 m/s (1129 ft/s). • Sound wave to return and multiply it by 344 meters (or 1129 feet) to find the total round-trip distance of the sound wave. • Round-trip means that the sound wave traveled 2 times the distance to the object before it was detected by the sensor. • To find the distance to the object, simply divide the round-trip distance in half.
  • 32. • The Trig pin will be used to send the signal and • The Echo pin will be used to listen for returning signal
  • 33. Ultrasonic Sensor import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) trigger=18 echo=23 GPIO.setwarnings(False) GPIO.setup(trigger,GPIO.OUT) GPIO.setup(echo,GPIO.IN) while True: GPIO.output(trigger,False) time.sleep(1) GPIO.output(trigger,True) time.sleep(0.00001) #keep trigger_pin high for 10 micro_seconds GPIO.output(trigger,False)
  • 34. while(GPIO.input(echo)==0): #check, when the echo_pin goes low starttime=time.time() #and, note down this time stamp while(GPIO.input(echo)==1): #check, when the echo_pin goes high stoptime=time.time() #and, note down this time stamp totaltime=stoptime-starttime distacne=(totaltime*34400)/2 print(distance) time.sleep(2)
  • 35. Key Interfacing • The Button is wired in such a way that when it is pressed, it will connect GPIO 23 to the Ground(GND).
  • 36. • Each GPIO pin in Raspberry Pi has software configurable pull-up and pull-down resistors. • When using a GPIO pin as an input, you can configure these resistors so that one or either or neither of the resistors is enabled, using the optional pull_up_down parameter to GPIO.setup • If it is set to GPIO.PUD_UP , the pull-up resistor is enabled; if it is set to GPIO.PUD_DOWN , the pull- down resistor is enabled. • After running the code, when you push the Button, LED should turn ON and in terminal window you will see the text "Button Pressed...".
  • 38. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup (23, GPIO.IN,pull_up_down=GPIO.PUD_UP) #Button to GPIO23 GPIO.setup(24, GPIO.OUT) #LED to GPIO24 try: while True: button_state = GPIO.input(23) if button_state == False: GPIO.output(24, True) print('Button Pressed...') #time.sleep(0.2) else: GPIO.output(24, False) except: GPIO.cleanup()
  • 40. Introduction • The 7-segment display, also written as “seven segment display”, consists of seven LEDs arranged in a rectangular fashion as shown in the Figure. • Each of the seven LEDs is called a segment.
  • 42. Introduction • Each one of the seven LEDs in the display is given a positional segment which is controlled by one pin. • These LED pins are labeled a, b, c, d, e, f, and g representing each individual LED. • The other LED pins are connected together and wired to form a common pin. • By forward biasing the appropriate pins of the LED segments, some segments will be light and others will be dark allowing the desired character pattern of the number to be generated on the display. • This allows us to display each of the ten decimal digits 0 through to 9 or hexa decimal numbers 0 through to F , on the same 7-segment display. • An additional 8th LED is sometimes used within the same package thus allowing the indication of a decimal point, (DP) when two or more 7-segment displays are connected together to display numbers greater than ten.
  • 43. Types of 7-Segment Displays • The displays common pin is generally used to identify which type of 7-segment display it is. • As each LED has two connecting pins, one called the “Anode” and the other called the “Cathode”. • Therefore , there are two types of LED 7-segment display: – 1. Common Cathode (CC) – 2. Common Anode (CA)
  • 44. Common Cathode (CC) • In the common cathode display, – all the cathode connections of the LED segments are joined together to logic “0″ or ground. – The individual segments are illuminated by application of a “HIGH”, or logic “1″ signal via a current limiting resistor to forward bias the individual Anode terminals (a-g).
  • 45. Common Anode (CA) • In the common anode display, – all the anode connections of the LED segments are joined together to “HIGH”, or logic “1″. – The individual segments are illuminated by application of a logic “0″ or ground signal via a suitable current limiting resistor to the Cathode of the particular segment (a-g).
  • 46. Displaying Digital Digits • Depending upon the decimal digit to be displayed, the particular set of LEDs is forward biased. • The various digits from 0 through 9 can be displayed using a 7-segment display as shown.
  • 47. Displaying Decimal Digits (Cont..) • Table 1: Display decimal digits using the 7-segments (Common Cathode) Decimal Digit G F E D C B A 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 2 1 0 1 1 0 1 1 3 1 0 0 1 1 1 1 4 1 1 0 0 1 1 0 5 1 1 0 1 1 0 1 6 1 1 1 1 1 0 1 7 0 0 0 0 1 1 1 8 1 1 1 1 1 1 1 9 1 1 0 1 1 1 1 A B C D E F G
  • 48. Driving a 7-Segment Display • Although a 7-segment display can be thought of as a single display, it is still seven individual LEDs within a single package and as such these LEDs need protection from over-current. • LEDs produce light only when it is forward biased with the amount of light emitted being proportional to the forward current. • This means that an LEDs light intensity increases in an approximately linear manner with an increasing current. • So this forward current must be controlled and limited to a safe value by an external resistor to prevent damaging the LED segments.
  • 49. Driving a 7-Segment Display (Cont..) • The forward voltage drop across a red LED segment is very low at about 2-to-2.2 volts. • To illuminate correctly, the LED segments should be connected to a voltage source in excess of this forward voltage value with a series resistance used to limit the forward current to a desirable value. • Typically for a standard red colored 7-segment display, each LED segment can draw about 15mA to illuminated correctly, so on a 5 volt digital logic circuit, – the value of the current limiting resistor would be about 200Ω (5v – 2v)/15mA, or – 220Ω to the nearest higher preferred value.
  • 50. Driving a 7-Segment Display (Cont..) • So to understand how the segments of the display are connected to a 220Ω current limiting resistor consider the circuit below.
  • 51. Driving a 7-Segment Display (Cont..) • In this example, – the segments of a common anode display are illuminated using the switches. – If switch a is closed, current will flow through the “a” segment of the LED to the current limiting resistor connected to pin a and to 0 volts, making the circuit. – Then only segment a will be illuminated. – If we want the decimal number “4″ to illuminate on the display, then switches b, c, f and g would be closed to light the corresponding LED segments.
  • 52. Interfacing 7-Segment Display to Arduino • The 7-Segment Display (shown in Figure below) can be interfaced to the Arduino Uno Board as shown in the next two slides. • Power supply of 5V DC is provided, either through Vcc1 pin or Vcc2 pin., with respect to a resister connected across. Pin configuration of the 7-Segment display with common anode G F Vcc1 A B E D Vcc2 C DP CommonAnode(CA): Com: Vcc=5V (through a Resistor) A – G : Vcc=5V i.e. bibary ‘1’ => LEDs (A – G) will be OFF A – G : Gnd=0V i.e. bibary ‘0’ => LEDs (A – G) will be ON CommonCathode(CC): Com: Gnd=0v (through a Resistor) A – G : Vcc=5V i.e. bibary ‘1’ => LEDs (A – G) will be ON A – G : Gnd=0V i.e. bibary ‘0’ => LEDs (A – G) will be OFF
  • 53. 0 – 9 using format() #CA_SSD import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) data=[0x01,0x4f, 0x12, 0x06, 0x4c, 0x24, 0x20, 0x0f, 0x00, 0x04] for i in range (2,9): GPIO.setup(i,GPIO.OUT) while True: for j in range(0,10): c=format(data[j],'08b') print("c is:",c) for k in range(2,9): GPIO.output(k,int(c[k-1])) time.sleep(1)
  • 54. 0 – 9 without format() import RPi.GPIO as GPIO Import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) a,b,c,d,e,f,g=4,17,18,27,22,24,25 char = [[0,0,0,0,0,0,1],[1,0,0,1,1,1,1],[0,0,1,0,0,1,0],[0,0,0,0,1,1,0], [1,0,0,1,1,0,0],[0,1,0,0,1,0,0],[0,1,0,0,0,0,0],[0,0,0,1,1,1,1],[0,0,0,0,0,0,0], [0,0,0,1,1,0,0]] pins = [a,b,c,d,e,f,g] for k in range(0,7): GPIO.setup(pins[k],GPIO.OUT) while True: for i in range(0,10): for j in range (0,7): GPIO.output(pins[j],char[i][j]) time.sleep(1)
  • 55. 00 – 99 import RPi.GPIO as x import time x.setmode(x.BCM) x.setwarnings(False) data = [0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10]; # dp g f e d c b a y=[24,23,22,27,18,17,4] z=[25,5] for i in range(len(y)): x.setup(y[i],x.OUT) for j in range(len(z)): x.setup(z[j],x.OUT)
  • 56. 00 – 99 (Cont..) while True: for j in range(100): a=j%10 b=j//10 c=format(data[a],'08b’) g=format(data[b],'08b’) for i in range(20): x.output(z[1],1) x.output(z[0],0) for k in range(len(y)): x.output(y[k],int(c[k+1])) time.sleep(0.01) x.output(z[1],0) x.output(z[0],1) for f in range(len(y)): x.output(y[f],int(g[f+1])) time.sleep(0.01)
  • 58. Introduction • Liquid crystal displays (LCDs) offer a convenient and inexpensive way to provide a user interface for a project.
  • 60. • Here, we are going to install and use the library from Adafruit. • First, clone the required git directory to the Raspberry Pi by running the following command in terminal window.  git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git • Next change into the directory, we just cloned and run the setup file.  cd ./Adafruit_Python_CharLCD  sudo python setup.py install (or) sudo python3 setup.py install • Once it’s finished installing, you can now call the Adafruit library in any Python script on the Pi. • To include the library just add the following line at the top of the Python script. – import Adafruit_CharLCD as LCD • And to initialize the LCD python library, add the following. – lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
  • 61. some of the methods that are available, under Adafruit library: home() – This method will move the cursor back to home which is the first column on the first line. clear() – This method clears the LCD so that it’s completely blank. set_cursor(col, row) – This method will move the cursor to a specific position. You specify the position by passing the column and row numbers as parameters. Eg. set_cursor(4,1) enable_display(enable) – This enables or disables the display. Set it to True to enable it. show_cursor(show) – This either shows or hides the cursor. Set it to True if you want the cursor to be displayed. blink(blink) – Turns on or off a blinking cursor. Set this to True if you want the cursor to be blinking. move_left() or move_right() – Moves the cursor either left or right by one position. set_right_to_left() or set_left_to_right() – Sets the cursor direction either left to right or right to left. autoscroll(autoscroll) – If autoscroll is set to True then the text will right justify from the cursor. If set to False it will left justify the text. message(text) – Simply writes text to the display. You can also include new lines (n) in your message.
  • 62. #!/usr/bin/python # Example using a 16x2 character LCD connected to a Raspberry Pi import time import Adafruit_CharLCD as LCD # Raspberry Pi pin setup lcd_rs = 26 lcd_en = 24 lcd_d4 = 23 lcd_d5 = 17 lcd_d6 = 18 lcd_d7 = 22 lcd_backlight = 2 # Define LCD column and row size for 16x2 LCD. lcd_columns = 16 lcd_rows = 2
  • 63. lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight) lcd.message('Hellonworld!') # Wait 5 seconds time.sleep(5.0) lcd.clear() text = input("Type Something to be displayed: ") lcd.message(text) # Wait 5 seconds time.sleep(5.0) lcd.clear() lcd.message('GoodbyenWorld!') time.sleep(5.0) lcd.clear()
  • 64. Connecting the LCD using I2C Protocol
  • 72. Sulphur Sulphur dioxide/Hydroge dioxide/Hydroge n Sulphide gas n Sulphide gas sensor sensor Temperature/ Temperature/ Humidity Humidity Sensor Sensor Thermal Thermal mass flow mass flow sensor sensor
  • 73. Data Types 1. list 2. tuple 3. dictionary 4. set
  • 75. Pre-define (Built-in) math functions Import math 1.math.ceil(x) 2.math.floor(y) 3.math.fmod(x,y) 4.math.exp(x) 5.math.factorial(x) 6.math.sqrt(x) 7.math.pow(x,y)
  • 77. Pre-defined random numbers generator functions Import random 1.random.random() 2.random.uniform(a,b) 3.random.randint(a,b) 4.random.getrandbits(k) 5.random.choice(seq.)
  • 79. Strings • Initialization • Concatination • Repetetion Split function: • string_name.split()
  • 80. Built-in string functions: 1. input_string_name.capitalize() 2. input_string_name.center(width,fill_char) 3. input_string_name.count(sub_string,beginning_index, end_index) 4. input_string_name.endswith(sub_string,beginning_index, end_index) 5. input_string_name.find(sub_string,beginning_index, end_index)
  • 81. Built-in string functions (Cont..): 6. input_string_name.index(sub_string,beginning_index, end_index) 7. input_string_name.isupper() 8. input_string_name.islower() 9. input_string_name.istitle() 10. len(input_string_name)
  • 82. Built-in string functions (Cont..): 11. input_string_name.lower() 12. input_string_name.upper() 13. max(input_string_name) 14. min(input_string_name) 15. input_string_name.startswith(sub_string,beginning_index, end_index)
  • 83. Built-in string functions (Cont..): 16. input_string_name.rfind(sub_string,beginning_index, end_index) 17. input_string_name.rindex(sub_string,beginning_index, end_index) 18. input_string_name.swapcase() 19. input_string_name.title()
  • 85. Python input/output • Input(prompt) • N= input(“Enter the number”) • Print() • Print (“statement”) • >>> print(1,2,3,4,5,sep='@') 1@2@3@4@5 • >>> print(1,2,3,4,5,sep='*',end='&') 1*2*3*4*5&
  • 87. Decision making • Sequential structure i=i+1, j=j+1 • Selection structure if(x<y): i=i+1 else: j=j+1 • Iteration structure for I in range(5): print(i) • Encapsulation structure
  • 88. If statement if test expression: statement(s) Ex: num = 3 if num > 0: print(num, "is a positive number.") print("This is always printed.") if test expression: Body of if else: Body of else
  • 89. Cont… Ex: num = 3 if num >= 0: print("Positive or Zero") else: print("Negative number") if test expression: Body of if elif test expression: Body of elif else: Body of else
  • 90. Cont… Ex: num = 3.4 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
  • 91. Iteration - Looping • While Loop:- while test_expression: Body of while Ex: n = 10 sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter print("The sum is", sum)
  • 92. Cont… Ex: counter = 0 while counter < 3: print("Inside loop") counter = counter + 1 else: print("Inside else")
  • 93. Cont… Ex: i = 1 while i < 6: print(i) if i == 3: break i += 1 Ex: i = 0 while i < 6: i += 1 if i == 3: continue print(i)
  • 94. Cont… • For loop:- for val in sequence: Body of for Ex: numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] sum = 0 for val in numbers: sum = sum+val print("The sum is", sum)
  • 95. Cont… print(range(10)) print(list(range(10))) print(list(range(2, 8))) print(list(range(2, 20, 3))) genre = ['pop', 'rock', 'jazz'] for i in range(len(genre)): print("I like", genre[i])
  • 96. Cont… Ex: digits = [0, 1, 5] for i in digits: print(i) else: print("No items left.") Ex: student_name = 'Soyuj’ marks = {'James': 90, 'Jules': 55, 'Arthur': 77} for student in marks: if student == student_name: print(marks[student]) break else: print('No entry with that name found.')
  • 98. Functions: • Function definition: • Function call • No function declaration
  • 99. Functions (Cont..): Eg. /* Function to add two numbers*/ def add(a,b): sum=a+b return sum a=int(input(“Enter 1st no. for a”)) b=int(input(“Enter 2nd no. for b”)) result=add(a,b) print(“Result=”, result)
  • 100. Local and Global variables in Functions: Eg. a=20 def display(): b=30 print(“Inside the user defi. fun.:”, a) print(“Local variable:”, b) display() c=40 print(“Outside the user defi. fun.:”, a) print(“Local variable:”, b)
  • 102. Type of arguments: Different ways, that the arguments could be passed to the system call are: 1.Required arguments 2.Keyword arguments 3.Default arguments 4.Variable length arguments
  • 103. 1. Required arguments: Eg. def display(a,b): print(“a=”,a,”b=”,b) display(10,20) /*display(20,10)*/
  • 104. 2. Keyword arguments: Eg. def display(a,b): print(“a=”,a,”b=”,b) display(a=10,b=20) /*display(b=10,a=20)*/
  • 105. 3. Default arguments: Eg. def display(name=“abc”,courses=“b.tech”): print(“name=”, name) print(“courses=”, courses) display(name=“abc”, courses=“m.tech”) display(name=“pqr”)
  • 106. 4. Variable length arguments: Eg. def display(*subjects): for i in subjects: print(i) display(“b.tech”,”m.tech”,”mba”,”mca”)
  • 108. Recursion Function: 1. Base case 2. Recursive case
  • 109. Recursion Function (Cont..): Eg. def factorial(n): if(n==0 or n==1) return 1 else: return n*factorial(n-1) n=int(input(“Enter a value for n”)) result=factorial(n) print(“Factorial of”,n,”is:”,result)
  • 110. Anonymous/Lambda Function: • Do not define by “def” keyword – Will be defined by using “lambda” keyword • Will return expression but not value • Are one line functions • Can take any number of arguments • Can not access global variables • Does not have any specific name – Syntax: lambda argument(s):expression
  • 111. Anonymous/Lambda Function: Eg. /* Function to add two numbers*/ sum=(lambda x,y:x+y) a=int(input(“Enter a value for a:”) b=int(input(“Enter a value for b:”) Print(“sum=”, sum(a,b))
  • 113. Command line Arguments: • input()  takes the i/p in runtime (string format) – Another way to accept the i/p’s. i.e. i/p’s will be processed to the program as an arguments from the command prompt directly • “sys” module • All the arguments will be formed/saved as a LIST in argv (argument’s value) • By using sys.argv  we can access the command prompt • Arguments passing from command prompt will also be considered as string
  • 114. Command line Arguments (Cont..): • Elements will be having by “sys.argv(LIST)” • Elements of argv can be accessed using INDEX values – sys.argv[0] is our file name, then from sys.argv[1] on wards are the arguments/elements • So we have to import “sys” module before using argv Eg. Import sys print(sys.argv) print(len(sys.argv)) for ele in sys.argv: print(“Arguments:”,ele)
  • 115. Command line Arguments (Cont..): • Eg. Program to add two add two numbers: # sum of all the elements inputed from command line Import sys sum=0 for i in range(0,length(sys.argv)): sum+=int(sys.argv[i]) print(“result=”, sum)
  • 117. Meta-Characters: [ ]  return a match if string contains characters specified in [ ] ^  return a match if string starts with given pattern $  return a match if string ends with given pattern .  accept any character except new line *  return a match if there is zero or more occurrences of given pattern +  return a match if there is one or more occurrences of given pattern { }  return a match if the string contains specified no. of occurrences
  • 118. Spatial Sequences: d  return a match if the given string having digits D  return a match if the given string does not have digits w  return a match if the given string having word characters W  return a match if the given string does not have word characters s  return a match if the given string having spaces S  return a match if the given string does not have spaces Z  return a match if the given string ends with specified character
  • 120. Meta-Characters (Cont..): import re str = “Example for metacharacters in regular expression” result=re.findall(“[a]”, str) print(result) result =re.findall(“^Example”, str) result =re.findall(“expression$”, str) result =re.findall(“Exam..”, str) result =re.findall(“m*”, str)
  • 121. Spatial Sequences (Cont..): import re str = “Example for metacharacters in regular expression” Str2=“123 friend in need is a friend in deed” result=re.findall(“s”, str2) print(result) res=re.findall(“d”, str2) res=re.findall(“expression$”, str)
  • 123. Date and Time Module: