0% found this document useful (0 votes)
319 views72 pages

Preface: About Sunfounder

Uploaded by

Razvan Lungu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
319 views72 pages

Preface: About Sunfounder

Uploaded by

Razvan Lungu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Preface

About SunFounder
SunFounder is a company focused on STEAM education with products like open source robots and smart
devices distributed globally. In SunFounder, we strive to help elementary and middle school students as
well as hobbyists, through STEAM education, strengthen their hands-on practices and problem-solving
abilities. In this way, we hope to disseminate knowledge and provide skill training in a full-of-joy way, thus
fostering your interest in programming and making, and exposing you to a fascinating world of science
and engineering. To embrace the future of artificial intelligence, it is urgent and meaningful to learn
abundant STEAM knowledge.

About This Kit


PiCar-4WD is a cost-effectively developmental smart car kit of Raspberry Pi, suitable for the Raspberry Pi 3
model B/B+ and 4 Model B. With the grayscale module, ultrasonic module, Photo-interrupter sensor
module, the car can realize obstacle avoidance, line following, object following, cliff detection, velocity
measurement, mileage calculation and so on.

Besides, the kits comes with operational examples of Web terminal, a rookie-friendly design. We also
provide the original python code for in-depth learning.
Quickly Support
Thanks for using the PiCar-4WD Smart Robot Car Kit for Raspberry Pi. You can contact us at the email
address below. Please don't hesitate to let us know if you need any support from us. We love helping our
customers to learn and play with our products.

If you have any TECHNICAL question, add a topic under FORUM section on our website and we'll
reply as soon as possible.

For NON-TECH questions like order and shipment issues, please send an email to
service@sunfounder.com. You're also welcomed to share your projects on FORUM.

Copyright Notice
All contents including but not limited to texts, images, and code in this manual are owned by the
SunFounder Company. You should only use it for personal study, investigation, enjoyment, or other
non-commercial or nonprofit purposes, under the related regulations and copyrights laws, without
infringing the legal rights of the author and relevant right holders. For any individual or organization that
uses these for commercial profit without permission, the Company reserves the right to take legal action.

V1.0.0 Mar. 2020


Warning
When you purchase or use this product, please note the following points:

 This product contains many small parts. Swallowing or improper operation may cause serious
infections and death. Seek immediate medical attention once the accident happens.

 Strictly prohibit use this product and its parts near any AC electrical outlet or other circuits in case of
the potential risk of electric shock.

 Strictly prohibit use this product near any liquid or fire. Keep conductive materials away from this
product.

 Do not allow children under 3 years old to use this product without adult supervision. Please place this
product in the position where children under 3 years old cannot reach.

 Do not store or use this product in any extreme environments such as extreme hot or cold, high
humidity and etc.

 Remember to break the circuit when it is not needed.

 Some parts of this product may become warm to touch when used in certain circuit designs, which is
normal.

 Using components not in accordance with the specification may cause damage to the product.
