0% found this document useful (0 votes)
19 views128 pages

Freenove Product Support and Safety Guide

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)
19 views128 pages

Freenove Product Support and Safety Guide

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

Welcome

Thank you for choosing Freenove products!

About Battery

First, read the document About_Battery.pdf in the unzipped folder.


If you did not download the zip file, please download it and unzip it via link below.
[Link]

Get Support and Offer Input

Freenove provides free and responsive product and technical support, including but not limited to:
 Product quality issues
 Product use and build issues
 Questions regarding the technology employed in our products for learning and education
 Your input and opinions are always welcome
 We also encourage your ideas and suggestions for new products and product improvements
For any of the above, you may send us an email to:

support@[Link]
Safety and Precautions

Please follow the following safety precautions when using or storing this product:
 Keep this product out of the reach of children under 6 years old.
 This product should be used only when there is adult supervision present as young children lack necessary
judgment regarding safety and the consequences of product misuse.
 This product contains small parts and parts, which are sharp. This product contains electrically conductive
parts. Use caution with electrically conductive parts near or around power supplies, batteries and
powered (live) circuits.
 When the product is turned ON, activated or tested, some parts will move or rotate. To avoid injuries to
hands and fingers, keep them away from any moving parts!
 It is possible that an improperly connected or shorted circuit may cause overheating. Should this happen,
immediately disconnect the power supply or remove the batteries and do not touch anything until it
cools down! When everything is safe and cool, review the product tutorial to identify the cause.
 Only operate the product in accordance with the instructions and guidelines of this tutorial, otherwise
parts may be damaged or you could be injured.
 Store the product in a cool dry place and avoid exposing the product to direct sunlight.
 After use, always turn the power OFF and remove or unplug the batteries before storing.
About Freenove

Freenove provides open source electronic products and services worldwide.

Freenove is committed to assist customers in their education of robotics, programming and electronic circuits
so that they may transform their creative ideas into prototypes and new and innovative products. To this end,
our services include but are not limited to:

 Educational and Entertaining Project Kits for Robots, Smart Cars and Drones
 Educational Kits to Learn Robotic Software Systems for Arduino, Raspberry Pi and micro: bit
 Electronic Component Assortments, Electronic Modules and Specialized Tools
 Product Development and Customization Services

You can find more about Freenove and get our latest news and updates through our website:

[Link]

Copyright

All the files, materials and instructional guides provided are released under Creative Commons Attribution-
NonCommercial-ShareAlike 3.0 Unported License. A copy of this license can be found in the folder containing
the Tutorial and software files associated with this product.

This means you can use these resource in your own derived works, in part or completely, but NOT for the
intent or purpose of commercial use.

Freenove brand and logo are copyright of Freenove Creative Technology Co., Ltd. and cannot be used without
written permission.


R

Free your innovation

