Professional Documents
Culture Documents
3.raspberry Pi Hardware Control
3.raspberry Pi Hardware Control
com
Note: need to turn off the programme of boot-up, then follow the below instructions
Open the terminal and input sudo nano /etc/rc.local then press Enter
Press Ctrl + o to save, then press Enter and Ctrl + X to exit editing
Raspberry Pi Control
Contents
Expansion Board.........................................................................................................................................................................3
1. Passive Buzzer........................................................................................................................................................................4
1.1 Code 1...................................................................................................................................................................................4
1.2 Run code 1 and test result.....................................................................................................................................................6
1.3 Code 2...................................................................................................................................................................................6
1.4 Run code 2.............................................................................................................................................................................9
2. Line Tracking Sensor............................................................................................................................................................10
2.1 Code....................................................................................................................................................................................10
2.2 Run code and test result......................................................................................................................................................11
1
www.keyestudio.com
3. Ultrasonic Sensor..................................................................................................................................................................12
3.1 Code....................................................................................................................................................................................13
3.2 Run code and test result......................................................................................................................................................15
4. Servo Control........................................................................................................................................................................15
4.1 Code 1.................................................................................................................................................................................16
4.2 Run code and test result......................................................................................................................................................17
4.3 Code2..................................................................................................................................................................................17
4.4 Run code and test result......................................................................................................................................................19
5. LED Panel.............................................................................................................................................................................19
5.1 8*16 Dot Matrix Display....................................................................................................................................................19
5.2 Interface Description and Communication Protocol:..........................................................................................................20
5.3 Introduction for modulus tool.............................................................................................................................................23
5.4 Code....................................................................................................................................................................................25
5.5 Run code and test result......................................................................................................................................................28
6. OLED Display.......................................................................................................................................................................28
6.1 Code....................................................................................................................................................................................28
6.2 Run code and test result......................................................................................................................................................30
6.3 Code2..................................................................................................................................................................................31
6.4 Run code 2 and test result...................................................................................................................................................33
7. Driver Motor.........................................................................................................................................................................34
7.1 Schematic Diagram........................................................................................................................................................34
7.2 Code....................................................................................................................................................................................35
7.3 Run code and test result......................................................................................................................................................37
8. Infrared Receiver...................................................................................................................................................................37
8.1 Code....................................................................................................................................................................................39
8.2 Run code and test result......................................................................................................................................................42
9. IR Remote Control Car.........................................................................................................................................................42
9.1 Code....................................................................................................................................................................................42
9.2 Run code and test result......................................................................................................................................................49
10. Line Tracking Car...............................................................................................................................................................49
10.1 Code..................................................................................................................................................................................50
10.2 Run code and test result....................................................................................................................................................54
11. Ultrasonic Following Car....................................................................................................................................................54
11.1 Code..................................................................................................................................................................................55
11.2 Run code and test result....................................................................................................................................................59
12. Ultrasonic Obstacle Avoidance Robot................................................................................................................................59
12.1 Code..................................................................................................................................................................................61
12.2 Run code and test result....................................................................................................................................................66
Expansion Board
2
www.keyestudio.com
When programming GPIO pins, there are three different ways to refer to
them: BCM GPIO number, physical number and WiringPi GPIO number.
Generally the WiringPi GPIO number is for the C language.The BCM GPIO
Our tutorial is written in Python, so the BCM GPIO number will be used,
and the silkscreen on the expansion board is identified by the BCM GPIO
number.
1. Passive Buzzer
Passive buzzer relies on piezoelectric effect to produce sound which is very clear
3
www.keyestudio.com
BCM pin:GPIO 16
1.1 Code 1
import time
buzPin = 16
i1 = 0
i2 = 0
GPIO.setmode(GPIO.BCM) # use BCM numbers
try:
4
www.keyestudio.com
while 1: #loop
while(i1<50):
GPIO.output(buzPin,GPIO.HIGH)
GPIO.output(buzPin,GPIO.LOW)
time.sleep(0.001)
i1 = i1 + 1
time.sleep(0.3)
while(i2<50):
GPIO.output(buzPin,GPIO.HIGH)
GPIO.output(buzPin,GPIO.LOW)
time.sleep(0.001)
i2 = i2 + 1
time.sleep(1)
i1 = 0
i2 = 0
except KeyboardInterrupt:
pass
5
www.keyestudio.com
cd /home/pi/RaspberryPi-Car/basic_project
After running test code, the buzzer will emit “tick,tick” sound。
1.3 Code 2
This example code uses GPIO.PWM to make the buzzer emit sounds with
different frequency.
import time
# Happy birthday
Do = 262
6
www.keyestudio.com
Re = 294
Mi = 330
Fa = 349
Sol = 392
La = 440
Si = 494
Do_h = 523
Re_h = 587
Mi_h = 659
Fa_h = 698
Sol_h = 784
La_h = 880
Si_h = 988
# The tune
song_1 = [
Sol,Sol,La,Sol,Do_h,Si,
Sol,Sol,La,Sol,Re_h,Do_h,
Sol,Sol,Sol_h,Mi_h,Do_h,Si,La,
Fa_h,Fa_h,Mi_h,Do_h,Re_h,Do_h
7
www.keyestudio.com
# delay
beat_1 = [
0.5,0.5,1,1,1,1+1,
0.5,0.5,1,1,1,1+1,
0.5,0.5,1,1,1,1,1,
0.5,0.5,1,1,1,1+1,
def setup():
location
GPIO.PWM
ration
def loop():
while True:
8
www.keyestudio.com
0.5s
def destory():
setup()
try:
loop()
destory()
9
www.keyestudio.com
cd /home/pi/RaspberryPi-Car/basic_project
After running test code, the buzzer will play a birthday song.
It mainly depends on whether the infrared receiving tube can receive the
GPIO 18 R : GPIO 17
10
www.keyestudio.com
2.1 Code
#tracking pin
trackingPin1 = 17
trackingPin2 = 18
trackingPin3 = 19
while True:
val1 = GPIO.input(trackingPin1) # read the value
val2 = GPIO.input(trackingPin2)
val3 = GPIO.input(trackingPin3)
print("tracking1 = ", val1, "tracking2 = ", val2, "tracking3 = ", val3)
sleep(0.1)
cd /home/pi/RaspberryPi-Car/basic_project
If the car is placed on the table, the IR receiving tube will receive the IR
11
www.keyestudio.com
3. Ultrasonic Sensor
As the above picture shown, it is like two eyes. One is transmitting end,
The ultrasonic module will emit the ultrasonic waves after triggering a
signal. When the ultrasonic waves encounter the object and are reflected
back, the module outputs an echo signal, so it can determine the distance
of the object from the time difference between the trigger signal and
echo signal.
The t is the time that emitting signal meets obstacle and returns. And the
12
www.keyestudio.com
speed * time. However, the ultrasonic wave emits and comes back, which
2. Setting the delay time of Trig pin of SR04 to 10μs at least, which can
ultrasonic pulses and detect whether there is a signal return. This step will
4. If the signal returns, the Echo pin will output a high level, and the
duration of the high level is the time from the transmission of the
13
www.keyestudio.com
3.1 Code
GPIO.setmode(GPIO.BCM)
def distance():
# 10us is the trigger signal
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001) #10us
GPIO.output(GPIO_TRIGGER, False)
start_time = time.time() # Log the time the program runs to this point
stop_time = time.time() # Log the time the program runs to this point
14
www.keyestudio.com
while True:
dist = distance() #
print("Measured Distance = {:.2f} cm".format(dist)) #{:.2f},Keep two decimal
places
time.sleep(0.1)
cd /home/pi/RaspberryPi-Car/basic_project
After running test code, then the detected distance value will be displayed
on the terminal.
4. Servo Control
15
www.keyestudio.com
servo has three lines in brown, red and orange. The brown wire is grounded,
the red one is a positive pole line and the orange one is a signal line.
through the cascade reduction gear, which leads that the voltage difference is
0, and the motor stops rotating. Generally, the angle range of servo rotation is
0° --180 °
The rotation angle of servo motor is controlled by regulating the duty cycle of
fact, it's between 0.5ms-2.5ms. The width corresponds the rotation angle from
0° to 180°. But note that for different brand motors, the same signal may have
Pins of servo:
Servo for ultrasonic sensor: GPIO 5 Base servo: GPIO 7 Servo for camera:GPIO 6
16
www.keyestudio.com
4.1 Code 1
def init():
GPIO.setup(servoPin1, GPIO.OUT)
try:
init()
while True:
for i in range(0,180):
servoPulse(servoPin1, i)
for i in range(0,180):
i = 180 - i
servoPulse(servoPin1, i)
except KeyboardInterrupt:
pass
cd /home/pi/RaspberryPi-Car/basic_project
17
www.keyestudio.com
4.3 Code2
servoPin2 = 7
servoPin3 = 6
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
def init():
GPIO.setup(servoPin2, GPIO.OUT)
GPIO.setup(servoPin3, GPIO.OUT)
try:
init()
while True:
for i in range(0,180):
servoPulse(servoPin2, i)
for i in range(0,180):
servoPulse(servoPin3, i)
for i in range(0,180):
i = 180 - i
servoPulse(servoPin2, i)
for i in range(0,180):
18
www.keyestudio.com
i = 180 - i
servoPulse(servoPin3, i)
cd /home/pi/RaspberryPi-Car/basic_project
After running the code, the pan tilt of the camera rotates.
5. LED Panel
19
www.keyestudio.com
①The starting condition for data input: SCL is high level and SDA changes
②For data command setting, there are methods as shown in the figure
below
20
www.keyestudio.com
Universal mode
Test mode
Irrelevant Irrelevant
choice, choice,
fill in 0 fill in 0
below.
The first 00H is selected in our sample program, and the binary number
21
www.keyestudio.com
Display address
Irrelevant
choice,
fill in 0
④The requirement for data input is that SCL is high level when inputting
data, the signal on SDA must remain unchanged. Only when the clock
signal on SCL is low level, the signal on SDA can be altered. The data
⑤ The condition to end data transmission is that when SCL is low, SDA is
low, and when SCL is high, the SDA level also becomes high.
⑥ Display control, set different pulse width, the pulse width can be
22
www.keyestudio.com
Function Description
http://dotmatrixtool.com/#
23
www.keyestudio.com
②The dot matrix is 8*16 in this project. So set the height to 8, width to 16,
24
www.keyestudio.com
As shown below, the left button of the mouse is for selection while the
right is for canceling. Thus you could use them to draw the pattern you
5.4 Code
SCLK = 8
DIO = 9
# Display pattern data
smile = (0x00, 0x00, 0x38, 0x40, 0x40, 0x40, 0x3a, 0x02, 0x02, 0x3a, 0x40, 0x40, 0x40,
0x38, 0x00, 0x00)
matrix_forward = (0x00, 0x00, 0x00, 0x00, 0x12, 0x24, 0x48, 0x90, 0x90, 0x48, 0x24, 0x12,
0x00, 0x00, 0x00, 0x00)
matrix_back = (0x00, 0x00, 0x00, 0x00, 0x48, 0x24, 0x12, 0x09, 0x09, 0x12, 0x24, 0x48,
0x00, 0x00, 0x00, 0x00)
25
www.keyestudio.com
matrix_left = (0x00, 0x00, 0x00, 0x00, 0x18, 0x24, 0x42, 0x99, 0x24, 0x42, 0x81, 0x00,
0x00, 0x00, 0x00, 0x00)
matrix_right = (0x00, 0x00, 0x00, 0x00, 0x00, 0x81, 0x42, 0x24, 0x99, 0x42, 0x24, 0x18,
0x00, 0x00, 0x00, 0x00)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(SCLK,GPIO.OUT)
GPIO.setup(DIO,GPIO.OUT)
def nop():
time.sleep(0.00003)
def start():
GPIO.output(SCLK,0)
nop()
GPIO.output(SCLK,1)
nop()
GPIO.output(DIO,1)
nop()
GPIO.output(DIO,0)
nop()
def matrix_clear():
GPIO.output(SCLK,0)
nop()
GPIO.output(DIO,0)
nop()
GPIO.output(DIO,0)
nop()
def send_date(date):
for i in range(0,8):
GPIO.output(SCLK,0)
nop()
if date & 0x01:
GPIO.output(DIO,1)
else:
GPIO.output(DIO,0)
nop()
GPIO.output(SCLK,1)
nop()
date >>= 1
26
www.keyestudio.com
GPIO.output(SCLK,0)
def end():
GPIO.output(SCLK,0)
nop()
GPIO.output(DIO,0)
nop()
GPIO.output(SCLK,1)
nop()
GPIO.output(DIO,1)
nop()
def matrix_display(matrix_value):
start()
send_date(0xc0)
for i in range(0,16):
send_date(matrix_value[i])
end()
start()
send_date(0x8A)
end()
try:
while True:
matrix_display(smile)
time.sleep(1)
matrix_display(matrix_back)
time.sleep(1)
matrix_display(matrix_forward)
time.sleep(1)
matrix_display(matrix_left)
time.sleep(1)
matrix_display(matrix_right)
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
27
www.keyestudio.com
cd /home/pi/RaspberryPi-Car/basic_project
After running the code, the dot matrix shows a smile image and a
direction pattern.
6. OLED Display
OLED display is the most commonly used for mobile phone. It features
the fine image quality, small size and high brightness. The size of our
OLED display is 0.96 inches, and the driving chip is SSD1306. It adopts IIC
6.1 Code
import time
28
www.keyestudio.com
import subprocess
# Initialize library.
disp.begin()
# Clear display.
disp.clear()
disp.display()
29
www.keyestudio.com
# Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
# font = ImageFont.truetype('Minecraftia.ttf', 8)
while True:
# Display image.
disp.image(image)
disp.display()
time.sleep(.1)
cd /home/pi/RaspberryPi-Car/basic_project/OledModule
30
www.keyestudio.com
After running the code, the OLED display shows the IP address, CPU,
6.3 Code2
import time
import time
GPIO.setmode(GPIO.BCM)
import Adafruit_SSD1306
GPIO_TRIGGER = 14
GPIO_ECHO = 4
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
GPIO.output(GPIO_TRIGGER, GPIO.HIGH)
time.sleep(0.00001) #10us
GPIO.output(GPIO_TRIGGER, GPIO.LOW)
pass
31
www.keyestudio.com
t1 = time.time()
while GPIO.input(GPIO_ECHO):
pass
t2 = time.time()
time.sleep(0.01)
import subprocess
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
# Initialize library.
disp.begin()
# Clear display.
disp.clear()
disp.display()
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
draw = ImageDraw.Draw(image)
32
www.keyestudio.com
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x=0
font = ImageFont.load_default()
# Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script!
# font = ImageFont.truetype('Minecraftia.ttf', 8)
while True:
# Display image.
disp.image(image)
disp.display()
time.sleep(.1)
33
www.keyestudio.com
cd /home/pi/RaspberryPi-Car/basic_project/OledModule
sudo python3 bp6_2oled_ultrasonic.py
After running the code, the terminal will print out the distance measured
by the ultrasonic sensor, and the value measured by ultrasound will also
7. Driver Motor
We use two TB6612 motor driver chips to drive four motors, that is to say,
34
www.keyestudio.com
7.1 Schematic Diagram
7.2 Code
# Control M2 motor
L_IN1 = 20
L_IN2 = 21
L_PWM1 = 0
# Control M1 motor
L_IN3 = 22
L_IN4 = 23
L_PWM2 = 1
# Control M3 motor
R_IN1 = 24
R_IN2 = 25
R_PWM1 = 12
# Control M4 motor
R_IN3 = 26
R_IN4 = 27
35
www.keyestudio.com
R_PWM2 = 13
GPIO.setup(L_IN3,GPIO.OUT)
GPIO.setup(L_IN4,GPIO.OUT)
GPIO.setup(L_PWM2,GPIO.OUT)
GPIO.setup(R_IN1,GPIO.OUT)
GPIO.setup(R_IN2,GPIO.OUT)
GPIO.setup(R_PWM1,GPIO.OUT)
GPIO.setup(R_IN3,GPIO.OUT)
GPIO.setup(R_IN4,GPIO.OUT)
GPIO.setup(R_PWM2,GPIO.OUT)
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.LOW)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.LOW)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.LOW)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.LOW)
36
www.keyestudio.com
while True:
GPIO.output(L_IN1,GPIO.LOW) #Upper Left forward
GPIO.output(L_IN2,GPIO.HIGH)
pwm_L1.ChangeDutyCycle(50)
GPIO.output(L_IN3,GPIO.HIGH) #Lower left forward
GPIO.output(L_IN4,GPIO.LOW)
pwm_L2.ChangeDutyCycle(50)
GPIO.output(R_IN1,GPIO.HIGH) #Upper Right forward
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(50)
GPIO.output(R_IN3,GPIO.LOW) #Lower Right forward
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(50)
#stop pwm
pwm_R1.stop()
pwm_L1.stop()
pwm_R2.stop()
pwm_L2.stop()
sleep(1)
Note: Run the code and the car will go forward. If you connect the power
and network cables, remember to lift the car first before running it so as
cd /home/pi/RaspberryPi-Car/basic_project
37
www.keyestudio.com
8. Infrared Receiver
NEC Protocol:
and inverse.
38
www.keyestudio.com
The inverse code is used to verify and improve the accuracy of keys value.
The four bytes of data bits are each sent least significant bit first. Figure 1
The NEC protocol uses pulse distance encoding of the bits. Each pulse is a
562.5µs long 38kHz carrier burst (about 21 cycles). A logical "1" takes
2.25ms to transmit, while a logical "0" is only half of that, being 1.125ms.
39
www.keyestudio.com
8.1 Code
PIN = 15;
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN,GPIO.IN,GPIO.PUD_UP)
print("irm test start...")
def exec_cmd(key_val):
if(key_val==0x46):
print("Button up")
elif(key_val==0x44):
print("Button left")
elif(key_val==0x40):
print("Button ok")
elif(key_val==0x43):
print("Button right")
elif(key_val==0x15):
print("Button down")
elif(key_val==0x16):
print("Button 1")
elif(key_val==0x19):
print("Button 2")
elif(key_val==0x0d):
print("Button 3")
elif(key_val==0x0c):
print("Button 4")
elif(key_val==0x18):
40
www.keyestudio.com
print("Button 5")
elif(key_val==0x5e):
print("Button 6")
elif(key_val==0x08):
print("Button 7")
elif(key_val==0x1c):
print("Button 8")
elif(key_val==0x5a):
print("Button 9")
elif(key_val==0x42):
print("Button *")
elif(key_val==0x52):
print("Button 0")
elif(key_val==0x4a):
print("Button #")
try:
while True:
if GPIO.input(PIN) == 0:
count = 0
while GPIO.input(PIN) == 0 and count < 200: # Wait for 9ms LOW level boot
code and exit the loop if it exceeds 1.2ms
count += 1
time.sleep(0.00006)
count = 0
while GPIO.input(PIN) == 1 and count < 80: # Wait for a 4.5ms HIGH level
boot code and exit the loop if it exceeds 0.48ms
count += 1
time.sleep(0.00006)
41
www.keyestudio.com
time.sleep(0.00006)
count = 0
while GPIO.input(PIN) == 1 and count < 40: # waits for logical HIGH level
to pass and exits the loop if it exceeds 2.4ms
count += 1
time.sleep(0.00006)
cd /home/pi/RaspberryPi-Car/basic_project
42
www.keyestudio.com
After running the code, point at infrared receiver module with the infrared
remote control and press keys. The terminal will print out the received
We have learned motor drivers, 8*16 dot matrix and infrared remote
9.1 Code
PIN = 15;
SCLK = 8
DIO = 9
# Display pattern data
matrix_smile = (0x00, 0x00, 0x38, 0x40, 0x40, 0x40, 0x3a, 0x02, 0x02, 0x3a, 0x40, 0x40, 0x40, 0x38,
0x00, 0x00)
matrix_forward = (0x00, 0x00, 0x00, 0x00, 0x12, 0x24, 0x48, 0x90, 0x90, 0x48, 0x24, 0x12, 0x00,
0x00, 0x00, 0x00)
matrix_back = (0x00, 0x00, 0x00, 0x00, 0x48, 0x24, 0x12, 0x09, 0x09, 0x12, 0x24, 0x48, 0x00, 0x00,
0x00, 0x00)
43
www.keyestudio.com
matrix_left = (0x00, 0x00, 0x00, 0x00, 0x18, 0x24, 0x42, 0x99, 0x24, 0x42, 0x81, 0x00, 0x00, 0x00,
0x00, 0x00)
matrix_right = (0x00, 0x00, 0x00, 0x00, 0x00, 0x81, 0x42, 0x24, 0x99, 0x42, 0x24, 0x18, 0x00, 0x00,
0x00, 0x00)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(SCLK,GPIO.OUT)
GPIO.setup(DIO,GPIO.OUT)
44
www.keyestudio.com
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.LOW)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.LOW)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.LOW)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.LOW)
def nop():
time.sleep(0.000001)
def nop2():
time.sleep(0.01)
def start():
GPIO.output(SCLK,1)
nop()
GPIO.output(DIO,1)
nop()
GPIO.output(DIO,0)
nop()
GPIO.output(SCLK,0)
def send_date(date):
for i in range(0,8):
GPIO.output(SCLK,0)
nop()
if date & 0x01:
GPIO.output(DIO,1)
else:
45
www.keyestudio.com
GPIO.output(DIO,0)
nop()
GPIO.output(SCLK,1)
nop()
date >>= 1
GPIO.output(SCLK,0)
def end():
GPIO.output(SCLK,0)
nop()
GPIO.output(DIO,0)
nop()
GPIO.output(SCLK,1)
nop()
GPIO.output(DIO,1)
nop()
def matrix_display(matrix_value):
start()
send_date(0xc0)
for i in range(0,16):
send_date(matrix_value[i])
end()
start()
send_date(0x8A)
end()
def exec_cmd(key_val):
if(key_val==0x46):
print("Button up")
matrix_display(matrix_forward)
GPIO.output(L_IN1,GPIO.LOW) #Upper Left forward
GPIO.output(L_IN2,GPIO.HIGH)
pwm_L1.ChangeDutyCycle(50)
GPIO.output(L_IN3,GPIO.HIGH) #Lower left forward
GPIO.output(L_IN4,GPIO.LOW)
pwm_L2.ChangeDutyCycle(50)
GPIO.output(R_IN1,GPIO.HIGH) #Upper Right forward
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(50)
GPIO.output(R_IN3,GPIO.LOW) #Lower Right forward
46
www.keyestudio.com
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(50)
elif(key_val==0x44):
print("Button left")
matrix_display(matrix_left)
GPIO.output(L_IN1,GPIO.HIGH)
GPIO.output(L_IN2,GPIO.LOW)
pwm_L1.ChangeDutyCycle(100)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.HIGH)
pwm_L2.ChangeDutyCycle(100)
GPIO.output(R_IN1,GPIO.HIGH) #Upper Right forward
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(100)
GPIO.output(R_IN3,GPIO.LOW) #Lower Right forward
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(100)
elif(key_val==0x40):
print("Button ok")
matrix_display(matrix_smile)
pwm_L1.ChangeDutyCycle(0)
pwm_L2.ChangeDutyCycle(0)
pwm_R1.ChangeDutyCycle(0)
pwm_R2.ChangeDutyCycle(0)
elif(key_val==0x43):
print("Button right")
matrix_display(matrix_right)
GPIO.output(L_IN1,GPIO.LOW) #Upper Left forward
GPIO.output(L_IN2,GPIO.HIGH)
pwm_L1.ChangeDutyCycle(100)
GPIO.output(L_IN3,GPIO.HIGH) #Lower left forward
GPIO.output(L_IN4,GPIO.LOW)
pwm_L2.ChangeDutyCycle(100)
GPIO.output(R_IN1,GPIO.LOW) #Upper Right forward
GPIO.output(R_IN2,GPIO.HIGH)
pwm_R1.ChangeDutyCycle(100)
GPIO.output(R_IN3,GPIO.HIGH) #Lower Right forward
GPIO.output(R_IN4,GPIO.LOW)
pwm_R2.ChangeDutyCycle(100)
elif(key_val==0x15):
print("Button down")
matrix_display(matrix_back)
GPIO.output(L_IN1,GPIO.HIGH)
47
www.keyestudio.com
GPIO.output(L_IN2,GPIO.LOW)
pwm_L1.ChangeDutyCycle(50)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.HIGH)
pwm_L2.ChangeDutyCycle(50)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.HIGH)
pwm_R1.ChangeDutyCycle(50)
GPIO.output(R_IN3,GPIO.HIGH)
GPIO.output(R_IN4,GPIO.LOW)
pwm_R2.ChangeDutyCycle(50)
elif(key_val==0x16):
print("Button 1")
elif(key_val==0x19):
print("Button 2")
elif(key_val==0x0d):
print("Button 3")
elif(key_val==0x0c):
print("Button 4")
elif(key_val==0x18):
print("Button 5")
elif(key_val==0x5e):
print("Button 6")
elif(key_val==0x08):
print("Button 7")
elif(key_val==0x1c):
print("Button 8")
elif(key_val==0x5a):
print("Button 9")
elif(key_val==0x42):
print("Button *")
elif(key_val==0x52):
print("Button 0")
elif(key_val==0x4a):
print("Button #")
try:
while True:
if GPIO.input(PIN) == 0:
count = 0
while GPIO.input(PIN) == 0 and count < 200: # Wait for 9ms LOW level boot code and exit
the loop if it exceeds 1.2ms
count += 1
48
www.keyestudio.com
time.sleep(0.00006)
count = 0
while GPIO.input(PIN) == 1 and count < 80: # Wait for a 4.5ms HIGH level boot code and
exit the loop if it exceeds 0.48ms
count += 1
time.sleep(0.00006)
count = 0
while GPIO.input(PIN) == 1 and count < 40: # waits for logical HIGH level to pass and
exits the loop if it exceeds 2.4ms
count += 1
time.sleep(0.00006)
# if count>8, that is, the logical time is greater than 0.54+0.562=1.12ms, that is,
#the period is greater than the logical 0 period, that is equivalent to receiving logical 1
if count > 8:
data[idx] |= 1<<cnt #When idx=0 is the first data data[idx] = data[idx] | 1<<cnt
00000001 <<1 == 0000 0010
if cnt == 7: #With 8 byte
cnt = 0 #Displacement qing 0
idx += 1 #Store the next data
else:
cnt += 1 #The shift adds 1
#Determine whether address code + address inverse code =0xff, control code + control
inverse code = 0xFF
if data[0]+data[1] == 0xFF and data[2]+data[3] == 0xFF:
print("Get the key: 0x%02x" %data[2]) #Data [2] is the control code we need
exec_cmd(data[2])
49
www.keyestudio.com
except KeyboardInterrupt:
GPIO.cleanup()
cd /home/pi/RaspberryPi-Car/basic_project
sudo python3 bp9_ir_car.py
After running test code, press the keys of the remote control,then the car
will move and the dot matrix will show the corresponding patterns.
The three-channel line tracking sensor has three sensor. When it detects
The middle sensor detects black lines: the car will go forward.
Left sensor detects black lines and right one doesn’t detect black lines;
The left one doesn’t detect black lines, the right one detects ones ;the
Neither left one nor right one detects black lines;the car will stop
50
www.keyestudio.com
10.1 Code
# Control M2 motor
L_IN1 = 20
L_IN2 = 21
L_PWM1 = 0
# Control M1 motor
L_IN3 = 22
51
www.keyestudio.com
L_IN4 = 23
L_PWM2 = 1
# Control M3 motor
R_IN1 = 24
R_IN2 = 25
R_PWM1 = 12
# Control M4 motor
R_IN3 = 26
R_IN4 = 27
R_PWM2 = 13
#tracking pin
trackingPin1 = 17
trackingPin2 = 18
trackingPin3 = 19
GPIO.setup(L_IN3,GPIO.OUT)
GPIO.setup(L_IN4,GPIO.OUT)
GPIO.setup(L_PWM2,GPIO.OUT)
GPIO.setup(R_IN1,GPIO.OUT)
GPIO.setup(R_IN2,GPIO.OUT)
GPIO.setup(R_PWM1,GPIO.OUT)
GPIO.setup(R_IN3,GPIO.OUT)
GPIO.setup(R_IN4,GPIO.OUT)
GPIO.setup(R_PWM2,GPIO.OUT)
52
www.keyestudio.com
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.LOW)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.LOW)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.LOW)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.LOW)
53
www.keyestudio.com
GPIO.output(L_IN1,GPIO.HIGH)
GPIO.output(L_IN2,GPIO.LOW)
pwm_L1.ChangeDutyCycle(50)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.HIGH)
pwm_L2.ChangeDutyCycle(50)
GPIO.output(R_IN1,GPIO.HIGH)
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(50)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(50)
# car right
def car_right():
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.HIGH)
pwm_L1.ChangeDutyCycle(50)
GPIO.output(L_IN3,GPIO.HIGH)
GPIO.output(L_IN4,GPIO.LOW)
pwm_L2.ChangeDutyCycle(50)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.HIGH)
pwm_R1.ChangeDutyCycle(50)
GPIO.output(R_IN3,GPIO.HIGH)
GPIO.output(R_IN4,GPIO.LOW)
pwm_R2.ChangeDutyCycle(50)
# car stop
def car_stop():
pwm_L1.ChangeDutyCycle(0)
pwm_L2.ChangeDutyCycle(0)
pwm_R1.ChangeDutyCycle(0)
pwm_R2.ChangeDutyCycle(0)
while True:
val1 = GPIO.input(trackingPin1) # read the value
val2 = GPIO.input(trackingPin2)
val3 = GPIO.input(trackingPin3)
54
www.keyestudio.com
if(val2 == 1):
car_forward()
print("forward")
else:
if((val1 == 1) and (val3 == 0)):
car_right()
print("right")
elif((val1 == 0) and (val3 == 1)):
car_left()
print("left")
else:
car_stop()
print("stop")
#stop pwm
pwm_R1.stop()
pwm_L1.stop()
pwm_R2.stop()
pwm_L2.stop()
sleep(1)
cd /home/pi/RaspberryPi-Car/basic_project
sudo python3 bp10_tracking_car.py
Run the code and plug in power and place it on a tracking map,then the
55
www.keyestudio.com
Gauge distance by the ultrasonic detection, make car follow the object to
go forward or backward.
<10 Go back
>50 stop
11.1 Code
56
www.keyestudio.com
# Control M2 motor
L_IN1 = 20
L_IN2 = 21
L_PWM1 = 0
# Control M1 motor
L_IN3 = 22
L_IN4 = 23
L_PWM2 = 1
# Control M3 motor
R_IN1 = 24
R_IN2 = 25
R_PWM1 = 12
# Control M4 motor
R_IN3 = 26
R_IN4 = 27
R_PWM2 = 13
57
www.keyestudio.com
GPIO.setup(L_IN2,GPIO.OUT)
GPIO.setup(L_PWM1,GPIO.OUT)
GPIO.setup(L_IN3,GPIO.OUT)
GPIO.setup(L_IN4,GPIO.OUT)
GPIO.setup(L_PWM2,GPIO.OUT)
GPIO.setup(R_IN1,GPIO.OUT)
GPIO.setup(R_IN2,GPIO.OUT)
GPIO.setup(R_PWM1,GPIO.OUT)
GPIO.setup(R_IN3,GPIO.OUT)
GPIO.setup(R_IN4,GPIO.OUT)
GPIO.setup(R_PWM2,GPIO.OUT)
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.LOW)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.LOW)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.LOW)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.LOW)
58
www.keyestudio.com
GPIO.output(L_IN3,GPIO.HIGH)
GPIO.output(L_IN4,GPIO.LOW)
pwm_L2.ChangeDutyCycle(30)
GPIO.output(R_IN1,GPIO.HIGH)
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(30)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(30)
# car back
def car_back():
GPIO.output(L_IN1,GPIO.HIGH)
GPIO.output(L_IN2,GPIO.LOW)
pwm_L1.ChangeDutyCycle(30)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.HIGH)
pwm_L2.ChangeDutyCycle(30)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.HIGH)
pwm_R1.ChangeDutyCycle(30)
GPIO.output(R_IN3,GPIO.HIGH)
GPIO.output(R_IN4,GPIO.LOW)
pwm_R2.ChangeDutyCycle(30)
# car stop
def car_stop():
pwm_L1.ChangeDutyCycle(0)
pwm_L2.ChangeDutyCycle(0)
pwm_R1.ChangeDutyCycle(0)
pwm_R2.ChangeDutyCycle(0)
while True:
dist = distance()
print("Measured Distance = {:.2f} cm".format(dist))
#time.sleep(0.02)
if dist < 10:
time.sleep(0.15)
car_back()
elif (dist>=10 and dist<=14):
59
www.keyestudio.com
car_stop()
time.sleep(0.1)
elif (dist>14 and dist<= 50):
time.sleep(0.15)
car_forward()
else:
car_stop()
print("stop")
#stop pwm
pwm_R1.stop()
pwm_L1.stop()
pwm_R2.stop()
pwm_L2.stop()
sleep(1)
cd /home/pi/RaspberryPi-Car/basic_project
sudo python3 bp11_follow_car.py
Run test code and plug in power. Put your hand before the car, then it will
60
www.keyestudio.com
obstacle.
Principle:
If the obstacle is away from more than 15cm, the car will go forward
If the obstacle is less than or equal to 15cm, the servo will rotate to left
and record the distance value away form an obstacle, then rotate to right
and record the distance value away from an obstacle. Next, compare
these two values, if left one is greater than the right one,the car will turn
Logic Chart:
Detected
Left distance Right distance
distance Compare values Status
value value
value
>15cm - - - Go
61
www.keyestudio.com
forward
12.1 Code
servoPin1 = 5
GPIO.setup(servoPin1, GPIO.OUT)
def servoPulse(servoPin, myangle):
pulsewidth = (myangle*11) + 500 # The pulse width
GPIO.output(servoPin,GPIO.HIGH)
time.sleep(pulsewidth/1000000.0)
GPIO.output(servoPin,GPIO.LOW)
time.sleep(20.0/1000 - pulsewidth/1000000.0) # The cycle of 20 ms
62
www.keyestudio.com
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
# 10us is the trigger signal
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001) #10us
GPIO.output(GPIO_TRIGGER, False)
start_time = time.time() # Log the time the program runs to this point
stop_time = time.time() # Log the time the program runs to this point
while GPIO.input(GPIO_ECHO) == 0: #Indicates that the ultrasonic wave has been emitted
start_time = time.time() #Record launch time
while GPIO.input(GPIO_ECHO) == 1: #Indicates that the returned ultrasound has been received
stop_time = time.time() #Record receiving time
time_elapsed = stop_time - start_time #Time difference from transmit to receive
distance = (time_elapsed * 34000) / 2 #Calculate the distance
return distance #Return to calculated distance
# Control M2 motor
L_IN1 = 20
L_IN2 = 21
L_PWM1 = 0
# Control M1 motor
L_IN3 = 22
L_IN4 = 23
L_PWM2 = 1
# Control M3 motor
R_IN1 = 24
R_IN2 = 25
R_PWM1 = 12
# Control M4 motor
R_IN3 = 26
R_IN4 = 27
R_PWM2 = 13
63
www.keyestudio.com
GPIO.setup(L_IN4,GPIO.OUT)
GPIO.setup(L_PWM2,GPIO.OUT)
GPIO.setup(R_IN1,GPIO.OUT)
GPIO.setup(R_IN2,GPIO.OUT)
GPIO.setup(R_PWM1,GPIO.OUT)
GPIO.setup(R_IN3,GPIO.OUT)
GPIO.setup(R_IN4,GPIO.OUT)
GPIO.setup(R_PWM2,GPIO.OUT)
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.LOW)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.LOW)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.LOW)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.LOW)
64
www.keyestudio.com
GPIO.output(R_IN1,GPIO.HIGH)
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(40)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(40)
# car left
def car_left():
GPIO.output(L_IN1,GPIO.HIGH)
GPIO.output(L_IN2,GPIO.LOW)
pwm_L1.ChangeDutyCycle(80)
GPIO.output(L_IN3,GPIO.LOW)
GPIO.output(L_IN4,GPIO.HIGH)
pwm_L2.ChangeDutyCycle(80)
GPIO.output(R_IN1,GPIO.HIGH)
GPIO.output(R_IN2,GPIO.LOW)
pwm_R1.ChangeDutyCycle(80)
GPIO.output(R_IN3,GPIO.LOW)
GPIO.output(R_IN4,GPIO.HIGH)
pwm_R2.ChangeDutyCycle(80)
# car right
def car_right():
GPIO.output(L_IN1,GPIO.LOW)
GPIO.output(L_IN2,GPIO.HIGH)
pwm_L1.ChangeDutyCycle(80)
GPIO.output(L_IN3,GPIO.HIGH)
GPIO.output(L_IN4,GPIO.LOW)
pwm_L2.ChangeDutyCycle(80)
GPIO.output(R_IN1,GPIO.LOW)
GPIO.output(R_IN2,GPIO.HIGH)
pwm_R1.ChangeDutyCycle(80)
GPIO.output(R_IN3,GPIO.HIGH)
GPIO.output(R_IN4,GPIO.LOW)
pwm_R2.ChangeDutyCycle(80)
# car stop
def car_stop():
pwm_L1.ChangeDutyCycle(0)
65
www.keyestudio.com
pwm_L2.ChangeDutyCycle(0)
pwm_R1.ChangeDutyCycle(0)
pwm_R2.ChangeDutyCycle(0)
# Loop several times to make sure the steering gear is turned to the specified Angle
# The initialization Angle is 90 degrees
for g in range(0, 50):
servoPulse(servoPin1, 90)
while True:
dist = distance()
print("Measured Distance = {:.2f} cm".format(dist))
time.sleep(0.01)
if dist > 15: # If the obstacle in front is larger than 15cm
car_forward()
else: # If the obstacle in front is less than 15cm
dist = distance()
if dist <= 15: # Make sure the obstacle in front is less than 15cm
car_stop()
# Loop several times to make sure the steering gear is turned to the specified Angle
for i in range(0, 50):
servoPulse(servoPin1, 180)
time.sleep(0.1)
left_distance = distance() # Measure the distance to the left
time.sleep(0.2)
for j in range(0, 50):
servoPulse(servoPin1, 0)
time.sleep(0.1)
right_distance = distance() # Measure the distance to the right
time.sleep(0.2)
for k in range(0, 50):
servoPulse(servoPin1, 90)
time.sleep(0.3)
# Compare the distance between the left and right sides
if left_distance > right_distance:
car_left()
time.sleep(0.6)
#The car stops to prevent the sudden positive and
66
www.keyestudio.com
#negative rotation of the motor from causing the raspberry PI voltage and
#current too low malfunction
car_stop()
time.sleep(0.1)
else:
car_right()
time.sleep(0.6)
car_stop()
time.sleep(0.1)
#stop pwm
pwm_R1.stop()
pwm_L1.stop()
pwm_R2.stop()
pwm_L2.stop()
sleep(1)
cd /home/pi/RaspberryPi-Car/basic_project
sudo python3 bp12_avoid_car.py
Run test code and plug in power. The car will avoid the obstacle
67
www.keyestudio.com
68