Contents
Component List......................................................................................................................................................................... 1
Structural Plates.................................................................................................................................................................1
Mechanical Parts............................................................................................................................................................... 2
Electronic Parts.................................................................................................................................................................. 3
Other Parts.......................................................................................................................................................................... 4
Driving Parts....................................................................................................................................................................... 6
Self- prepared Part............................................................................................................................................................6
Get Started with Raspberry Pi............................................................................................................................................... 7
If You Have A Screen........................................................................................................................................................ 8
Required Components.............................................................................................................................................8
Procedures.................................................................................................................................................................. 9
If You Have No Screen................................................................................................................................................... 20
Required Components.......................................................................................................................................... 20
Burn System..............................................................................................................................................................20
Connect the Raspberry Pi to the Internet........................................................................................................ 22
Start SSH................................................................................................................................................................... 23
Power on the Raspberry Pi................................................................................................................................... 23
Get the IP Address.................................................................................................................................................. 24
Use the SSH Remote Control.............................................................................................................................. 26
Download the Code............................................................................................................................................................... 30
Test the Modules.................................................................................................................................................................... 31
Initialize the Environment.............................................................................................................................................31
Module Testing................................................................................................................................................................ 33
Power Supply Detection............................................................................................................................................... 36
Reset Controller...............................................................................................................................................................36
Hardware Assembling........................................................................................................................................................... 37
Assembling Motor.......................................................................................................................................................... 37
Photo-interrupter Module + Encoding Disk........................................................................................................... 38
Assembling Grayscale Sensor Module......................................................................................................................39
Assembling Battery Holder.......................................................................................................................................... 40
Assembling Servo........................................................................................................................................................... 41
Assembling Nylon Standoffs....................................................................................................................................... 42
Assembling Top Plate and Bottom Plate.................................................................................................................. 43
Assembling Spoiler.........................................................................................................................................................44
Assembling Control Board........................................................................................................................................... 45
Connect Wires................................................................................................................................................................. 46
Assembling Radar Support.......................................................................................................................................... 47
Assembling Ultrasonic Sensor Module.....................................................................................................................48
Assembling Wheels(finished)...................................................................................................................................... 49
Web Control............................................................................................................................................................................. 50
Boot Web Control........................................................................................................................................................... 50
Setting Page..................................................................................................................................................................... 53
Python Program Control....................................................................................................................................................... 60
Python Example Program............................................................................................................................................. 60
Python Example Code Analysis................................................................................................................................... 62
Component List
Structural Plates

1
Mechanical Parts

2
Electronic Parts

3
Other Parts

4
5
Driving Parts

Self- prepared Part

Note: After opening the package, please check whether the


quantity of components is compliance with product
description and whether all components are in good
condition.

6
Get Started with Raspberry Pi
Before you complete the assembly, you
need to test whether all the modules work
properly and keep the servo angle at 90
degrees. In this chapter, configure your
Raspberry Pi first.

For the Raspbian system, You are


recommend to install the version :
Raspbian Buster with desktop and
recommended software.

If you have installed the other two versions, you need to install the following softwares manually and then
skip this chapter.

sudo apt-get update


sudo apt-get install git-core
sudo apt-get install python3-pip
sudo pip3 install setuptools
If you are a beginner for Raspberry Pi, please follow this chapter to let your Raspberry Pi work.

7
Depending on the different devices you use, you can start up the Raspberry Pi in different methods. If you
have a separate screen for Raspberry Pi, follow the instructions in this chapter. Otherwise, please find the
corresponding steps in the following chapters.

If You Have A Screen

If you have a screen, you can use the NOOBS (New Out Of Box System) to install the Raspbian system.

Required Components

Any Raspberry Pi 1 * 2.5A Power Adapter

1 * Monitor 1 * Monitor Power Adapter

1 * HDMI cable 1 * Micro SD card

1 * Mouse 1 * Keyboard

1 * Personal Computer

8
Procedures

Step 1

To download NOOBS from your PC, you can choose NOOBS or NOOBS LITE - the only difference is that
there is a built-in offline Raspbian installer in NOOBS, while the NOOBS LITE can only be operated online.
Here, you are suggested to use the former. Here is the download address of Noobs:

https://www.raspberrypi.org/downloads/noobs/

Step 2