Raspberry Pi® is a trademark of Raspberry Pi Foundation ([Link]

Need support?  [Link]


Contents

Welcome ............................................................................................................................................................................................... 1
Contents ................................................................................................................................................................................................ 1
List ........................................................................................................................................................................................................... 1
4WD Smart Car Board for Raspberry Pi ............................................................................................................................ 1
Machinery Parts ......................................................................................................................................................................... 2
Transmission Parts .................................................................................................................................................................... 3
Acrylic Parts ................................................................................................................................................................................. 3
Electronic Parts........................................................................................................................................................................... 4
Tools .............................................................................................................................................................................................. 4
Self-prepared Parts .................................................................................................................................................................. 5
Preface ................................................................................................................................................................................................... 6
Raspberry Pi Introduction....................................................................................................................................................... 7
Chapter 0 Raspberry Pi Preparation .......................................................................................................................................... 17
Install a System ........................................................................................................................................................................ 17
Remote desktop & VNC ....................................................................................................................................................... 26
Chapter 1 Software installation and Test (necessary) .......................................................................................................... 34
Step 1 Obtain the Code and Set python3 as Default ................................................................................................. 34
Step 2 Configuration .............................................................................................................................................................. 37
Step 3 Run the Libraries Installation Program ................................................................................................................. 40
Chapter 2 Assemble Smart Car ................................................................................................................................................... 41
Chapter 3 Module test (necessary)............................................................................................................................................. 55
Chapter 4 Light tracing Car........................................................................................................................................................... 80
Description ................................................................................................................................................................................ 80
Run program ............................................................................................................................................................................ 80
Chapter 5 Ultrasonic Obstacle Avoidance Car ....................................................................................................................... 82
Description ................................................................................................................................................................................ 82
Run program ............................................................................................................................................................................ 82
Chapter 6 Infrared Line Tracking Car ........................................................................................................................................ 84
Description ................................................................................................................................................................................ 84
Run program ............................................................................................................................................................................ 84
Chapter 7 Smart video car ............................................................................................................................................................ 87
Server .......................................................................................................................................................................................... 88
Client ........................................................................................................................................................................................... 94
Android and iOS app ...........................................................................................................................................................115
Free innovation ......................................................................................................................................................................117
What's next? .....................................................................................................................................................................................124
█ [Link] List 1

List
If you have any concerns, please feel free to contact us via support@[Link]

4WD Smart Car Board for Raspberry Pi

Need support?  [Link]


2 List [Link] █

Machinery Parts

Note: You may receive M1.4*4 or M1.4*5. Can be used normally

Need support?  [Link]


█ [Link] List 3

Transmission Parts

Servo package x2 Driven wheel x4

DC speed reduction motor x4 Motor bracket package x4

Acrylic Parts

For Pan Tilt

Need support?  [Link]


4 List [Link] █

Electronic Parts

Line tracking module x1 Camera x1 HC-SR04 Ultrasonic


Module x1

Connection board

Jumper Wire F/F(4) x1

XH-2.54-5Pin cable x1

Tools

Cross screwdriver (3mm) x1 Black tape x1 Cable Tidy x25cm

Need support?  [Link]


█ [Link] List 5

Self-prepared Parts

Please refer to About_Battery.pdf in unzipped folder.

Raspberry Pi (Recommended model: Raspberry 4B / 3B+ / 3B) x1

Need support?  [Link]


6 Preface [Link] █

Preface
Welcome to use Freenove 4WD Smart Car Kit for Raspberry Pi. Following this tutorial, you can make a very
cool smart car with many functions.

This kit is based on Pi Raspberry, a popular control panel, so you can share and exchange your experience
and design ideas with many enthusiasts all over the world. The parts in this kit include all electronic
components, modules, and mechanical components required for making the smart car. And all of them are
packaged individually. There are detailed assembly and commissioning instructions in this book.

And if you encounter any problems, please feel free to contact us for fast and free technical support.

support@[Link]

The contents in this book can help enthusiasts with little technical knowledge to make a smart car. If you are
very interested in Raspberry Pi, and want to learn how to program and build the circuit, please visit our
website [Link] or contact us to buy the kits designed for beginners:
Freenove Basic\LCD1602\Super\Ultrasonic\RFID\Ultimate Starter Kit for Raspberry Pi

Need support?  [Link]


█ [Link] Preface 7

Raspberry Pi Introduction

Raspberry Pi (called RPi, RPI, RasPi, the text these words will be used alternately later), a micro-computer with
size of a card, quickly swept the world since its debut. It is widely used in desktop workstation, media center,
smart home, robots, and even the servers, etc. It can do almost anything, which continues to attract fans to
explore it. Raspberry Pi used to be running with Linux system and along with the release of windows 10 IoT.
We can also run it with Windows. Raspberry Pi (with interfaces USB, network, HDMI, camera, audio, display
and GPIO), as a microcomputer, can be running in command line mode and desktop system mode.
Additionally, it is easy to operate just like Arduino, and you can even directly operate the GPIO of CPU.

So far, Raspberry Pi has developed to the fourth generation. Changes in versions are accompanied by increase
and upgrades in hardware. A type and B type, the first generation of products, have been stopped due to
various reasons. Other versions are popular and active and the most important is that they are consistent in
the order and number of pins, which makes the compatibility of peripheral devices greatly enhanced between
different versions.

Below are the Raspberry Pi pictures and model pictures supported by this product.
Practicality picture of Raspberry Pi 4 Model B: Model diagram of Raspberry Pi 4 Model B:

Need support?  [Link]


8 Preface [Link] █

Practicality picture of Raspberry Pi 3 Model B+: Model diagram of Raspberry Pi 3 Model B+:

Practicality picture of Raspberry Pi 3 Model B: Model diagram of Raspberry Pi 3 Model B:

Need support?  [Link]


█ [Link] Preface 9

Practicality picture of Raspberry Pi 2 Model B: Model diagram of Raspberry Pi 2 Model B:

Practicality picture of Raspberry Pi 1 Model B+: Model diagram of Raspberry Pi 1 Model B+:

Need support?  [Link]


10 Preface [Link] █

Practicality picture of Raspberry Pi 3 Model A+: Model diagram of Raspberry Pi 3 Model A+:

Practicality picture of Raspberry Pi 1 Model A+: Model diagram of Raspberry Pi 1 Model A+:

Need support?  [Link]


█ [Link] Preface 11

Practicality picture of Raspberry Pi Zero W: Model diagram of Raspberry Pi Zero W:

Practicality picture of Raspberry Pi Zero: Model diagram of Raspberry Pi Zero:

Need support?  [Link]


12 Preface [Link] █

Hardware interface diagram of RPi 4B is shown below:

GPIO
Connector Ethernet
Connector

Display
Connector

USB
Power Connector x4
Connector

MINI HDMI Camera Audio


Connector x2 Connector Connector

Hardware interface diagram of RPi 3B+/3B/2B/1B+ are shown below:

GPIO
Connector
USB
Connector
Display
Connector

Ethernet
Power Connector
Connector

HDMI Camera Audio


Connector Connector Connector

Need support?  [Link]


█ [Link] Preface 13

Hardware interface diagram of RPi 3A+/A+ is shown below:

GPIO
Connector

USB
Display Connector
Connector

Power
Connector

HDMI Camera Audio


Connector Connector Connector

Hardware interface diagram of RPi Zero/Zero W is shown below:

GPIO
Connector

Camera
Connector

HDMI USB Power


Connector Connector Connector

Need support?  [Link]


14 Preface [Link] █

GPIO

GPIO: General purpose input/output. We will introduce the specific feature of the pins on the Raspberry Pi
and what you can do with them. You can use them for all sorts of purposes. Most of them can be used as
either inputs or outputs, depending on your program.
When programming the GPIO pins there are 3 different ways to refer to them: GPIO numbering, physical
numbering, WiringPi GPIO Numbering.

BCM GPIO Numbering


Raspberry Pi CPU use BCM2835/BCM2836/BCM2837of Broadcom. GPIO pin number is set by chip
manufacturer. These are the GPIO pins as that computer recognizes. The numbers are unordered and don't
make any sense to humans. You will need a printed reference or a reference board that fits over the pins.
Each pin is defined as below:

For more details about pin definition of GPIO, please refer to [Link]

Need support?  [Link]


█ [Link] Preface 15

PHYSICAL Numbering
Another way to refer to the pins is by simply counting across and down from pin 1 at the top left (nearest to
the SD card). This is 'physical numbering', as shown below:

WiringPi GPIO Numbering


Different from the previous mentioned two kinds of GPIO serial numbers, RPi GPIO serial number of the
WiringPi was renumbered. Here we have three kinds of GPIO number mode: based on the number of BCM
chip, based on the physical sequence number and based on wiringPi. The correspondence between these
three GPIO numbers is shown below:

(For more details, please refer to [Link] )

Need support?  [Link]


16 Preface [Link] █

You can also use the following command to view their correspondence.
gpio readall

For more details about wiringPi, please refer to [Link] .

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 17

Chapter 0 Raspberry Pi Preparation

Install a System

Firstly, install a system for your RPi.

Component List

Required Components
Raspberry Pi 4B / 3B+/ 3B /3A+ (Recommended) 5V/3A Power Adapter. Different versions of
Raspberry Pi have different power requirements.

Micro USB Cable x1 Micro SD Card (TF Card) x1, Card Reader x1

This robot also supports the following versions of the Raspberry Pi, but additional accessories need to be
prepared by yourself.
Raspberry Additional accessories
Raspberry Pi Zero W Camera cable(>25cm) for zero w, 15 Pin 1.0mm Pitch to 22 Pin 0.5mm
[Link]
Raspberry Pi Zero 1.3 wireless network adapter,
Camera cable(>25cm) for zero w, 15 Pin 1.0mm Pitch to 22 Pin 0.5mm,
OTG cable (USB Type micro B to USB Type A)
Raspberry Pi 2 Model B wireless network adapter
Raspberry Pi 1 Model A+ wireless network adapter
Raspberry Pi 1 Model B+ wireless network adapter

Need support?  [Link]


18 Chapter 0 Raspberry Pi Preparation [Link] █

Power requirement of different versions of Raspberry Pi is shown in following table:


Product Recommended Maximum total USB Typical bare-board
PSU current peripheral current draw active current
capacity consumption
Raspberry Pi Model A 700mA 500mA 200mA
Raspberry Pi Model B 1.2A 500mA 500mA
Raspberry Pi Model A+ 700mA 500mA 180mA
Raspberry Pi Model B+ 1.8A 600mA/1.2A (switchable) 330mA
Raspberry Pi 2 Model B 1.8A 600mA/1.2A (switchable) 350mA
Raspberry Pi 3 Model B 2.5A 1.2A 400mA
Raspberry Pi 3 Model A+ 2.5A Limited by PSU, board, and 350mA
connector ratings only.
Raspberry Pi 3 Model B+ 2.5A 1.2A 500mA
Raspberry Pi 4 Model B 3.0A 1.2A 600mA
Raspberry Pi Zero W 1.2A Limited by PSU, board, and 150mA
connector ratings only.
Raspberry Pi Zero 1.2A Limited by PSU, board, and 100mA
connector ratings only
For more details, please refer to [Link]

In addition, RPi also needs a network cable used to connect it to wide area network.

All of these components are necessary. Among them, the power supply is required at least 5V/2.5A, because
lack of power supply will lead to many abnormal problems, even damage to your RPi. So power supply with
5V/2.5A is highly recommend. SD Card Micro (recommended capacity 16GB or more) is a hard drive for RPi,
which is used to store the system and personal files. In later projects, the components list with a RPi will
contains these required components, using only RPi as a representative rather than presenting details.

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 19

Optional Components

Under normal circumstances, there are two ways to login to Raspberry Pi: using independent monitor, or
remote desktop to share a monitor with your PC.
Required Accessories for Monitor
If you want to use independent monitor, mouse and keyboard, you also need the following accessories.
1. Display with HDMI interface
2. Mouse and Keyboard with USB interface

As to Pi Zero and Pi Zero W, you also need the following accessories.


1. Micro-HDMI to HDMI converter wire.
2. Micro-USB to USB-A Receptacles converter wire (Micro USB OTG wire).
3. USB HUB.
4. USB transferring to Ethernet interface or USB Wi-Fi receiver.

For different Raspberry Pi, the optional items are slightly different. But all of their aims are to convert the
special interface to standard interface of standard Raspberry Pi.
Item Pi Zero Pi Zero W Pi A+ Pi 3A+ Pi B+/2B Pi 3B/3B+/4B
Monitor Yes Yes Yes Yes Yes Yes
Mouse Yes Yes Yes Yes Yes Yes
Keyboard Yes Yes Yes Yes Yes Yes
Micro-HDMI to
Yes Yes No No No No
HDMI cable
Micro-USB to USB-A
Yes Yes No No No No
OTG cable
USB HUB Yes Yes Yes Yes No No
USB transferring to select optional Internal
optional select
Ethernet interface one from Integration
one from
USB Wi-Fi receiver two or Internal Internal
two or
select Internal Integration Integration
select two optional
two from Integration
from two
two

Required Accessories for Remote Desktop


If you don't have an independent monitor, or you want to use a remote desktop, first you need to login to
Raspberry Pi through SSH, then open the VNC or RDP service. So you need the following accessories.

Item Pi Zero Pi Zero W Pi A+ Pi 3A+ Pi B+/2B Pi 3B/3B+/4B


Micro-USB to USB-A Yes Yes No
OTG cable
USB transferring to Yes Yes Yes
Ethernet interface NO

Need support?  [Link]


20 Chapter 0 Raspberry Pi Preparation [Link] █

Raspberry Pi OS

Install imager tool


Visit this website to install imager tool.
[Link]

Download OS file
Visit following website to download the OS file.
[Link]

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 21

Write System to Micro SD Card


First, insert your Micro SD card into card reader and connect it to USB port of PC. Then open imager tool.
Choose system that you just downloaded in Use custom.

Need support?  [Link]


22 Chapter 0 Raspberry Pi Preparation [Link] █

Choose the SD card.

Image option.

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 23

Enable SSH.

Configure WiFi and location. Here we set username as pi, password as raspberry

Need support?  [Link]


24 Chapter 0 Raspberry Pi Preparation [Link] █

Finally WRITE.

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 25

Start Raspberry Pi
If you don’t have a spare monitor, please skip to next section.
If you have a spare monitor, please follow the steps in this section.
After the system is written successfully, put SD card into the SD card slot of RPi. Then connect your RPi to
monitor through HDMI cable, attach your mouse and keyboard through the USB ports,

Later, after setup, you will need to enter your user name and password to login. The default user name: pi;
password: raspberry. After login, you should see the following screen.

You can connect WiFi on the right corner if WiFi is connected successfully.
Now you can skip to VNC Viewer.

Need support?  [Link]


26 Chapter 0 Raspberry Pi Preparation [Link] █

Remote desktop & VNC

After you log in Raspberry Pi, please use VNC Viewer to connect Raspberry Pi for this robot. Other
remote ways may not support GUI. If you have logged in Raspberry Pi please skip to VNC Viewer.

If you don't have a spare monitor, mouse and keyboard for your RPi, you can use a remote desktop to share
a display, keyboard, and mouse with your PC. Below is how to use:
MAC OS remote desktop and Windows OS remote desktop.

MAC OS Remote Desktop

Open the terminal and type following command. If this command doesn’t work, please move to next page.
ssh pi@[Link]
The password is raspberry by default, case sensitive.

You may need to type yes during the process.

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 27

You can also use the IP address to log in Pi.


Enter router client to inquiry IP address named “raspberry pi”. For example, I have inquired to my RPi IP
address, and it is “[Link]".

Open the terminal and type following command.


ssh pi@[Link]
When you see pi@raspberrypi:~ $, you have logged in Pi successfully. Then you can skip to next section.

Then you can skip to VNC Viewer.

Need support?  [Link]


28 Chapter 0 Raspberry Pi Preparation [Link] █

Windows OS Remote Desktop

If you are using win10, you can use follow way to login Raspberry Pi without desktop.
Press Win+R. Enter cmd. Then use this command to check IP:
ping -4 [Link]

Then [Link] is my Raspberry Pi IP.

Or enter router client to inquiry IP address named “raspberrypi”. For example, I have inquired to my RPi
IP address, and it is “[Link]".

ssh pi@[Link]

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 29

VNC Viewer & VNC

Type the following command. And select Interfacing Options VNC YesOKFinish. Here Raspberry Pi
may need to be restarted, and choose ok. Then open VNC interface.
sudo raspi-config

Need support?  [Link]


30 Chapter 0 Raspberry Pi Preparation [Link] █

Then download and install VNC Viewer according to your computer system by clicking following link:
[Link]
After installation is completed, open VNC Viewer. And click File  New Connection. Then the interface is
shown below.

Enter IP address of your Raspberry Pi and fill in a Name. And click OK.
Then on the VNC Viewer panel, double-click new connection you just created, and the following dialog box
pops up.

Enter username: pi and Password: raspberry. And click OK.

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 31

Here, you have logged in to Raspberry Pi successfully by using VNC Viewer

If the resolution ratio is not great or there is just a little window, you can set a proper resolution ratio via
steps below.
sudo raspi-config
Select Display OptionsVNV ResolutionProper resolution ratio (set by yourself)OKFinishYes.
And then reboot Raspberry Pi.

Need support?  [Link]


32 Chapter 0 Raspberry Pi Preparation [Link] █

In addition, your VNC Viewer window may zoom your Raspberry Pi desktop. You can change it. On your
VNC View control panel, click right key. And select Properties->Options label->Scaling. Then set proper
scaling.

Need support?  [Link]


█ [Link] Chapter 0 Raspberry Pi Preparation 33

Here, you have logged in to Raspberry Pi successfully by using VNC Viewer and operated proper setting.

Raspberry Pi 4B/3B+/3B integrates a Wi-Fi adaptor. If you did not connect Pi to WiFi. You can connect it to
wirelessly control the robot.

Need support?  [Link]


34 Chapter 1 Software installation and Test (necessary) [Link] █

Chapter 1 Software installation and Test (necessary)


If you have any concerns, please feel free to contact us via support@[Link]

In this chapter, we will make some necessary preparation: start your Pi Raspberry and install some necessary
libraries. Then test some parts. Batteries are needed when driving peripherals such as motors, servos, LEDs,
etc.

Note:
1, Please use Raspberry Pi OS with Desktop
2, The installation of libraries takes much time. You can power Raspberry Pi with a power supply Cable.
3, If you are using remote desktop to login Raspberry Pi, you need to use VNC viewer.

You can refer to this video.

[Link]

Step 1 Obtain the Code and Set python3 as Default

To download the code, you can power Raspberry Pi with a power supply cable or switch on S1 (Power Switch).
Then open the Raspberry Pi and the terminal. You can open the terminal by clicking as shown below, or you
can press “CTRL + ALT + T” on the desktop.

Terminal Terminal

The terminal is shown below:

Open the terminal and type the following commands to obtain the car code. And the code will be placed in
the directory "Pi". (Note: Here are two commands. Please execute them in order.)
cd
git clone [Link]
Need support?  [Link]
█ [Link] Chapter 1 Software installation and Test (necessary) 35

Downloading takes some time. Please wait with patience.


You can also find and download the code by visiting our official website ([Link] or our
GitHub repository ([Link]
Please note that this tutorial is based on python3. If you want to use python2, please download another
version of the tutorial.

Set Python3 as default python (Necessary)

First, execute python to check the default python on your Raspberry Pi. Press Ctrl-Z to exit.

If it is python3, you can skip this section.


If it is python2, you need execute the following commands to set default python to python3.
1. Enter directory /usr/bin
cd /usr/bin
2. Delete the original python link.
sudo rm python
3. Create new python links to python.
sudo ln -s python3 python
4. Check python. Press Ctrl-Z to exit.
python

If you want to set python2 as default python in other projects, just repeat the commands above and change
python3 to python2.

Need support?  [Link]


36 Chapter 1 Software installation and Test (necessary) [Link] █

Shortcut Key
Now, we will introduce several shortcuts that are very useful and commonly used in terminal.
1. up and down arrow keys. History commands can be quickly brought back by using up and down arrow
keys, which are very useful when you need to reuse certain commands.
When you need to type commands, pressing “↑” will go backwards through the history of typed commands,
and pressing “↓” will go forwards through the history of typed command.
2. Tab key. The Tab key can automatically complete the command/path you want to type. When there are
multiple commands/paths conforming to the already typed letter, pressing Tab key once won’t have any result.
And pressing Tab key again will list all the eligible options. This command/path will be completely typed as
soon as you press the Tab key when there is only one eligible option.

As shown below, under the ‘~’directory, enter the Documents directory with the “cd” command. After typing
“cd D”, press Tab key, then there is no response. Press Tab key again, then all the files/folders that begin with
“D” is listed. Continue to type the character "oc", then press the Tab key, and then “Documents” is completely
typed automatically.

Need support?  [Link]


█ [Link] Chapter 1 Software installation and Test (necessary) 37

Step 2 Configuration

Enable I2C and VNC


The I2C interface Raspberry Pi is disabled by default. You need to open it manually.

Click

Click

Need support?  [Link]


38 Chapter 1 Software installation and Test (necessary) [Link] █

Type a command to check whether the I2C module is enabled:


lsmod | grep i2c
If I2C module has been enabled, the following content will show up (the numbers showing in your device may
be different):

Install I2C-Tools
Type the command to install I2C-Tools.
sudo apt-get install i2c-tools
Install python-smbus
Python-smbus is a module of the program Python, which contains some classes and methods to operate I2C.
Type the following command to install python-smbus:
sudo apt-get install python3-smbus

Communication test
The smart car board has two chips, PCF8591 and PCA9685. Their I2C addresses are 0X48 and 0X40 respectively.
Command “i2cdetect –y 1” can detect whether the board is successfully connected to Raspberry Pi.
i2cdetect -y 1

If an I2C device is connected to your RPI, its I2C address will be displayed here.

Need support?  [Link]


█ [Link] Chapter 1 Software installation and Test (necessary) 39

Additional supplement
Raspbery Pi, other than 4B and 400, needs to disable the audio module, othewise the LED will not work
properly.
1. Create a new [Link] and open it for editing
sudo nano /etc/modprobe.d/[Link]
Add following content: After adding the contents, you need to press Ctrl+O, Enter, Ctrl+Z.
blacklist snd_bcm2835

2. We also need to edit config file.


sudo nano /boot/[Link]
Find the contents of the following two lines (with Ctrl + W you can search):
# Enable audio (loads snd_bcm2835)
dtparam=audio=on
Add # to comment out the second line. Press Ctrl+O, Enter, Ctrl+X.
# Enable audio (loads snd_bcm2835)
# dtparam=audio=on

It will take effect after restarting, and you can restart after executing the next section.
If you want to restart the audio module, just restore the content modified in the above two steps.

Need support?  [Link]


40 Chapter 1 Software installation and Test (necessary) [Link] █

Step 3 Run the Libraries Installation Program

1. Execute following commands to enter directory of “[Link]”.


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code
2. Run [Link]
sudo python [Link]

This program will automatically install the pca9685, rpi_ws281x, PyQt5 library, etc. Please reboot the Raspberry
Pi after the installation is completed, as shown below.

If the installation fails, please rerun [Link]. After the installation is completed, restart the Raspberry Pi. Most
installation failures are caused by network reasons.
sudo python [Link]

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 41

Chapter 2 Assemble Smart Car


If you have any concerns, please feel free to contact us via support@[Link]

You can refer to this video: [Link]

Motor, Wheel and Servo arm

Installation steps:
Step 0

Screw M2.5*8
Servo arm

Place the Rocker arm on the smart car board in accordance with its silkscreen printing. Use two M2.5*8
screws to install it to smart car board.

There are two servo packages. Each package contains one servo, three rocker arms, one M2*4 screw and
two M2.5*8 screws, as shown below:

Screw M2.5*8

Rocker arm

Need support?  [Link]


42 Chapter 2 Assemble Smart Car [Link] █

Step 1
There are 4 bracket packages to fix motors, each containg an aluminum bracket, two M3*30 screws, two
M3*8 screws and two M3 nuts, as shown below:

Screw
M3*8

Install motor bracket with M3*8.

You can also attach this bracket to motor first.

Step 2

Keep the side with


wire toward inside.

M3*30 M3
Screw Nut

Install motor to bracket with M3*30 screw and M3 Nut.

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 43

Step 3

The installation of the rest 3 sets of motor is the same. Then connect motor wires to motor ports. If you
think the wires are too long, you can tie a knot.
Step 4

Install 4 wheels to motor. The mounting hole is not a round hole.

Need support?  [Link]


44 Chapter 2 Assemble Smart Car [Link] █

Now, all motors and wheels are installed successfully.

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 45

Infrared line tracking module

Step 1

M3*6 M3*30
Screw Standoff

First install two M3*30 standoffs on smart car board with M3*6 screws. Then install line tracking module on
standoffs with M3*6 screws.
Step 2

Cable
XH-2.54-5Pin

Connect line tracking module to smart car board with XH-2.54-5Pin cable.

Need support?  [Link]


46 Chapter 2 Assemble Smart Car [Link] █

Raspberry Pi

M2.5*4
Screw

M2.5*8+6 Standoff X4
First install four M2.5*8+6 standoffs to the nuts on smart car board. And then place the Rapberry Pi on the
standoff in accordance with its silkscreen printing, and use four M2.5*4 screws to install it.

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 47

Connection board

Step 1

Install the connection board as shown in the figure above. Long female header connector should be
connected to smart car board and the short one should be connected to Raspberry Pi.
Step 2
Press it until you can see the pins.

× √

If you have any concerns, please feel free to contact us via support@[Link]
We will offer you satisfied solution.

Need support?  [Link]


48 Chapter 2 Assemble Smart Car [Link] █

Pan Tilt

Finally, install two 18650 batteries. Please refer to About_Battery.pdf in the unzipped folder.

Please push the battery to + ends of battery holder to make the connection good enough.
Run program
In the first chapter, we did not install the Pan-Tilt. Because we need to run programs for the installation of the
servos to ensure that the servos rotate to the correct angle.
Next let us install the Pan-Tilt.
Connect two servos to port Servo0 and port Servo1 on the smart car board. And please remember the
numbers of the servos.

Servo1

Servo0

Enter the following command in the terminal:


If the terminal displays the directory as below (where [Link] is located). You can directly execute the [Link]
command.

[Link] not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
[Link] [Link] command:
sudo python [Link]
Then servos rotate to a proper angle. Please keep the connection between the servos and the smart car board.

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 49

Installation steps: (Note: Do not disorder Servo0 and Servo1 during the installation.)
Step 1 Step 2 Step 3
Acrylic Arcylic
part

M3*14 Servo0

M2*10

Step 4 Step 5 Step 6


Servo1 Arcylic

M2*10 M1.4*4

Servo0 Camera

Step 7 Step 8: Step 9


M2.5*8
M3*14
M3*14
M3*14

Now please refer to Wiring Section to wring ultrasonic sensor and camera frist.

Step 10 Step 11 After finished

Keep them
vertical
M2*4 screw in servo package

Need support?  [Link]


50 Chapter 2 Assemble Smart Car [Link] █

Install Pan Tilt on smart car board.


Step 1

Keep the pan tilt as shown in the right picture and install servo0 with rocker arm.
Step 2
Use a Cross screwdrive to support M2 * 10 screws and M2 nuts to fix the servo 0.

Screw M2*10 and Nut M2

Screw M2*10

Nut M2
Screw

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 51

Step 3

Servo 1

Servo 0

Pay attention to servo wiring.


(Note: wiring about the ultrasonic and camera module will be introduced later. )

Need support?  [Link]


52 Chapter 2 Assemble Smart Car [Link] █

Wiring

Camera
You need shut down Raspberry Pi when wire camera.
Step 1

Step 2

√ ×
The Blue side of cable should be toward to Servo.
Connect one end of cable to camera. Please note the front and back of the cable.

Need support?  [Link]


█ [Link] Chapter 2 Assemble Smart Car 53

Step 3

Step 4

√ ×

The Blue side of cable should be toward to RPi USB port.


Connect another end of cable to Raspberry Pi. Please note the front and back of the cable.

Need support?  [Link]


54 Chapter 2 Assemble Smart Car [Link] █

Ultrasonic
Use jumper wires F/F to connect ultrasonic module with pins on smart car board.
GND-GND, VCC-5V, ECHO-ECHO, TRIG-TRIG

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 55

Chapter 3 Module test (necessary)


If you have any concerns, please feel free to contact us via support@[Link]
In this section, the car must be equipped with batteries, and Both S1 power switch and S2 motor switch need
to be preessed. Then 5V, 3.3V, battery power indicators will be turned on.

S2:
Motor and servo S1:
power switch Power main switch

During the test, the motor will work. So you can disconnect the wheels or put it on the ground to avoid that
it falls down and is damaged. Next, test RGB LED, motor, ultrasonic module, servo, etc.

You can still power Raspberry Pi with a power supply Cable when switches are pressed.

If you have never learned python before, you can learn some basic knowledge via the link below:
[Link]

Need support?  [Link]


56 Chapter 3 Module test (necessary) [Link] █

Motor

Run program
Open the terminal of Raspberry Pi. Enter the following commands to test the motor.
1. Use the cd command to enter the directory where [Link] is located.
cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Execute [Link] command:
sudo python [Link] Motor

Result:
The car moves forward for 1 seconds, then moves back for 1 seconds, then turns left for 1 seconds, turns right
for 1 seconds, then stops. You can press "Ctrl + C" to end the program ahead of time. If the car doesn’t work
normally, please check if both switches are pressed.

If the direction is reversed, it moves back then move forward, please follow steps below.

1. Find [Link] in the following path in your Raspberry Pi:


Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server/[Link]
Open [Link] and add a “–“ before duty1,2,3,4 like below.
1 def setMotorModel(self,duty1,duty2,duty3,duty4):
2 duty1,duty2,duty3,duty4=self.duty_range(duty1,duty2,duty3,duty4)
3 self.left_Upper_Wheel(-duty1)
4 self.left_Lower_Wheel(-duty2)
5 self.right_Upper_Wheel(-duty3)
6 self.right_Lower_Wheel(-duty4)

Then save the modification and try again.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 57

The code is as below:


1 from Motor import *
2 PWM=Motor()
3 def test_Motor():
4 try:
5 [Link](1000,1000,1000,1000) #Forward
6 print "The car is moving forward"
7 [Link](1)
8 [Link](-1000,-1000,-1000,-1000) #Back
9 print "The car is going backwards"
10 [Link](1)
11 [Link](-1500,-1500,2000,2000) #Left
12 print "The car is turning left"
13 [Link](1)
14 [Link](2000,2000,-1500,-1500) #Right
15 print "The car is turning right"
16 [Link](1)
17 [Link](0,0,0,0) #Stop
18 print "\nEnd of program"
19 except KeyboardInterrupt:
20 [Link](0,0,0,0)
21 print "\nEnd of program"

Reference
setMotorModel(data1,data2,data3,data4)
This function has four input parameters that control the left front motor, the left rear motor, the right front
motor, and the right rear motor. When the input parameter is within 0~4096, the motor will rotate forward.
If it is within -4096~0, the motor will rotate reversely. The larger the absolute value is, the faster the motor
is. When the input is 0, the motor will stop. If the function is input as follows: setMotorModel(2000,2000,
2000, 2000), four motors will rotate forward and the car will move forward.

Data1 Data2

Data3 Data4

Need support?  [Link]


58 Chapter 3 Module test (necessary) [Link] █

ADC Module

Run program
Enter the following commands to test ADC module.
If the terminal displays the directory as below (where [Link] is located). You can directly execute the [Link]
command.

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Execute [Link] command:
sudo python [Link] ADC

Result:
Every 1s, the voltage values of the two photoresistors and the battery are output. The value read for the first
time is not stable and inaccurate when the chip just starts. It will be stable later. You can press "Ctrl + C" to
end program.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 59

The code is as below:


1 from ADC import *
2 adc=Adc()
3 def test_Adc():
4 try:
5 while True:
6 Left_IDR=[Link](0)
7 print ("The photoresistor voltage on the left is "+str(Left_IDR)+"V")
8 Right_IDR=[Link](1)
9 print ("The photoresistor voltage on the right is "+str(Right_IDR)+"V")
10 Power=[Link](2)
11 print ("The battery voltage is "+str(Power*3)+"V")
12 [Link](1)
13 print '\n'
14 except KeyboardInterrupt:
15 print "\nEnd of program"

Reference
recvADC(channel)
This function has only one input parameter, which can be 0, 1 or 2.
When the input is 0, the value of this function is the voltage value of the left photoresistor.
When the input is 1, the value of this function is the voltage value of the right photoresistor.
When the input is 2, the value of this function is the voltage value of each battery. After multiplying by 3,
it is the actual battery voltage value

Need support?  [Link]


60 Chapter 3 Module test (necessary) [Link] █

Infrared Line tracking module

Run program
Enter the following command in the terminal to test line tracking module.
If the terminal displays the directory as below (where [Link] is located), you can directly execute the [Link]
command.

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Execute [Link] command:
sudo python [Link] Infrared

Result:
When the black line is on the left side of the module, the left LED will light up and the terminal will print “Left”;
When the black line is in the middle of the module, the middle LED will light up and the terminal will print
“Middle”.
When the black line is on the right side of the module, right The LED will light up, the terminal will print “Right”,
You can press “Ctrl + C” to end the program.

If there are issues with the test, the infrared device may need to be adjusted. The adjustment screw is on top
of the sensor.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 61

The code is as below:


1 from Infrared_Obstacle_Avoidance import *
2 def test_Infrared():
3 try:
4 while True:
5 if [Link](IR01)!=True and [Link](IR02)==True and [Link](IR03)!=True:
6 print 'Middle'
7 elif [Link](IR01)!=True and [Link](IR02)!=True and [Link](IR03)==True:
8 print 'Right'
9 elif [Link](IR01)==True and [Link](IR02)!=True and [Link](IR03)!=True:
10 print 'Left'
11 except KeyboardInterrupt:
12 print "\nEnd of program"

Reference
[Link](IO)
This function has an input parameter. If the IO input is high level, [Link](IO) returns True. If the IO input
is low level, [Link](IO) returns False.

Need support?  [Link]


62 Chapter 3 Module test (necessary) [Link] █

LED

There are 8 RGB LEDs on the smart car board, as shownbelow. You can control them separately.

LED5 LED6

LED4 LED7

LED3 LED0

LED2 LED1

Run program
Enter the following commands to test LEDs.
If the terminal displays the directory as below (where [Link] is located), you can directly execute the [Link]
command.

[Link] not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
[Link] [Link] command:
sudo python [Link] Led

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 63

Result:
All LEDs will be turned on for 3 seconds, and colors from LED0 to LED7 are: red, orange, yellow, green, cyan,
blue, purple, and white. You can end the program ahead of time by pressing "ctrl+c".
If the LED color display order is not correct, open the "[Link]" file in the current directory and modify the
value of the "[Link]" variable on line 15.

The code of [Link] is as below:


1 import time
2 try:
3 from Led import *
4 led=Led()
5 def test_Led():
6 try:
7 [Link](0x01,255,0,0) #Red
8 [Link](0x02,255,125,0) #orange
9 [Link](0x04,255,255,0) #yellow
10 [Link](0x08,0,255,0) #green
11 [Link](0x10,0,255,255) #cyan-blue
12 [Link](0x20,0,0,255) #blue
13 [Link](0x40,128,0,128) #purple
14 [Link](0x80,255,255,255) #white
15 print "The LED has been lit, the color is red orange yellow green cyan-blue blue
16 white"
17 [Link](3) #wait 3s
18 [Link]([Link], Color(0,0,0)) #turn off the light
19 print "\nEnd of program"
20 except KeyboardInterrupt:
21 [Link]([Link], Color(0,0,0)) #turn off the light
22 print "\nEnd of program"
23 except:
24 pass

Need support?  [Link]


64 Chapter 3 Module test (necessary) [Link] █

Reference
ledIndex( Index, R, G, B)
This function has 4 parameters.
The first one is the index of the LED that you want to control. Its value is hexadecimal. There are LED0~7.
The rest 3 parameters are R G B value of color respectively.
For example, ledindex(0x01,255,0,0) makes LED 0 light to red; ledeindex(0x40,0,255,0) makes LED 6 light
green.

colorWipe(strip, color, wait_ms)


This function erases the color of one pixel at a time. It has three input parameters: strip represents the
Neopixel object, color represents the color to be erased, and wait_ms represents the erasure interval. The
default is 50ms. For example, colorWipe(strip, Color(255,0,0),20) means that the LED0 is red first, wait for
20ms, and then the LED1 is also red, until all eight LEDs are lit and red.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 65

LED Show

Now we add some algorithms in this chapter to make the LED display more styles. You can take this as a
reference, then you can use your imagination to write your own algorithm to achieve the LED styles you want.
Run Program
If the terminal displays the directory as below, you can directly run the [Link].

[Link] not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
[Link] [Link]:
sudo python [Link]

You can press "Ctrl + C" to end the program.

Part of code is as below:


1 # -*-coding: utf-8 -*-
2 import time
3 from rpi_ws281x import *
4 # LED strip configuration:
5 LED_COUNT = 8 # Number of LED pixels.
6 LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
7 LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
8 LED_DMA = 10 # DMA channel to use for generating signal (try 10)
9 LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
10 LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
11 LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
12 # Define functions which animate LEDs in various ways.
13 class Led:
14 def __init__(self):
15 [Link] = "GRB" #Control the sending order of color data
16 # Create NeoPixel object with appropriate configuration.
17 [Link] = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
18 LED_BRIGHTNESS, LED_CHANNEL)
19 # Intialize the library (must be called once before other functions).

Need support?  [Link]


66 Chapter 3 Module test (necessary) [Link] █

20 [Link]()
21 def LED_TYPR(self,order,R_G_B):
22 B=R_G_B & 255
23 G=R_G_B >> 8 & 255
24 R=R_G_B >> 16 & 255
25 Led_type=["GRB","GBR","RGB", "RBG","BRG","BGR"]
26 color =
27 [Color(G,R,B),Color(G,B,R),Color(R,G,B),Color(R,B,G),Color(B,R,G),Color(B,G,R)]
28 if order in Led_type:
29 return color[Led_type.index(order)]
30 def colorWipe(self,strip, color, wait_ms=50):
31 """Wipe color across display a pixel at a time."""
32 color=self.LED_TYPR([Link],color)
33 for i in range([Link]()):
34 [Link](i, color)
35 [Link]()
36 [Link](wait_ms/1000.0)
37 def wheel(self,pos):
38 """Generate rainbow colors across 0-255 positions."""
39 if pos<0 or pos >255:
40 r=g=b=0
41 elif pos < 85:
42 r=pos * 3
43 g=255 - pos * 3
44 b=0
45 elif pos < 170:
46 pos -= 85
47 r=255 - pos * 3
48 g=0
49 b=pos * 3
50 else:
51 pos -= 170
52 r=0
53 g=pos * 3
54 b=255 - pos * 3
55 return self.LED_TYPR([Link],Color(r,g,b))
56 def rainbow(self,strip, wait_ms=20, iterations=1):
57 """Draw rainbow that fades across all pixels at once."""
58 for j in range(256*iterations):
59 for i in range([Link]()):
60 [Link](i, [Link]((i+j) & 255))
61 [Link]()
62 [Link](wait_ms/1000.0)
63 def rainbowCycle(self,strip, wait_ms=20, iterations=5):

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 67

64 """Draw rainbow that uniformly distributes itself across all pixels."""


65 for j in range(256*iterations):
66 for i in range([Link]()):
67 [Link](i, [Link]((int(i * 256 / [Link]())
68 + j) & 255))
69 [Link]()
70 [Link](wait_ms/1000.0)
71 def theaterChaseRainbow(self,strip, wait_ms=50):
72 """Rainbow movie theater light style chaser animation."""
73 for j in range(256):
74 for q in range(3):
75 for i in range(0, [Link](), 3):
76 [Link](i+q, [Link]((i+j) % 255))
77 [Link]()
78 [Link](wait_ms/1000.0)
79 for i in range(0, [Link](), 3):
80 [Link](i+q, 0)
81 led=Led()
82 # Main program logic follows:
83 if __name__ == '__main__':
84 print ('Program is starting ... ')
85 try:
86 while True:
87 print "Chaser animation"
88 [Link]([Link], Color(255,0, 0)) # Red wipe
89 [Link]([Link], Color(0, 255, 0)) # Green wipe
90 [Link]([Link], Color(0, 0, 255)) # Blue wipe
91 [Link]([Link])
92 print "Rainbow animation"
93 [Link]([Link])
94 [Link]([Link])
95 [Link]([Link], Color(0,0,0),10)
96 except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be
97 executed.
98 [Link]([Link], Color(0,0,0),10)

Reference
[Link](Index,color(R,G,B))
This is a function of WS2812 library. It is the same as the previously customized ledIndex() function. It is
used to light up one LED and it has two input parameters. The first one is the LED number, the second
one is used to set the color of the LED. For example, [Link](1,Color(255, 0, 0)), and write
[Link]() in the next line, then LED1 will light red.

[Link]()

Need support?  [Link]


68 Chapter 3 Module test (necessary) [Link] █

This function is of WS2812 library. When the LED color is set with the previous fuction, this function needs
to be executed to make the LED show the corresponding color. If the color is set, but this function is not
executed LED will not change color.

wheel(pos)
Generate rainbow colors in range of 0-255.

LED_TYPR(self,order,R_G_B)
Change the order in which the LED color data is transmitted. When the value of the order parameter is
"RGB", the order of data transmission should be: R-G-B; when the value of the order parameter is "GBR",
and the order of data transmission should be: G-B-R

theaterChaseRainbow(strip, wait_ms)
The function is used to make 8 LEDs show one color at the same time, and change to various colors to
make a blink. The blinking interval is wait_ms, and its default value is 50ms.

rainbow(strip, wait_ms,)
This function achieves the effect of rainbow breathing. It makes 8 LEDs display same color simultaneously,
and then change them all into various colors like breathing. The interval is wait_ms. The default value is
20ms.

rainbowCycle(strip, wait_ms)
This function also achieves the effect of rainbow breathing. but unlike rainbow(), it makes eight LEDs to
display different colors at the same time, and then change them into various color separately. The interval
is wait_ms. The default value is 20ms.

Result analysis
This code mainly achieves two LED effects, chasing animation and rainbow animation.
Chasing animation: first let the 8 LEDs light red one by one in turn, then green and blue. Interval is 50ms
between two LED, so the LED will display a round of red, then a round of green, and the last round of blue,
like chasing. Then let the LEDs blink with different colors with an interval of 50ms, rendering a tense
atmosphere, thus completing the chase animation.
Rainbow animation: The effect of the rainbow is different from the effect of blinking. The blinking is to make
the LED on, off, on, and off. And the rainbow is to make LED on all the time, and switch between different
colors, and the interval is shorter than the blinking. First, make the eight LEDs display one color at the same
time and then change the color with intervals of 20ms. And then make the eight LEDs display different colors
at the same time, and then change the color to produce another rainbow effect.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 69

Buzzer

Run the program


Enter the following command in the terminal to test buzzer.
If the terminal displays the directory as below (where [Link] is located). You can directly execute the [Link]
command.

1 If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2 Execute [Link] command:
sudo python [Link] Buzzer

Result:
The buzzer will be turned on and last for 3s. Then the program will automatically end or you can press "Ctrl
+ C" to end the program.

The code is as below:


1 from Buzzer import *
2 buzzer=Buzzer()
3 def test_Buzzer():
4 try:
5 [Link](cmd.CMD_START)
6 [Link](1)
7 print "1S"
8 [Link](1)
9 print "2S"
10 [Link](1)
11 print "3S"
12 [Link](cmd.CMD_STOP)
13 print "\nEnd of program"

Need support?  [Link]


70 Chapter 3 Module test (necessary) [Link] █

14 except KeyboardInterrupt:
15 [Link](cmd.CMD_STOP)
16 print "\nEnd of program"

Reference
[Link](cmd)
This function has one input parameter. If the input is ’1’, the buzzer will be turned on. If the input is ‘0’, the
buzzer will be turned off.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 71

Servo

Enter the following commands in the terminal to test servos.


If the terminal displays the directory as below (where [Link] is located), you can directly execute the [Link]
command.

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Execute [Link] command:
sudo python [Link] Servo

Result:
The servo 0 repeats rotating from left to right and then from right to left. The servo 1 repeats rotating from
bottom to top and then from top to bottom. You can press “Ctrl + C” to end the program.
The code is as below:
1 from servo import *
2 pwm=Servo()
3 def test_Servo():
4 try:
5 while True:
6 for i in range(50,110,1):
7 [Link]('0',i)
8 [Link](0.01)
9 for i in range(110,50,-1):
10 [Link]('0',i)
11 [Link](0.01)
12 for i in range(80,150,1):
13 [Link]('1',i)
14 [Link](0.01)
15 for i in range(150,80,-1):
16 [Link]('1',i)
17 [Link](0.01)
18 except KeyboardInterrupt:

Need support?  [Link]


72 Chapter 3 Module test (necessary) [Link] █

19 [Link]('0',90)
20 [Link]('1',90)
21 print "\nEnd of program"

Reference
setServoPwm(Servo,angle)
There are 2 parameters.
The first one is related to servo index.
The second one is related to the angle of servos.
For example,
setServoPwm(‘0’,20) makes servo0 rotate to 20°.
setServoPwm(‘1’,90) makes servo1 rotate to 90°.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 73

Ultrasonic module

Next, use jumper wires F/F to connect ultrasonic module with pins on smart car board.

When connecting the ultrasonic module, you need disconnect the Servo1 cable, so that the servo can
rotate freely, and after the wiring is completed, connect the servo cable again. When wiring, you should
keep the silk screen of the ultrasonic module and the smart car board consistent. Vcc should be connected
to 5V, Trig to TRIG, Echo to ECHO, and Gnd to GND.
If the connection is wrong, for example, if Vcc is connected to GND, and Gnd is connected to 5V, it will
cause the damage to ultrasonic module. After the wiring is completed, you can start testing.

Run program
Enter following command in the terminal:
If the terminal displays the directory as below (where [Link] is located). You can directly execute the [Link]
command.

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Execute [Link] command:
sudo python [Link] Ultrasonic

Need support?  [Link]


74 Chapter 3 Module test (necessary) [Link] █

Result:
Every 1s, the distance between the obstacle and the ultrasonic module will be printed out, and you can press
"Ctrl + C" to end the program.

The code is as below:


1 from Ultrasonic import *
2 ultrasonic=Ultrasonic()
3 def test_Ultrasonic():
4 try:
5 while True:
6 data=ultrasonic.get_distance() #Get the value
7 print ("Obstacle distance is "+str(data)+"CM")
8 [Link](1)
9 except KeyboardInterrupt:
10 print "\nEnd of program"

Reference
get_distance()
This function is used to obtain the distance between ultrasonic module and obstacles in front of it, with unit
CM.

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 75

Camera

Next let us connect the camera to smart car board. First turn off S1 (Power Switch), shut down Raspberry Pi
and disconnect power cable. If the data cable is used to power the Raspberry Pi, disconnect the data cable
and install the CSI camera to the Raspberry Pi camera interface when the Raspberry Pi is powered off. (The
CSI camera must be connected or disconnected under no power and when Raspberry Pi is shut down,
or the camera may be burned.)

Step 1

√ ×

The Blue side of cable should be toward to Servo.


Connect one end of cable to camera. Please note the front and back of the cable.

Need support?  [Link]


76 Chapter 3 Module test (necessary) [Link] █

Step 2

√ ×

The Blue side of cable should be toward to RPi USB port.


Connect another end of cable to Raspberry Pi. Please note the front and back of the cable.
Run program
To use the camera, you need to disable legacy camera, which is disabled by default on the latest Raspberry
Pi OS. If it is not disabled, please do it as below.
Enter the following command. Choose Interface Options Legacy Camera NoOKFinish,and then
restart the Raspberry Pi.
sudo raspi-config

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 77

Need support?  [Link]


78 Chapter 3 Module test (necessary) [Link] █

libcamera-apps does not work properly on Pi 0 to 3 devices when running the latest Bullseye images.
A workaround is to open a terminal, run "sudo raspi-config", navigate to "Advanced Options" and enable
"Glamor" graphic acceleration. Then reboot your Pi.
sudo raspi-config

Need support?  [Link]


█ [Link] Chapter 3 Module test (necessary) 79

Then reboot your Pi.

1. execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Execute the following command:
python [Link]
Then please open and check the generated [Link] under
/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server.

Need support?  [Link]


80 Chapter 4 Light tracing Car [Link] █

Chapter 4 Light tracing Car


If you have any concerns, please feel free to contact us via support@[Link]

Description

The light-tracing function of the car mainly uses a photoresistor. The car has two photoresistors located on
the left and right sides at the front to detect light

A photoresistor is a resistor based on the photoelectric effect of the semiconductor. The resistance changes
with the intensity of the incident light. With the incident light intensity increasing, the resistance decreases.
With the incident light intensity decreasing, the resistance increases.

And the change of the resistance value also causes voltage applied to the photoresistor changes. According
to the change of voltage, the position of the light to the car will be detected, and then make the car move
corresponding action to trace light.

Put your car in a darker environment.

Run program

If the terminal displays the directory as below, you can directly execute the [Link] command.

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Run [Link]:
sudo python [Link]

You can press "Ctrl + C" to end the program.

Need support?  [Link]


█ [Link] Chapter 4 Light tracing Car 81

The code is below:


1 import time
2 from Motor import *
3 from ADC import *
4 class Light:
5 def run(self):
6 try:
7 [Link]=Adc()
8 [Link]=Motor()
9 [Link](0,0,0,0)
10 while True:
11 L = [Link](0)
12 R = [Link](1)
13 if L < 2.99 and R < 2.99 :
14 [Link](600,600,600,600)
15
16 elif abs(L-R)<0.15:
17 [Link](0,0,0,0)
18
19 elif L > 3 or R > 3:
20 if L > R :
21 [Link](-1200,-1200,1400,1400)
22
23 elif R > L :
24 [Link](1400,1400,-1200,-1200)
25
26 except KeyboardInterrupt:
27 led_Car.[Link](0,0,0,0)
28
29 if __name__=='__main__':
30 print ('Program is starting ... ')
31 led_Car=Light()
32 led_Car.run()

Result analysis
When the voltages of left and right photoresistor are less than 2.99V, the car move forward straightly. And
when one of the voltages is greater than 3V:
If the left voltage is greater than the right, the car turns left.
If the right voltage is greater than the left, the car turns right.
You can change the judgment of the program to achieve the result you want, according to the light intensity
of the environment.

Need support?  [Link]


82 Chapter 5 Ultrasonic Obstacle Avoidance Car [Link] █

Chapter 5 Ultrasonic Obstacle Avoidance Car


If you have any concerns, please feel free to contact us via support@[Link]

Description

The obstacle avoidance function of the car mainly uses the HC-SR04 ultrasonic module. The ultrasonic module
is controlled by the servo. The servo rotates to the left, middle and right repeatedly, so that the ultrasonic
module measures the distance of obstacles on the left, middle and right directions. And then it controls the
car to move according to different distances.

Run program

If the terminal displays the directory as below, you can directly run the [Link].

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Run [Link]:
sudo python [Link]

You can press "Ctrl + C" to end the program.


Part of code is as below:
1 def run(self):
2 [Link]=Motor()
3 self.pwm_S=Servo()
4 for i in range(30,151,60):
5 self.pwm_S.setServoPwm('0',i)
6 [Link](0.2)
7 if i==30:
8 L = self.get_distance()
9 elif i==90:
10 M = self.get_distance()
11 else:
12 R = self.get_distance()
13 while True:

Need support?  [Link]


█ [Link] Chapter 5 Ultrasonic Obstacle Avoidance Car 83

14 for i in range(90,30,-60):
15 self.pwm_S.setServoPwm('0',i)
16 [Link](0.2)
17 if i==30:
18 L = self.get_distance()
19 elif i==90:
20 M = self.get_distance()
21 else:
22 R = self.get_distance()
23 self.run_motor(L,M,R)
24 for i in range(30,151,60):
25 self.pwm_S.setServoPwm('0',i)
26 [Link](0.2)
27 if i==30:
28 L = self.get_distance()
29 elif i==90:
30 M = self.get_distance()
31 else:
32 R = self.get_distance()
33 self.run_motor(L,M,R)
34 ultrasonic=Ultrasonic()
35 # Main program logic follows:
36 if __name__ == '__main__':
37 print ('Program is starting ... ')
38 try:
39 [Link]()
40 except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be
41 executed.
42 [Link](0,0,0,0)
43 ultrasonic.pwm_S.setServoPwm('0',90)

Result analysis
Let servo0 rotate back and forth to 30 degrees, 90 degrees and 150 degrees respectively. And the ultrasonic
module also follows the movement to measure the obstacle distance of these three angles.
When distances detected on the left>30cm, middle >30cm, right>30cm. It means that there is no obstacle
within 30cm. So the car move forward.
When distances detected on the left<30cm, middle <30cm, right<30cm, it means that the car enters a dead
end, so the car move back and turned back.
When distances detected on the left<30cm, middle <30cm, right>30cm. It means that there is an obstacle on
the left side of the car, so the car turn right.
When distances detected on the left>30cm, middle <30cm, right<30cm. It means that there is an obstacle on
the right side of the car, so the car turn left.

Need support?  [Link]


84 Chapter 6 Infrared Line Tracking Car [Link] █

Chapter 6 Infrared Line Tracking Car


If you have any concerns, please feel free to contact us via support@[Link]

Description

The line tracing function of the car mainly uses an infrared module. When the sensor detects black line, the
corresponding LED will light up, which controls the car to move according to the value of three sensors.

Run program

If the terminal displays the directory as below, you can directly run the program.

1. If not, execute the cd command:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Run Line_Tracking.py:
sudo python Line_Tracking.py

You can press "Ctrl + C" to end the program.


If there are issues with the test, the infrared device may need to be adjusted. The adjustment screw is on top
of the sensor.

Need support?  [Link]


█ [Link] Chapter 6 Infrared Line Tracking Car 85

The code is as below:


1 import time
2 from Motor import *
3 import [Link] as GPIO
4 IR01 = 14
5 IR02 = 15
6 IR03 = 23
7 [Link]([Link])
8 [Link](IR01,[Link])
9 [Link](IR02,[Link])
10 [Link](IR03,[Link])
11 class Line_Tracking:
12 def run(self):
13 while True:
14 [Link]=0x00
15 if [Link](IR01)==True:
16 [Link]=([Link] | 4)
17 if [Link](IR02)==True:
18 [Link]=([Link] | 2)
19 if [Link](IR03)==True:
20 [Link]=([Link] | 1)
21 if [Link]==2:
22 [Link](800,800,800,800)
23 elif [Link]==4:
24 [Link](-1500,-1500,2500,2500)
25 elif [Link]==6:
26 [Link](-2000,-2000,4000,4000)
27 elif [Link]==1:
28 [Link](2500,2500,-1500,-1500)
29 elif [Link]==3:
30 [Link](4000,4000,-2000,-2000)
31 elif [Link]==7:
32 pass
33
34 infrared=Line_Tracking()
35 # Main program logic follows:
36 if __name__ == '__main__':
37 print ('Program is starting ... ')
38 try:
39 [Link]()
40 except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be
41 executed.
42 [Link](0,0,0,0)

Need support?  [Link]


86 Chapter 6 Infrared Line Tracking Car [Link] █

Result analysis
There are 3 sensors on the left, middle and right. When the black line is detected by a sensor, it will show high
level, or it is low.
When the sensor on left: high, middle: low, right: low, the car turns left lightly.
When the sensor on left: high, middle: high, right: low, the car turns left.
When the sensor on left: low, middle: high, right: low, the car moves forward straight.
When the sensor on left: low, middle: low, right: high, the car turns right lightly.
When the sensor on left: low, middle: high, right: high, the car turns right.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 87

Chapter 7 Smart video car

You can refer to this video: [Link]

If you have any concerns, please feel free to contact us via support@[Link]
The smart video car integrates the previous functions of light tracing, obstacle avoidance, line tracing, video
transmission, face detection, LED and so on. And it is built with a server and a client, so it can be controlled
remotely.

Start Start

Open server Open client

Wait Connect
connection server

No
No

If success
If success

Yes
Yes
Wait
Send
command
command

No Yes

If get
command If success

Done No
Yes success
keep
Execute
sending
Command

End End

Need support?  [Link]


88 Chapter 7 Smart video car [Link] █

Server

The server works on the Raspberry Pi and can transmit camera data, ultrasonic data, etc. to the client, and it
can also receive commands from the client.
In the Server folder, there is a [Link] file which contains main server code.
get_interface_ip() is used to get IP address of the native Raspberry Pi wlan0, without manually modifying the
code to set IP parameters.
StartTcpServer() is used to start the TCP service. The channel of port 5000 is mainly used to send and receive
commands between the client and the server. The channel of port 8000 is used for the server to transmit the
collected camera data to the client.
StopTcpServer() is used to stop the TCP service.
sendvideo() is used to sends the camera data.

Part of server code is as follows:


1 def get_interface_ip(self):
2 s = [Link](socket.AF_INET, socket.SOCK_DGRAM)
3 return socket.inet_ntoa([Link]([Link](), 0x8915, [Link]('256s',
4 "wlan0"[:15]))[20:24])
5 def StartTcpServer(self):
6 HOST=str(self.get_interface_ip())
7 self.server_socket1 = [Link]()
8 self.server_socket1.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT,1)
9 self.server_socket1.bind((HOST, 5000))
10 self.server_socket1.listen(1)
11 self.server_socket = [Link]()
12 self.server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT,1)
13 self.server_socket.bind((HOST, 8000))
14 self.server_socket.listen(1)
15 print('Server address: '+HOST)
16
17 def StopTcpServer(self):
18 try:
19 [Link]()
20 [Link]()
21 except Exception , e:
22 print "No client connection"
23
24 def sendvideo(self):
25 try:
26 [Link],self.client_address = self.server_socket.accept()
27 [Link]=[Link]('rb')
28 except:
29 pass

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 89

