Freenove Product Support and Safety Guide
Freenove Product Support and Safety Guide
About Battery
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 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
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]
Machinery Parts
Transmission Parts
Acrylic Parts
Electronic Parts
Connection board
XH-2.54-5Pin cable x1
Tools
Self-prepared Parts
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
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:
Practicality picture of Raspberry Pi 3 Model B+: Model diagram of Raspberry Pi 3 Model B+:
Practicality picture of Raspberry Pi 1 Model B+: Model diagram of Raspberry Pi 1 Model B+:
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+:
GPIO
Connector Ethernet
Connector
Display
Connector
USB
Power Connector x4
Connector
GPIO
Connector
USB
Connector
Display
Connector
Ethernet
Power Connector
Connector
GPIO
Connector
USB
Display Connector
Connector
Power
Connector
GPIO
Connector
Camera
Connector
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.
For more details about pin definition of GPIO, please refer to [Link]
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:
You can also use the following command to view their correspondence.
gpio readall
Install a System
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
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.
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
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
Raspberry Pi OS
Download OS file
Visit following website to download the OS file.
[Link]
Image option.
Enable SSH.
Configure WiFi and location. Here we set username as pi, password as raspberry
Finally WRITE.
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.
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.
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.
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]
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]
Type the following command. And select Interfacing Options VNC YesOKFinish. Here Raspberry Pi
may need to be restarted, and choose ok. Then open VNC interface.
sudo raspi-config
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.
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 OptionsVNV ResolutionProper resolution ratio (set by yourself)OKFinishYes.
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.
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.
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.
[Link]
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
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
First, execute python to check the default python on your Raspberry Pi. Press Ctrl-Z to exit.
If you want to set python2 as default python in other projects, just repeat the commands above and change
python3 to python2.
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.
Step 2 Configuration
Click
Click
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.
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
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.
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]
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
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
Step 2
M3*30 M3
Screw Nut
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
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.
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.
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.
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
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
M2*10 M1.4*4
Servo0 Camera
Now please refer to Wiring Section to wring ultrasonic sensor and camera frist.
Keep them
vertical
M2*4 screw in servo package
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
Nut M2
Screw
Step 3
Servo 1
Servo 0
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.
Step 3
Step 4
√ ×
Ultrasonic
Use jumper wires F/F to connect ultrasonic module with pins on smart car board.
GND-GND, VCC-5V, ECHO-ECHO, TRIG-TRIG
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]
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.
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
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.
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.
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
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.
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.
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.
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.
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.
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.
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].
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):
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]()
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.
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.
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.
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:
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°.
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.
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.
Reference
get_distance()
This function is used to obtain the distance between ultrasonic module and obstacles in front of it, with unit
CM.
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
√ ×
Step 2
√ ×
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
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.
Run program
If the terminal displays the directory as below, you can directly execute the [Link] command.
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.
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].
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.
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.
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.
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
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
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.
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"
Open Server
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.
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 OptionsA5 Resolutionproper resolution ratio (set by yourself)OKFinish. 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.
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.
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.
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)
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
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.
Option 2 Install python3 and some related python libraries to run the client
Install python3
Download the installation file:
[Link]
Choose and download Windows x86 executable installer. After downloading successfully, install it.
Select “Add Python 3.8 to PATH”. You can choose other installation features.
Here, my install location is D. You can also choose other location. Then click “Install”.
Wait installing.
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
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]
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.
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.
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 NOT 11, like 10.15, please install python 3.8. If you have
At bottom of the page, click macOS 64-bit installer and download installation package.
Click Continue.
Click Continue
Click Agree.
Click Install. If your computer has a password, enter the password and Install Software.
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
Open client
Following the previous step, after the installation is completed, you are now in the directory where
setup_macos.py is located.
The control way of Raspberry Pi macOS System client is same with Windows (Control).
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]
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]
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 server in Raspberry Pi car first. And enter your Pi IP.
Connect
Set
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
Click Save and save it into the Test folder, with name: test_Code.
Note: the code and library are written by Python 3. You need execute the code with python 3.
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
These codes can be integrated into one code to achieve your requirement.
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]