SunFounder PiCar-X Kit
(continued from previous page)
if Vilib.detect_obj_parameter['color_n']!=0 and Vilib.detect_obj_parameter[
˓→'color_w']>100:
tts.say("will done")
sleep(0.05)
renew_color_detect()
with lock:
if key != None and key in ('wsad'):
car_move(key)
sleep(0.5)
px.stop()
key = None
elif key == 'space':
tts.say("Look for " + color)
key = None
elif key == 'quit':
_key_t.join()
print("\n\rQuit")
break
sleep(0.05)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
except Exception as e:
print(f"ERROR: {e}")
finally:
Vilib.camera_close()
px.stop()
sleep(.2)
How it works?
To understand the basic logic of this code, you can focus on the following key parts:
1. Initialization and Imports: Import statements at the beginning of the code to understand the libraries being
used.
2. Global Variables: Definitions of global variables, such as color and key, which are used throughout the code
to track the target color and keyboard input.
3. renew_color_detect() : This function selects a random color from a list and sets it as the target color for
detection. It also uses text-to-speech to announce the selected color.
4. key_scan_thread() : This function runs in a separate thread and continuously scans for keyboard input, up-
dating the key variable with the pressed key. It uses a lock for thread-safe access.
5. car_move(key) : This function controls the movement of the PiCar-X based on the keyboard input (key). It
sets the direction and speed of the robot’s movement.
6. main() :The primary function that orchestrates the overall logic of the code. It does the following:
• Initializes the camera and starts displaying the camera feed.
86 Chapter 4. Play with Python