30 self.server_socket.close()
31 try:
32 with [Link]() as camera:
33 [Link] = (400,300) # pi camera resolution
34 [Link] = 30 # 15 frames/sec
35 [Link](2) # give 2 secs for camera to initilize
36 start = [Link]()
37 stream = [Link]()
38 # send jpeg format video stream
39 print "Start transmit ... "
40 for foo in camera.capture_continuous(stream, 'jpeg', use_video_port = True):
41 try:
42 [Link]()
43 [Link](0)
44 b = [Link]()
45 lengthBin = [Link]('L', len(b))
46 [Link](lengthBin)
47 [Link](b)
48 if [Link]() - start > 600:
49 break
50 [Link](0)
51 [Link]()
52 except :
53 print "End transmit ... "
54 break
55 except:
56 print "Camera unintall"

Need support?  [Link]


90 Chapter 7 Smart video car [Link] █

Open Server

Step 1 Login Raspberry Pi via VNC viewer


Because server and client use GUI. You need use VNC viewer as remote desktop way.
Download and install VNC Viewer according to your computer system by clicking following link:
[Link]
After installation is completed, open VNC Viewer. And click File  New Connection. Then the interface is
shown below.

Enter IP address of your Raspberry Pi and fill in a Name. And click OK.
Then on the VNC Viewer panel, double-click new connection you just created, and the following dialog box
pops up. Enter username: pi and Password: raspberry. And click OK.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 91