Plug in the Micro SD reader and format the Micro SD card with the SD Formatter
(https://www.sdcard.org/downloads/formatter/index.html). If there are some important files in the Micro
SD card, please backup them first.

9
Step 3

Next, you will need to extract the files from the NOOBS zip archive you downloaded from the Raspberry Pi
website.

 Find the downloaded archive — by default, it should be in your Downloads folder.

 Double-click on it to extract the files, and keep the resulting Explorer/Finder window open.

Finally select all the files in the NOOBS folder and copy them to the Micro SD card.

Step 4

All the files transferred, the Micro SD card pops up.

10
Step 5

Insert the Micro SD card into the Raspberry Pi. In addition, connect the screen, keyboard and mouse to it.
Finally switch on the 4WD-Hat board. Due to the long test time, you can also plug a 2.5A power adapter
into the Raspberry Pi.

Switch On/Off

11
Step 6

It will go to the NOOBS interface after starting up. If you use NOOBS LITE, you need to select Wi-Fi
networks (w) first. Tick the checkbox of the Raspbian and click Install in the top left corner. The NOOBS will
help to conduct the installation automatically. This process will take a few minutes.

12
Step 7

When the installation is done, the system will restart automatically and the desktop of the system will
appear.

13
Step 8

If you run Raspberry Pi for the first time, the application of “Welcome to Raspberry Pi” pops up and guides
you to perform the initial setup.

14
Step 9

Set country/region, language and time zone, and then click “next” again.

15
Step 10

Input the new password of Raspberry Pi and click “Next”.

16
Step 11

Connect the Raspberry Pi to WIFI and click "Next".

17
Step 12

Retrieve update.

18
Step 13

Click "Done" to complete the Settings.

Now we can run the Raspberry Pi.

Note: You can check the complete tutorial of NOOBS on the official website of the Raspberry
Pi: https://www.raspberrypi.org/help/noobs-setup/.

19
If You Have No Screen

If we don't have a screen, we can directly write the Raspbian system to the Micro SD card and we can
control the Raspberry Pi on PC remotely by directly modifying the configuration file of the network
settings in the Micro SD card.

Required Components

Any Raspberry Pi 1 * 2.5A Power Adapter

1 * Micro SD card 1 * Personal computer

Burn System
Step 1
Prepare the tool of image burning. Here we use the balenaEtcher. You can download the software from
the link: https://www.balena.io/etcher/

Step 2
Download the complete image on the official website by clicking this link:
https://www.raspberrypi.org/downloads/raspbian/. There are three different kinds of Raspbian system
available, You are recommend to install the version:Raspbian Buster with desktop and recommended
software.

20
Step 3
Unzip the package downloaded and you will see the .img file inside.

Note: DO NOT extract the file.

Step 4
Plug the USB Card Reader into the computer, then you can burn the image file with the Etcher.

At this point, Raspbian is installed. Keep the USB card reader plug in your computer. If you want to apply
it, next you need to complete the settings accordingly.

21
Connect the Raspberry Pi to the Internet
There are two methods to help get the Raspberry Pi connected to the network: the first one is using a
network cable, the other way is using WIFI. We will talk in detail about how to connect via WIFI as below.

If you want to use the WIFI function, you need to modify a WIFI configuration file wpa-supplicant.conf in
the Micro SD card by your PC that is located in the directory /etc/wpa-supplicant/.

If your personal computer is working on a linux system, you can access the directory directly to modify the
configuration file; however, if your PC use Windows system, then you can't access the directory and what
you need next is to go to the directory, /boot/ to create a new file with the same name, wpa-supplicant.
conf.

Input the following content in the file.

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={
ssid="WiFi-A"
psk="Sunfounder"
key_mgmt=WPA-PSK
priority=1
}

22
You need to replace “WiFi-A” with your custom name of WiFi and “Sunfounder” with your password. By
doing these, the Raspbian system will move this file to the target directory automatically to overwrite the
original WIFI configuration file when it runs next time. After doing this step, you also need to keep the USB
card reader plug in your computer.

Start SSH
To use the function of remote control of the Raspberry Pi, you need to start SSH firstly that is a more
reliable protocol providing security for remote login sessions and other network services. Generally, SSH of
Raspberry Pi is in a disabled state. Additionally, if you want to run it, you need to create a file named SSH
under directory /boot/.

Now, the Raspbian system is configured.

Power on the Raspberry Pi


You can plug out the USB card reader and then plug the Micro SD card into the Raspberry Pi. Finally
switch on the 4WD-Hat board. Due to the long test time, you can also plug a 2.5A power adapter into the
Raspberry Pi.

23
Switch On/Off

Get the IP Address


After the Raspberry Pi is powered on with a 2.5A power adapter, we need to get the IP address of it. There
are many ways to know the IP address, and two of them are listed as follows.

1. Checking via the router

24
If you have permission to log in the router(such as a home network), you can check the addresses assigned
to Raspberry Pi on the admin interface of router.

The default hostname of the system, Raspbian is raspberrypi, and you need to find it. (If you are using
ArchLinuxARM system, please find alarmpi.)

2. Network Segment Scanning


You can also use network scanning to look up the IP address of Raspberry Pi. You can apply the software,
Advanced IP scanner(download from Google).

Click Scan and the name of all connected devices will be displayed. Similarly, the default hostname of the
Raspbian system is raspberrypi, now you need to find the hostname and its IP.

25
Use the SSH Remote Control
We can open the Bash Shell of Raspberry Pi by applying SSH. Bash is the standard default shell of Linux.
The Shell itself is a program written in C that is the bridge linking the customers and Unix/Linux. Moreover,
it can help to complete most of the work needed.

 For Linux or/Mac OS X Users

Step 1
Go to Applications->Utilities, find the Terminal, and open it.

Step 2
Type in ssh pi@ip_address . “pi”is your username and “ip_address” is your IP address. For example:

ssh pi@192.168.18.197

Step 3
Input”yes”.

26
Step 4
Input the passcode and the default password is raspberry.

Step 5
We now get the Raspberry Pi connected and are ready to go to the next step.

Note: When you input the password, the characters do not display on window accordingly, which is
normal. What you need is to input the correct passcode.

27
 For Windows Users
If you're a Windows user, you can use SSH with the application of some software. Here, we recommend
PuTTY.

Step 1
Download PuTTY. Open PuTTY and click Session on the left tree-alike structure. Enter the IP address of the
RPi in the text box under Host Name (or IP address) and 22 under Port (by default it is 22).

28
Step 2

Click Open. Note that when you first log in to the Raspberry Pi with the IP address, there prompts a
security reminder. Just click Yes.

Step 3
When the PuTTY window prompts “ login as: ” , type in “ pi ” (the user name of the RPi), and password:
“raspberry” (the default one, if you haven't changed it).

Step 4
Here, we get the Raspberry Pi connected and it is time to conduct the next steps.

Note: When you input the password, the characters do not display on window accordingly, which is normal.
What you need is to input the correct password.

29
Download the Code
The codes in the disk don’t need downloading, only for your fast study. If you need the latest codes, please
go to github to download as following methods.

① Change directory to /home/pi.

cd /home/pi/

Note: cd, short for change directory is to change from the current path to the intended directory.
Informally, here is to go to the path /home/pi/.

② Clone the repository from github.

git clone https://github.com/sunfounder/picar-4wd

30
Test the Modules
In case of anything wrong with the components, you can firstly debug them, then start your assembling
and use.

Initialize the Environment

Initialize the environment before using the product example. The methods are as follows.

① Assemble 4WD-Hat and boot the Raspberry Pi.

4WD-Hat

Raspberry Pi

31
Switch On/Off

② Enter the folder picar-4wd.

cd /home/pi/picar-4wd/

③ Start up the initialization function.

sudo python3 setup.py install

32
The main functions of setup.py may be:

A. Download and configure necessary library files, including pip, sysstat, i2c-tools.

B. Provide entry points called「picar-4wd」to call the function of example code.

Note: Initialization needs connecting to the internet and spending a lot of time. The final line will appear
「finish」after configuration is finished.

Module Testing

To make sure that the module works well, you can test the module by these means.

① Testing the motor of the car.

Wire up the motor according to the diagram.

33
Input the command.

picar-4wd test motor

After you input the command, the four motors will last working till you press on CTRL+C. Among the
motors, two of them rotate clockwise, and the rest of them rotate anticlockwise.

② Testing the grayscale sensor module.

Finishing the wire up according to the diagram.


Detector

34
Input the following command.

picar-4wd test grayscale

After you input the command, the monitor will print the readings of three detectors of line-following
module once.

③ Testing the servo and the ultrasonic module.

Start your wire up:

Servo Pin(0)
Brown -> Black
Red -> Red
Orange -> Yellow
Recognize the same

35
Input the commands:

picar-4wd test servo

The arm of servo will rotate to the angle of 0, meanwhile the monitor will print the readings of ultrasonic
module once.

Note: You need to boot this function to check the direction of servo’s output axis when you assemble the
car and the servo.

Power Supply Detection

You can use the following command to get the supply voltage.

picar-4wd power-read

The supply voltage ought to be 6V~8.5V to ensure that the car works well.

Reset Controller

If you encounter some errors during your use, for example, the car don’t make response to your control
command of control terminal, you can try to reset HATS by using the following command.

picar-4wd soft-reset

36
Hardware Assembling
Assembling Motor

Assemble 4 motor to the bottom plate.

M3*28mm Screw Note:

1) Keep the vertex angle of the triangle


sticking upward.
M3 Nut
2) For the convenience of later assembly,
Support
please mark the number(1, 2, 3, 4) on the
socket of the 4 motors.

