Chapter 4 Light tracing Car
If you have any concerns, please feel free to contact us via support@freenove.com
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 Light.py command.
If not, execute the cd command:
$ cd ~/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server
Run Light.py:
$ sudo python car.py Light
The code is below:
1from ultrasonic import Ultrasonic
2from motor import Ordinary_Car
3from servo import Servo
4from infrared import Infrared
5from adc import ADC
6import time
7import math
8
9class Car:
10 def mode_light(self):
11 if (time.time() - self.car_record_time) > 0.2:
12 self.car_record_time = time.time()
13 self.motor.set_motor_model(0,0,0,0)
14 L = self.adc.read_adc(0)
15 R = self.adc.read_adc(1)
16 #print("L: {}, R: {}".format(L, R))
17 if L < 2.99 and R < 2.99 :
18 self.motor.set_motor_model(600,600,600,600)
19 elif abs(L-R)<0.15:
20 self.motor.set_motor_model(0,0,0,0)
21 elif L > 3 or R > 3:
22 if L > R :
23 self.motor.set_motor_model(-1200,-1200,1400,1400)
24 elif R > L :
25 self.motor.set_motor_model(1400,1400,-1200,-1200)
26def test_car_light():
27 car = Car()
28 try:
29 print("Program is starting...")
30 while True:
31 car.mode_light()
32 except KeyboardInterrupt:
33 car.close()
34 print("\nEnd of program")
35if __name__ == '__main__':
36 import sys
37 if len(sys.argv) < 2:
38 print("Parameter error: Please assign the device")
39 exit()
40 elif sys.argv[1] == 'Light' or sys.argv[1] == 'light':
41 test_car_light()
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.