WiFi

If the resolution ratio is not great or there is just a little window, you can set a proper resolution ratio via
steps below.
sudo raspi-config
Select 7 Advanced OptionsA5 Resolutionproper resolution ratio (set by yourself)OKFinish. And then
reboot Raspberry Pi.

In addition, your VNC Viewer window may zoom your Raspberry Pi desktop. You can change it. On your
VNC View control panel, click right key. And select Properties->Options label->Scaling. Then set proper
scaling.

Step 2 Run commands


If you are using remote desktop mode to login Raspberry Pi, you need use VNC viewer.
Enter the following command in the terminal.

Need support?  [Link]


92 Chapter 7 Smart video car [Link] █

1. Use cd command to enter directory where [Link] is located:


cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Run [Link]:
sudo python [Link]

The interface is as below:

If you don’t like the interface, you can also enter the commands to open the server. It is more convenient.
1. Use cd command to enter directory where [Link] is located:
cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
2. Run [Link]:
sudo python [Link] -t -n
or Run main,py with following command:
sudo python [Link] -tn
“-t” means open TCP communication. “-n“ means don’t show interface.

Sever Auto Start


1 Open the terminal and execute the following two commands respectively to create a “[Link]” file.
cd ~
sudo touch [Link]
2 Open “[Link]”.
sudo nano [Link]

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 93