1
4 Bottom Plate

37
Photo-interrupter Module + Encoding Disk

Insert the Encoding Disk into the motor, then assemble the Photo-interrupter module from bottom to top.

Note: Keep the Encoding Disk on the motor away from the Photo-interrupter module to avoid the
potential abrasion.

M3 Nut

Encoding Disk

Photo-interrupter Module

M3*8 Screw

38
Assembling Grayscale Sensor Module

Have the Grayscale sensor module be under the head of the car.

M3 Nut

Grayscale Sensor Module

M3*8 Screw

39
Assembling Battery Holder

Assemble the battery holder to the top plate and put the battery in.

Note: To get the battery out of the holder easily, you can wind the battery with ribbon like this.

18650 Batteries

M3*8 Flat-Head Screw

Top Plate
Battery Case
Ribbon

M3 Nut

40
Assembling Servo

Assemble the servo from bottom to top.

Note: the output axis is to face outwards.

M2*8 Screw

Top Plate

Servo

M2 Nut

41
Assembling Nylon Standoffs

M2.5*8+6mm Nylon Standoff

M2.5*6 Screw

42
Assembling Top Plate and Bottom Plate

M3*8 Screw

M3*30mm

Nylon Standoff

M3*8 Screw

43
Assembling Spoiler

Spoiler