3 Add the following contents to “[Link]” file.


#!/bin/sh
cd "/home/pi/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server"
pwd
sleep 10
sudo python [Link]
Press Ctrl + O and then press Enter to save it. Press Ctrl+X to exit.

4 Modify permissions.
sudo chmod 777 [Link]
5 Enter the following command to create a directory.
mkdir ~/.config/autostart/
6 create and open “[Link]” file
sudo nano .config/autostart/[Link]
7 Add the following content to “[Link]” file.
[Desktop Entry]
Type=Application
Name=start
NoDisplay=true
Exec=/home/pi/[Link]
Press Ctrl + O and then press Enter to save it. Press Ctrl+X to exit.
8 Modify permissions.
sudo chmod +x .config/autostart/[Link]
9 Finally enter the following content to reboot Raspberry Pi.
sudo reboot
Note: To cancel auto start, please delete the files “[Link]” and “[Link]” created above.

Need support?  [Link]


94 Chapter 7 Smart video car [Link] █

Client

The client connects to the server through TCP, which receives the video stream from the server, and other
commands. And it also sends commands to the server to control the car.
Clients can run on different systems, such as windows, Linux, and so on. However, you need to install related
software and libraries.

The related program is mainly in the [Link] file under the Client folder.
Part of client code is as below:
1 class VideoStreaming:
2 def __init__(self):
3 self.face_cascade = [Link](r'haarcascade_frontalface_default.xml')
4 self.video_Flag=True
5 self.connect_Flag=False
6 self.face_x=0
7 self.face_y=0
8 def StartTcpClient(self,IP):
9 self.client_socket1 = [Link](socket.AF_INET, socket.SOCK_STREAM)
10 self.client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
11 def StopTcpcClient(self):
12 try:
13 self.client_socket.shutdown(2)
14 self.client_socket1.shutdown(2)
15 self.client_socket.close()
16 self.client_socket1.close()
17 except:
18 pass
19
20 def IsValidImage4Bytes(self,buf):
21 bValid = True
22 if buf[6:10] in (b'JFIF', b'Exif'):
23 if not [Link](b'\0\r\n').endswith(b'\xff\xd9'):
24 bValid = False
25 else:
26 try:
27 [Link]([Link](buf)).verify()
28 except:
29 bValid = False
30 return bValid
31
32 def face_detect(self,img):
33 if [Link]('win'):
34 gray = [Link](img,cv2.COLOR_BGR2GRAY)

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 95