44
Assembling Control Board

M2.5*6 Screw

4WD-Hat

M2.5*11mm

Nylon Standoff

Raspberry Pi

45
Connect Wires

Connect the modules properly with the guidance of the marks on the 4WD-Hat board.

Note:For good appearance, you need to make sure that all the wires go through the bottom plate of the
car to the HAT on the upper plate of the car.

46
Assembling Radar Support

Note: Assemble the servo arm only when the Raspberry Pi is energized and the command
「picar-4wd test servo」is running.

M1.5*4 Screw

Radar Support

Servo Screw

Servo Arm

47
Assembling Ultrasonic Sensor Module

M1.4 Nut

Ultrasonic Module

M1.4*8 Screw

48
Assembling Wheels(finished)

49
Web Control
In the kit, there are two control methods: Web control and Python program control.

In this chapter, we are provided with method of web control. So we can open the browser on different
devices, including computer, cellphone(Recommended), tablet and so on. You can use most functions of
Picar-4wd, such as obstacle avoidance, line-following, object following and voltage check.

Note: Check the next chapter if you want to use python to control Picar-4wd.

Boot Web Control

Input the command and start up the web control program.

cd /home/pi/picar-4wd/
picar-4wd web-example

As the program is running, on the browser, type the IP of the Raspberry Pi, and you can enter the Web
interface.

50
Interface Introduction

51
1. Arrow Key

2. Power Regulator

3. Obstacle Monitor: checking the obstacle ahead within 35cm and 180°. Red dot represents there is an
obstacle ahead detected by ultrasonic module.

4. Grayscale Monitor: displaying the color condition of the detected surface. If the module detects the
black lines and then the cliff, the different colors will display on the monitor.

5. Mileage

6. Speed Monitor

1 . Ultrasonic: turning on/off the obstacle monitor and the ultrasonic measurement function.

2 . Grayscale: turning on/off the grayscale monitor and the line following function.

3 . Avoid: turning on/off obstacle avoidance function can make the car get around the obstacles
automatically or not.

4 . Follow: turning on/off line following function can let the car follow the objects ahead or not.

5 . Cliff: turn on/off edge detection. The car retreats once it detects the cliff or not. If the car doesn’t realize
the effect, please adjust the threshold on the setting page.

6 . Path: to turn on/off line following function. Once you start up the line following function, the car will

52
drive along the black lines on the ground. If not, please adjust the threshold on the setting page.

7 . Setting: You can enter the Setting page by clicking this one.

Setting Page

Ultrasonic
This page is used to test whether the ultrasonic sensor works well. The slider below can be used to adjust
the current direction and angle of the ultrasonic sensor.

53
Wheels
You can test the working condition of the wheels on this page.

Click a wheel then set the POWER, click the two buttons in bottom right corner. When you press the button
at left, the wheel goes forward; press the button on the right, the wheel go backward. If the car doesn’t
follow your operation like that, you should adjust the direction. The methods are as follows:

1) Input the following command to open the configure file.

cd ..

54
ls -a
cd .picar-4wd/
nano config

2) In the configure file, the first 4 lines of codes are used to control the turning of the motor. The last line is
used to adjust the angle of the servo. For example, if in the above test, the direction of the motor at
bottom left is reverse, so we change the code in the third line to left_rear_reverse = True.

55
3) Rerun the following commands.

cd /home/pi/picar-4wd/
picar-4wd web-example

4) In the browser, click Retry, and you can test the direction of the wheel ready to be used.

56
Grayscale
On this page, you can adjust the threshold of the line following and cliff detection.

Line Reference

Put the Picar-4wd on the white surface and record these three values of Grayscale. Now the value of
Grayscale is large enough, about 1500. Then put the grayscale sensor module of Picar-4wd above the black
surface and record these three values of Grayscale. Now, the value of Grayscale gets relatively small, about
150 as is predicted. So we set the value of Line Reference to 400. Of course, you can change the value. Once
you finish doing this, you can see that the corresponding area turning into gray if the value of Grayscale is
larger than 400; if not so, turning into black.

Cliff Reference

Put the car at the edge of the desk with the car’s head sticking out from the desk. Record three values of
Grayscale, and now the value is relatively small, less than 100. Please set the value of Cliff Reference to 110.
When you finish doing this, the corresponding area appears red exclamation symbol if the value of
Grayscale is less than 110.

57
58
System
You can check the operating condition of the system on this page.

1 Make the example program run automatically at startup.

picar-4wd web-example enable

2 If you want to turn off the Start on Boot, please type in the following command.

picar-4wd web-example disable

59
Python Program Control
Python Example Program

Python Example Program is in the examples folder.

cd /home/pi/picar-4wd/examples

You can run them by using Python3.

 keyboard_control.py

After running the example, press「W」, 「A」, 「S」, 「D」, and you can get the car going ahead, back, left,
right. And the keys「4」and「6」can increase or decrease the power of the motor.

Run it by using the following command.

python3 keyboard_control.py

 obstacle_avoidance.py

After running the example, the car goes ahead automatically.

It can also turn right to get around the obstacles if there is anything obstructive ahead.

python3 obstacle_avoidance.py

60
 track_line.py

If you paste a black lane (width: around 2.5cm) on the white floor, the car will move along the lane.

python3 track_line.py

 follow.py