35 faces = self.face_cascade.detectMultiScale(gray,1.3,5)
36 if len(faces)>0 :
37 for (x,y,w,h) in faces:
38 self.face_x=float(x+w/2.0)
39 self.face_y=float(y+h/2.0)
40 img = [Link](img, (x+w/2,y+h/2), (w+h)/4, (0, 255, 0), 2)
41 else:
42 self.face_x=0
43 self.face_y=0
44 [Link]('[Link]', img)
45
46 def streaming(self,ip):
47 stream_bytes = b' '
48 try:
49 self.client_socket.connect((ip, 8000))
50 [Link] = self.client_socket.makefile('rb')
51 except:
52 #print "command port connect failed"
53 pass
54 while True:
55 try:
56 stream_bytes= [Link](4)
57 leng=[Link]('L', stream_bytes[:4])
58 jpg=[Link](leng[0])
59 if self.IsValidImage4Bytes(jpg):
60 image = [Link]([Link](jpg, dtype=np.uint8),
61 cv2.IMREAD_COLOR)
62 if self.video_Flag:
63 self.face_detect(image)
64 self.video_Flag=False
65 except:
66 break

Need support?  [Link]


96 Chapter 7 Smart video car [Link] █

Run client on windows system

There are two ways to run Client on Windows.


Option 1 Running executable file directly
Find the “[Link]” file in the specified directory, double click it and the Client is opened.

The client interface is shown as below:

After the client opens successfully, you need open the Raspberry Pi and open server first, then enter the IP
address of the Raspberry Pi in the white IP edit box, and then click “Connect” to connect smart car to Raspberry
Pi. After the connection is successful, you can click on the controls on the interface to operate the car.
Note: when Raspberry Pi is shut down, server will be closed. You need open server again the next time.
If pressing forward but the car moves backward, please refer to page 51 to modify the code.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 97

Option 2 Install python3 and some related python libraries to run the client

If you want to modify the client, please follow this section.


This section will be completed in your computer with windows system, not Raspberry Pi.
There are many relevant software and libraries needed to be installed in Windows system, which takes a long
time. At this time, it does not need to run Server or use Raspberry Pi. You can shut down Raspberry Pi first.
After the installation is completed, you need to open Raspberry Pi and server again.

Install python3
Download the installation file:
[Link]

Click Latest Python 3 Release - Python 3.8.1

Choose and download Windows x86 executable installer. After downloading successfully, install it.

Need support?  [Link]


98 Chapter 7 Smart video car [Link] █

Select “Add Python 3.8 to PATH”. You can choose other installation features.

Select all options and click “Next”.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 99

Here, my install location is D. You can also choose other location. Then click “Install”.

Wait installing.

Need support?  [Link]


100 Chapter 7 Smart video car [Link] █

Now, installation is completed.

Install PyQt5、opencv、numpy and other libraries.


If have not download the zip file, do so via:
[Link]
Then unzip it and delete “-master” to rename it to “Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi”.
Then put it into D disk for example.

You can also place it into other disks (like E), but the path in the following command should be modified
accordingly (replace D: by E:).
Press “win + R” and enter cmd, and click ok. Then enter following commands.
1. Enter D disk. (If you put it into E, it should be E:)
D:
2. Enter directory where setup_windows.py is located: (If you put it into E, it should be E:)
cd D:\Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi\Code
3. Run setup_windows.py:
Python3 setup_windows.py

Or enter the unzipped directory Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi\Code\Client.


And double-click setup_client.py or open it with python3.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 101

Installation will take some time. Just wait patiently. For successful installation, it will prompt "All libraries
installed successfully":

If not all installations are successful, it will prompt "Some libraries have not been installed yet. Please run '
Python3 setup_windows.py ' again", then you need to execute the Python3 setup_windows.py command again.
Most of the installation failures are caused by poor networks. You can check your network before installing.

Open client
Press “win + R” and enter cmd, and click ok. Then enter following commands.
1. Enter D disk. If you put it into E, it should be E:
D:
2. Enter directory where [Link] is located:
cd D:\Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi\Code\Client
3. Run [Link]:
python [Link]

Or enter the unzipped directory and enter following directory:


Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi\Code\Client. And double-click [Link] or open it with
python to open the client.

Need support?  [Link]


102 Chapter 7 Smart video car [Link] █

The client interface is shown as below:

After the client opens successfully, you need open the Raspberry Pi and open server first, then enter the IP
address of the Raspberry Pi in the white IP edit box, and then click “Connect” to connect smart car to Raspberry
Pi. After the connection is successful, you can click on the controls on the interface to operate the car.
Note: when Raspberry Pi is shut down, server will be closed. You need open server again the next time.

If pressing forward but the car moves backward, please refer to page 51 to modify the code.

Control
And you can also control the car with following blue keys.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 103

The car has four work modes:


Mode Function
M-Free (Mode1) Free control mode
M-Light (Mode2) Light tracing mode
M-Sonic(Mode3) Ultrasonic obstacle avoidance mode
M-Line (Mode4) Infrared line tracking mode

The following is the corresponding operation of the buttons and keys.


Button on Client Key Action
ForWard W Move
BackWard S Back off
Turn Left A Turn left
Turn Right D Turn right
Left left arrow Turn camera left
Right right arrow Turn camera right
Up up arrow Turn camera up
Down down arrow Turn camera down
Home Home Turn camera back Home
Connect/ Disconnect C On/off Connection
Open Video/ Close Video V On/off Video
Mode 1,2,3,4 Q Switch Mode
Buzzer Space On/off Buzzer
Led 1,2,3,4,5,6,7,8 1,2,3,4,5,6,7,8 On/off Led 1,2,3,4,5,6,7,8
Led_Mode 1,2,3,4 L Switch Led Mode

The function of SliderBar is below:


SliderBar Function
Servo 1,2, SliderBar Servo 1, 2 are used to slightly adjust the
angle. If the servo is not fully centered during
installation, you can slightly tune it via the SliderBar.

Other control information:


Control Function
IP address Edit box Enter IP address of Raspberry Pi
Power box Show power level
R,G,B Edit box Control the color of LED selected.
Button “Ultrasonic“ Show the distance from obstacle.
Button “Light “ Show voltage of two photoresistors.
Button “Tracing-On/Off “ Open and close face tracking

Need support?  [Link]


104 Chapter 7 Smart video car [Link] █

If you don’t want to enter IP address after open the client, you can make some modification as below:
1. Open “Client_Ui.py” under directory “Client”, then find code in the thirty-sixth line from the bottom.
[Link](_translate("Client", "IP address", None))
2. Modify IP address to IP address of your Raspberry Pi. For example, my rpi IP is [Link]. After
modification, it should be as below:
[Link](_translate("Client", "[Link]", None))
Then save and close. And then restart your client. You can see it is modified successfully.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 105

Run client on macOS system

Here take MacOS 10.13 as an example. To run the client on MacOS, you need to install some software and
libraries. At this time, it does not need to run the server or use the Raspberry Pi. So you can turn off the
Raspberry Pi first. After the installation is complete, turn on the Raspberry Pi and run the server. MacOS 10.13
comes with python2, but no python3. However, the programs in this project need run under python3, so you
need to install it first.

Install python3
Download installation package, link: [Link]

If your macOS is 11. Like 11.0, please install python 3.9.

If your macOS is NOT 11, like 10.15, please install python 3.8. If you have

installed python 3.9. You need uninstall it first.

Need support?  [Link]


106 Chapter 7 Smart video car [Link] █

At bottom of the page, click macOS 64-bit installer and download installation package.

Click Continue.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 107

Click Continue

Click Agree.

Need support?  [Link]


108 Chapter 7 Smart video car [Link] █

Click Install. If your computer has a password, enter the password and Install Software.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 109

Now the installation succeeds.

You can find it in Aapplications.

Need support?  [Link]


110 Chapter 7 Smart video car [Link] █

Install PyQt5、opencv、numpy and other libraries


If there is no code for this car in your macOS system device, you can download it via the link below:
[Link]
After downloaded successfully, you can find it under Downloads.

Open the Terminal.

Type following commands in Terminal.


1 Enter “Downloads“, (Where the Car code is located. If your location for it is different, please enter the
location in your device.)
cd Downloads
2 Enter directory where setup_macos.py is located:
cd Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/
3 Run setup_macos.py:
python3 setup_macos.py

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 111

Installation will take some time. Just wait patiently. For successful installation, it will prompt "All libraries
installed successfully":

If not all installations are successful, it will prompt "Some libraries have not been installed yet. Please run
'python3 setup_macos.py' again", then you need to execute the python3 setup_macos.py command again.
Most of the installation failures are caused by poor networks. You can check your network before installing.

If you are using macOS under 11.0, like 10.15. Just skip to “Open client”.

If you are using macOS 11.0 or later version. Please run commands below:
pip3 uninstall PyQt5
pip3 install PyQt5

Need support?  [Link]


112 Chapter 7 Smart video car [Link] █

Open client
Following the previous step, after the installation is completed, you are now in the directory where
setup_macos.py is located.

[Link] following command to enter Client folder.


cd Client/
[Link] following command to run [Link].
python3 [Link]

The control way of Raspberry Pi macOS System client is same with Windows (Control).

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 113

Run client in Raspberry Pi (Linux system)

Install Opencv library


Execute the following commands in the terminal to install Opencv library:
1. Install opencv development environment:
sudo apt-get install -y libopencv-dev python3-opencv
2. Install some tools:
sudo apt-get install -y python3-pil python3-tk

Run client
Enter the following commands at the terminal.
1. Use the cd command to go to the directory where [Link] is located.
cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Client
2. Run [Link]:
sudo python [Link]

The interface is shown below:

Please check whether the camera protective film is torn off.

Need support?  [Link]


114 Chapter 7 Smart video car [Link] █

Troubleshooting

If the car works abnormally, it may be caused by following reasons: Raspberry Pi system is stuck or
batteries have no power.
You need check batteries power indicator or recharge batteries. Make sure batteries have enough power.
When the batteries voltage is less than 7V, the buzzer will make regular sound.
If the batteries are OK, Raspberry Pi system is stuck. You need wait some time to check if the client works. Or
reopen the server and client.
The latest Raspberry Pi official system is not stable. It occasionally is stuck. The old version is more stable.
If the Raspberry Pi system is stuck for a long time, you need reboot Raspberry Pi.
If you have any concerns, please feel free to contact us with pictures:

support@[Link]

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 115

Android and iOS app

You can download and install the Freenove Android app from below:
On Google play:
[Link]
On GitHub:
[Link]
In this github repository, you can find the App instruction ([Link]).

You can download and install the Freenove iPhone ios app by searching freenove in app store.

Open the app and select the car.

Need support?  [Link]


116 Chapter 7 Smart video car [Link] █

Open the server in Raspberry Pi car first. And enter your Pi IP.

Raspberry Pi IP Take photos Buzzer RGB led

Connect

Set

Control Car moving. Control camera angle and postion.


Drag the middle dot to The ring in the middle is use to reset.
anywhere in the area.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 117

Free innovation

If you have any concerns, please feel free to contact us via support@[Link]

If you want to write your own program to control the car, just follow this section. We will teach you how to
program this car.
If you have never learned python before, you can learn some basic knowledge via the link below:
[Link]
First, turned on S1 and S2. Then open Raspberry Pi, right click and create a new folder on the desktop: Test

Need support?  [Link]


118 Chapter 7 Smart video car [Link] █

Open Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server in your Raspberry Pi and copy the


following 8 files into the Test folder we created.

Paste them in Test folder.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 119

Run Thonny Python IDE

Need support?  [Link]


120 Chapter 7 Smart video car [Link] █

Click Save and save it into the Test folder, with name: test_Code.

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 121

Now you can see the file test_Code.py we created.

Then write code in test_Code.py, then click save.

Note: the code and library are written by Python 3. You need execute the code with python 3.

Need support?  [Link]


122 Chapter 7 Smart video car [Link] █

Open the terminal and use the following command to enter the directory where test_Code.py is located:
cd ~/Desktop/Test
Run test_Code.py:
sudo python test_Code.py

Code example

Following are code example for the parts. For more detail, please refer to Module test section.
For more details, please refer to Motor.
1 from Motor import * #import Motor
2 PWM=Motor() #create an object
3 [Link](2000,2000,2000,2000) #Forward
4 [Link](3) #waiting 3 second
5 [Link](0,0,0,0) #Stop

ADC. For more details, please refer to ADC.


1 from ADC import * #import ADC
2 adc=Adc() #create an object
3 Left_IDR=[Link](0) #get value
4 print ("The photoresistor voltage on the left is "+str(Left_IDR)+"V")

LED. For more details, please refer to LED.


1 from Led import * #import Led
2 led=Led() #create an object
3 [Link](0x04,255,255,0) #yellow
4 [Link](0x80,0,255,0) #green
5 [Link](5) #wait 5s
6 [Link]([Link], Color(0,0,0)) #turn off

Need support?  [Link]


█ [Link] Chapter 7 Smart video car 123

Buzzer. For more details, please refer to Buzzer.


1 from Buzzer import * #import Led
2 from Command import COMMAND as cmd #import Led
3 buzzer=Buzzer() #create an object
4 [Link](‘1’) #Start
5 [Link](3) #wait 3s
6 [Link](‘0’) #Stop

Servo. For more details, please refer to Servo.


1 from servo import * #import Led
2 pwm = Servo() #create an object
3 #Servo rotates from 30 degrees to 150 degrees
4 for i in range(30, 150, 1) :
5 [Link]('0', i)
6 [Link](0.01)
7 #Servo rotates from 150 degrees to 0 degrees
8 for i in range(150, 30, -1) :
9 [Link]('0', i)
10 [Link](0.01)

Ultrasonic module. For more details, please refer to Ultrasonic module.


1 from Ultrasonic import * #import Led
2 ultrasonic=Ultrasonic() #create an object
3 data=ultrasonic.get_distance() #Get the value
4 print ("Obstacle distance is "+str(data)+"CM")

These codes can be integrated into one code to achieve your requirement.

Need support?  [Link]


124 What's next? [Link] █

What's next?
Thanks for your reading.

This book is all over here. If you find any mistakes, missions or you have other ideas and questions about
contents of this book or the kit and ect., please feel free to contact us, and we will check and correct it as soon
as possible.

After completing the contents in this book, you can try to reform this smart car, such as purchasing and
installing other Freenove electronic modules, or improving the code to achieve different functions. We will
also try our best to add more new functions and update the code on our github ([Link]

If you want to learn more about Arduino, Raspberry Pi, smart cars, robots and orther interesting products in
science and technology, please continue to focus on our website. We will continue to launch cost-effective,
innovative and exciting products.
[Link]

Thank you again for choosing Freenove products.

Need support?  [Link]

You might also like