When the example runs, the car will follow the object ahead.

python3 follow.py

61
Python Example Code Analysis

Program Structure Framework

62
keyboard_control.py
In the code, we use readchar and readkey to get the input state of the key, then we assign some functions
to the keys by using if statement.

import picar_4wd as fc
import sys
import tty
import termios
import asyncio

power_val = 50
key = 'status'

def readchar():
……

def readkey(getchar_fn=None):
getchar = getchar_fn or readchar
……

def Keyborad_control():
while True:
global power_val
key=readkey()
if key=='6':
……
elif key=='4':
……
if key=='w':
……
elif key=='a':

63
……
elif key=='s':
……
elif key=='d':
……
else:
……
if key=='q':
print("quit")
break
if __name__ == '__main__':
Keyborad_control()

obstacle_avoidance.py
In the code, the distance measurement radar (ultrasonic + servo) will take sample for 11 times in total
(once every 18°). Then it makes judgement on the distance states of the fourth and the seventh sampling.
If radar indicates no obstacle(the returned value is 2), the car will continue moving ahead, or else the car
turn right to get around the obstacle.

Note: Check 「scan_step()」, 「get_status_at()」 in the 「_init_.py」for more details about the judgement
on radar sampling and distance state.

import picar_4wd as fc
speed = 30
def main():
while True:
scan_list = fc.scan_step(35)
if not scan_list:
continue

64
tmp = scan_list[3:7]
print(tmp)
if tmp != [2,2,2,2]:
fc.turn_right(speed)
else:
fc.forward(speed)

if __name__ == "__main__":
try:
main()
finally:
fc.stop()

track_line.py
In this code, grayscale sensor module will judge the gray level of the floor under the car’s head. The car
adjusts the directions according to the detection values of these three detectors to follow the black line.

Note: About Grayscale judgement, refer to 「get_line_status()」in 「_init_.py」for more details.

import picar_4wd as fc

Track_line_speed = 20

def Track_line():
gs_list = fc.get_grayscale_list()
if fc.get_line_status(400,gs_list) == 0:
fc.forward(Track_line_speed)
elif fc.get_line_status(400,gs_list) == -1:
fc.turn_left(Track_line_speed)
elif fc.get_line_status(400,gs_list) == 1:

65
fc.turn_right(Track_line_speed)

if __name__=='__main__':
while True:
Track_line()

follow.py
In the code, the ultrasonic module will take sample to form an array containing 11 elements; the module
detects once every 18 ° and puts the distance state (0 , 1 , 2) of every angle into the array. If there is
something obstructive at the right front, the detection value is [22222211122].

The array takes the 2 as a delimiter to divide the array anew. The examples above will be divided into
several null elements and a [111]- value element.

The corresponding angular range of the element with a value [111] is 108°~144° (0°+18°*6=108°, 0°+18°
*8=144°), and the car will turn its angle into a median 126°((144+108)/2)

Judge the distance, and keep the car away from the object about 10cm.

Note: Refer to 「scan_step()」and「get_status_at()」in 「_init_.py」to get more details about radar sampling
and the distance state judgement.

import picar_4wd as fc
speed = 30
def main():
while True:
scan_list = fc.scan_step(23)
if not scan_list:

66
continue
scan_list = [str(i) for i in scan_list]
scan_list = "".join(scan_list)
paths = scan_list.split("2")
length_list = []
for path in paths:
length_list.append(len(path))
if max(length_list) == 0:
fc.stop()
else:
i = length_list.index(max(length_list))
pos = scan_list.index(paths[i])
pos += (len(paths[i]) - 1) / 2
delta = len(scan_list) / 3
if pos < delta:
fc.turn_left(speed)
elif pos > 2 * delta:
fc.turn_right(speed)
else:
if scan_list[int(len(scan_list)/2-1)] == "0":
fc.backward(speed)
else:
fc.forward(speed)

if __name__ == "__main__":
try:
main()
finally:
fc.stop()

67

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy