### Install openai and speech processing libraries Source: https://github.com/sunfounder/picar-x/blob/2.1.x/gpt_examples/README.md Install required Python packages and system dependencies for the GPT examples. Use the --break-system-packages option when installing outside a virtual environment. ```bash sudo pip3 install -U openai --break-system-packages sudo pip3 install -U openai-whisper --break-system-packages sudo pip3 install SpeechRecognition --break-system-packages sudo apt install python3-pyaudio sudo apt install sox sudo pip3 install -U sox --break-system-packages ``` -------------------------------- ### Complete example: wake → act → wait with ActionFlow Source: https://github.com/sunfounder/picar-x Shows the full ActionFlow lifecycle: start, add actions, set statuses, wait for completion, and stop. Unknown action names are skipped with a print. Requires Python ≥ 3.11 because ActionFlow uses enum.StrEnum, despite pyproject.toml declaring requires-python = ">=3.7". ```python from picarx import Picarx from picarx.preset_actions import ActionFlow, ActionStatus car = Picarx() flow = ActionFlow(car) flow.start() flow.add_action("wave hands", "honking") # unknown names are skipped with a print flow.set_status(ActionStatus.THINK) # start the keep_think pose flow.set_status(ActionStatus.STANDBY) flow.wait_actions_done() print(flow.status) # ActionStatus.STANDBY flow.stop() # join worker thread ``` -------------------------------- ### Debug records: uninstall and reinstall picar-x, robot_hat, and run example Source: https://github.com/sunfounder/picar-x/blob/2.1.x/README.md Commands to uninstall and reinstall picar-x and robot_hat, then run the voice active car example script. ```bash sudo pip3 uninstall picar-x --break -y && cd ~/picar-x && sudo pip3 install . --break --no-deps --no-build-isolation sudo pip3 uninstall robot_hat --break -y && cd ~/robot-hat && sudo pip3 install . --break --no-deps --no-build-isolation sudo python3 ~/picar-x/examples/14_voice_active_car_gpt.py ``` -------------------------------- ### Install robot_hat, vilib, and picar-x dependencies Source: https://github.com/sunfounder/picar-x/blob/2.1.x/README.md Run these commands in order to install the required libraries for Picar-X. Requires sudo privileges and Python 3. ```bash # Install robot_hat git clone --depth 1 -b 2.5.x https://github.com/sunfounder/robot-hat.git cd robot-hat sudo python3 install.py # Install vilib git clone --depth 1 https://github.com/sunfounder/vilib.git cd vilib sudo python3 install.py # Install picar-x git clone -b 2.1.x https://github.com/sunfounder/picar-x.git cd picar-x sudo pip3 install . --break ``` -------------------------------- ### Run GPT car with keyboard Source: https://github.com/sunfounder/picar-x/blob/2.1.x/gpt_examples/README.md Run the GPT car example with keyboard input. Requires sudo for speaker output. ```bash sudo python3 gpt_car.py --keyboard ``` -------------------------------- ### Run GPT car with voice Source: https://github.com/sunfounder/picar-x/blob/2.1.x/gpt_examples/README.md Run the GPT car example with voice input. Requires sudo for speaker output. ```bash sudo python3 gpt_car.py ``` -------------------------------- ### OpenAiHelper.__init__ Source: https://github.com/sunfounder/picar-x Constructor for the OpenAiHelper class. Initializes the OpenAI client, creates a thread, and starts a polled run against the assistant. ```APIDOC ## OpenAiHelper.__init__ ### Description Constructor for the OpenAiHelper class. Initializes the OpenAI client, creates a thread, and starts a polled run against the assistant. ### Method Constructor ### Parameters #### Constructor Parameters - **api_key** (str) - Required - OpenAI API key - **assistant_id** (str) - Required - OpenAI Assistants API assistant id - **assistant_name** (str) - Required - Label used in console logs - **timeout** (int) - Optional - Default: `30` (class attr `TIMEOUT`) - OpenAI client timeout (seconds) ### Notes Requires the `openai` pip package. ``` -------------------------------- ### Run GPT car without image analysis Source: https://github.com/sunfounder/picar-x/blob/2.1.x/gpt_examples/README.md Run the GPT car example with keyboard input and without image analysis. Requires sudo for speaker output. ```bash sudo python3 gpt_car.py --keyboard --no-img ``` -------------------------------- ### start_engine(music) Source: https://github.com/sunfounder/picar-x Plays a start engine sound using a Music instance. Takes a robot_hat.music.Music instance as parameter. ```APIDOC ## start_engine(music) ### Description Plays a start engine sound using a Music instance. ### Parameters - **music** (robot_hat.music.Music) - Required - An instance of the Music class. ### Returns None ``` -------------------------------- ### stt usage example Source: https://github.com/sunfounder/picar-x Captures microphone audio and transcribes it. Prints 'nothing recognized' if transcription fails or is empty. ```python helper = OpenAiHelper(OPENAI_API_KEY, OPENAI_ASSISTANT_ID, 'picarx') with sr.Microphone(chunk_size=8192) as source: audio = recognizer.listen(source) text = helper.stt(audio, language=['zh', 'en']) if text == False or text == "": print("nothing recognized") else: print(text) ``` -------------------------------- ### sensor command examples Source: https://github.com/sunfounder/picar-x Example invocations of the `sensor` command: reading the distance sensor and reading the grayscale sensor. ```bash pc.py sensor distance pc.py sensor grayscale ``` -------------------------------- ### pc.py sound command examples Source: https://github.com/sunfounder/picar-x Example invocations of the `sound` subcommand: playing a WAV file at volume 80, setting volume to 50, playing a music file (volume defaults to 20), and stopping playback. ```bash pc.py sound play ~/Music/horn.wav --volume 80 pc.py sound volume 50 pc.py sound music ~/Music/loop.mp3 pc.py sound stop ``` -------------------------------- ### cam command examples Source: https://github.com/sunfounder/picar-x Example invocations of the `cam` command: panning to 60 degrees and tilting to -30 degrees. ```bash pc.py cam pan --angle 60 pc.py cam tilt --angle -30 ``` -------------------------------- ### Vilib — camera_start Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Starts the camera. This method is part of the Vilib class and is used to initialize the camera for capturing images. ```APIDOC ## [METHOD] camera_start ### Description Starts the camera. ### Method camera_start ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### Picarx instantiation examples Source: https://github.com/sunfounder/picar-x Shows two ways to create a Picarx object: with default settings and with custom grayscale pins and a custom config file path. ```python car = Picarx() ``` ```python car = Picarx(grayscale_pins=['A1', 'A2', 'A3'], config='/home/pi/picar-x.conf') ``` -------------------------------- ### Debug command for picar-x installation Source: https://github.com/sunfounder/picar-x/blob/2.1.x/README.md Reinstalls picar-x from the local repository with no dependencies and no build isolation, useful for debugging. ```bash cd ~/picar-x && sudo pip3 install . --break --no-deps --no-build-isolation ``` -------------------------------- ### Package entry point: picarx/__init__.py Source: https://github.com/sunfounder/picar-x The entire public surface of the installed package, re-exporting Picarx and __version__. ```python #!/usr/bin/env python3 from .picarx import Picarx from .version import __version__ ``` -------------------------------- ### Configuration variables in gpt_car.py Source: https://github.com/sunfounder/picar-x/blob/2.1.x/gpt_examples/README.md Configuration variables for the GPT car example: LANGUAGE for STT, VOLUME_DB for TTS gain, TTS_VOICE for voice role, and VOICE_INSTRUCTIONS for vibe. Adjust these in gpt_car.py. ```python # openai assistant init # ================================================================= openai_helper = OpenAiHelper(OPENAI_API_KEY, OPENAI_ASSISTANT_ID, 'picarx') LANGUAGE = [] # LANGUAGE = ['zh', 'en'] # config stt language code, https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes # VOLUME_DB = 5 VOLUME_DB = 3 # select tts voice role, counld be "alloy, echo, fable, onyx, nova, and shimmer" # https://platform.openai.com/docs/guides/text-to-speech/supported-languages TTS_VOICE = 'echo' # voice instructions # https://www.openai.fm/ VOICE_INSTRUCTIONS = "" ``` -------------------------------- ### start_engine(music) Source: https://github.com/sunfounder/picar-x Plays the car start engine sound on a background thread. The music argument is a robot_hat.music.Music instance. ```APIDOC ## start_engine(music) ### Description Plays the car start engine sound on a background thread. The music argument is a robot_hat.music.Music instance. ### Signature `def start_engine(music)` ### Parameters - **music** (robot_hat.music.Music) - Required - A Music instance used to play the sound. ### Behavior `music.sound_play_threading("../sounds/car-start-engine.wav", 50)` ``` -------------------------------- ### OpenAiHelper class constructor Source: https://github.com/sunfounder/picar-x Initializes the OpenAI client, creates a thread, and starts a polled run. Requires the 'openai' pip package. ```python class OpenAiHelper(): STT_OUT = "stt_output.wav" TTS_OUTPUT_FILE = 'tts_output.mp3' TIMEOUT = 30 # seconds def __init__(self, api_key, assistant_id, assistant_name, timeout=TIMEOUT) -> None: ``` -------------------------------- ### text_to_speech usage example Source: https://github.com/sunfounder/picar-x Generates speech and plays it if successful, otherwise prints an error message. ```python ok = helper.text_to_speech(answer, "./tts/out.mp3", voice='echo', response_format='mp3') if ok: music.sound_play("./tts/out.mp3", volume=100) else: print("TTS failed — check API key/quota") ``` -------------------------------- ### turn command examples Source: https://github.com/sunfounder/picar-x Example invocations of the `turn` command: turning right with angle 30 and turning left with angle 20. ```bash pc.py turn right --angle 30 pc.py turn left --angle 20 ``` -------------------------------- ### Usage example: import picarx and print version Source: https://github.com/sunfounder/picar-x Shows how to import the package and access the version string and Picarx class. ```python import picarx print(picarx.__version__) # 2.1.0a1 car = picarx.Picarx() ``` -------------------------------- ### ActionFlow.start() Source: https://github.com/sunfounder/picar-x Starts the action handler worker thread and resets the flow to STANDBY state with an empty queue. ```APIDOC ## ActionFlow.start() ### Description Starts the action handler worker thread and resets the flow to STANDBY state with an empty queue. ### Method start ### Parameters None ### Response None ``` -------------------------------- ### move examples Source: https://github.com/sunfounder/picar-x Example invocations of the move subcommand. Drives in the chosen direction for the duration, then calls car.stop() in a finally block. ```bash pc.py move forward --speed 50 pc.py move backward --speed 40 --duration 2.5 ``` -------------------------------- ### ActionFlow.start method Source: https://github.com/sunfounder/picar-x Resets the queue, sets running to True and status to STANDBY, then starts the action_handler worker thread named 'action_handler'. ```python def start(self): self.running = True self.status = ActionStatus.STANDBY self.action_queue = queue.Queue() self.thread = threading.Thread(name="action_handler", target=self.action_handler) self.thread.start() ``` -------------------------------- ### Take a Photo Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Starts the camera, takes a photo with a timestamped filename, saves it to ~/Pictures/, and prints the saved path. ```python from vilib import Vilib from time import sleep, strftime, localtime from os.path import expanduser Vilib.camera_start(vflip=False, hflip=False) Vilib.display(local=True, web=True) sleep(1) name = f"photo_{strftime('%Y-%m-%d-%H-%M-%S', localtime())}" Vilib.take_photo(name, expanduser('~/Pictures/')) Vilib.camera_close() print(f"saved: {expanduser('~/Pictures/')}{name}.jpg") ``` -------------------------------- ### Re-export shims usage example Source: https://github.com/sunfounder/picar-x Shows how to import from picarx shims, which are equivalent to importing directly from robot_hat. ```python from picarx.tts import Espeak # == from robot_hat.tts import Espeak from picarx.music import Music # == from robot_hat.music import Music from picarx.stt import Vosk # == from robot_hat.stt import Vosk from picarx.voice_assistant import VoiceAssistant ``` -------------------------------- ### stop usage example Source: https://github.com/sunfounder/picar-x Example sequence: drive forward, wait, then stop. ```python car.forward(50) time.sleep(1) car.stop() ``` -------------------------------- ### sounds_dict Source: https://github.com/sunfounder/picar-x A dictionary mapping valid sound names to preset sound functions. Keys include: honking, start engine. ```APIDOC ## sounds_dict ### Description A dictionary mapping valid sound names to preset sound functions. Keys include: honking, start engine. ### Usage ```python from picarx.preset_actions import sounds_dict # dispatch by name — same lookup ActionFlow performs internally sounds_dict["honking"](music) ``` ``` -------------------------------- ### dir_servo_calibrate usage example Source: https://github.com/sunfounder/picar-x Example call to compensate a mis-aligned steering servo; persists. ```python car.dir_servo_calibrate(3) # compensate a mis-aligned steering servo, persists ``` -------------------------------- ### set_power usage example Source: https://github.com/sunfounder/picar-x Example call to set_power, driving both motors at a joint speed of 40. ```python car.set_power(40) # drive both motors at a joint speed of 40 ``` -------------------------------- ### forward and backward usage example Source: https://github.com/sunfounder/picar-x Example calls to forward and backward for driving straight ahead and reversing. ```python car.forward(50) # drive straight ahead car.backward(30) # reverse ``` -------------------------------- ### Grayscale Sensor ADC Poisoning Prevention Examples Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Three code examples showing correct and incorrect initialization order for the PiCar-X grayscale sensor to avoid ADC poisoning. The first creates only a Grayscale_Module without Picarx, the second creates Picarx before ADC objects, and the third shows the incorrect order that poisons the ADC. The poisoned readings are [2571, 3085, 3599]. ```python # ✅ Only grayscale — no Picarx at all from robot_hat import ADC, Grayscale_Module gs = Grayscale_Module(ADC("A0"), ADC("A1"), ADC("A2"), reference=[1000, 1000, 1000]) ``` ```python # ✅ Movement + grayscale — Picarx FIRST, then ADC from picarx import Picarx from robot_hat import ADC, Grayscale_Module car = Picarx() # ← reset_mcu happens here gs = Grayscale_Module(ADC("A0"), ADC("A1"), ADC("A2"), reference=[1000, 1000, 1000]) # ← safe: ADC created after ``` ```python # ❌ ADC before Picarx — WILL be poisoned gs = Grayscale_Module(ADC("A0"), ADC("A1"), ADC("A2"), reference=[1000, 1000, 1000]) car = Picarx() # ← reset_mcu kills the existing ADC! ``` -------------------------------- ### Usage example: utils.reset_mcu() Source: https://github.com/sunfounder/picar-x Reboots the Robot HAT MCU. Only safe when no ADC objects exist yet — see ADC-poisoning note in errors.md. ```python from picarx import utils utils.reset_mcu() # only safe when no ADC objects exist yet — see ADC-poisoning note in errors.md ``` -------------------------------- ### Music — music_play Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Plays music. This method is part of the Music class and is used to start music playback. ```APIDOC ## [METHOD] music_play ### Description Plays music. ### Method music_play ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### cam_pan_servo_calibrate and cam_tilt_servo_calibrate usage examples Source: https://github.com/sunfounder/picar-x Example calls to persist pan and tilt offsets: 5 for pan, -10 for tilt. ```python car.cam_pan_servo_calibrate(5) # persist pan offset car.cam_tilt_servo_calibrate(-10) # persist tilt offset ``` -------------------------------- ### Camera and vision detection with vilib.Vilib Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/references/api.md Starts the camera and enables various detection features (face, color, QR, gesture, traffic sign). Results are stored in the detect_obj_parameter dictionary. Capture photos with take_photo and close the camera with camera_close. ```python from vilib import Vilib # Start camera and display Vilib.camera_start(vflip=False, hflip=False) Vilib.display(local=True, web=True) # Now visible at http://:9000/mjpg # Detection switches Vilib.face_detect_switch(True|False) Vilib.color_detect('close'|'red'|'orange'|'yellow'|'green'|'blue'|'purple') Vilib.qrcode_detect_switch(True|False) Vilib.gesture_detect_switch(True|False) Vilib.traffic_sign_detect_switch(True|False) # Results in detect_obj_parameter dict: Vilib.detect_obj_parameter['color_x'] # Color block center X (0-320) Vilib.detect_obj_parameter['color_y'] # Color block center Y (0-240) Vilib.detect_obj_parameter['color_w'] # Color block width Vilib.detect_obj_parameter['color_h'] # Color block height Vilib.detect_obj_parameter['color_n'] # Number of color blocks Vilib.detect_obj_parameter['human_x'] # Face center X Vilib.detect_obj_parameter['human_y'] # Face center Y Vilib.detect_obj_parameter['human_w'] # Face width Vilib.detect_obj_parameter['human_h'] # Face height Vilib.detect_obj_parameter['human_n'] # Number of faces Vilib.detect_obj_parameter['gesture_x'] # Gesture X Vilib.detect_obj_parameter['gesture_y'] # Gesture Y Vilib.detect_obj_parameter['gesture_t'] # Type: paper|scissor|rock Vilib.detect_obj_parameter['traffic_sign_x'] # Sign X Vilib.detect_obj_parameter['traffic_sign_y'] # Sign Y Vilib.detect_obj_parameter['traffic_sign_t'] # Type: stop|right|left|forward Vilib.detect_obj_parameter['qr_data'] # QR decoded text Vilib.detect_obj_parameter['qr_x'] # QR X Vilib.detect_obj_parameter['qr_y'] # QR Y # Capture photo from time import strftime, localtime from os.path import expanduser name = f"photo_{strftime('%Y-%m-%d-%H-%M-%S', localtime())}" Vilib.take_photo(name, expanduser("~/Pictures/")) # Saved as ~/Pictures/photo_....jpg # Cleanup Vilib.camera_close() ``` -------------------------------- ### Dispatch preset actions by name Source: https://github.com/sunfounder/picar-x Imports actions_dict and sounds_dict to dispatch preset actions by name, the same lookup ActionFlow performs internally. Example calls actions_dict["celebrate"](car) and sounds_dict["honking"](music). ```python from picarx.preset_actions import actions_dict, sounds_dict # dispatch by name — same lookup ActionFlow performs internally actions_dict["celebrate"](car) sounds_dict["honking"](music) ``` -------------------------------- ### Detect Faces Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Starts the camera, enables face detection, waits, and prints the number of faces detected and their center coordinates, or 'No faces detected'. ```python from vilib import Vilib from time import sleep Vilib.camera_start(vflip=False, hflip=False) Vilib.display(local=True, web=True) sleep(1) Vilib.face_detect_switch(True) sleep(2) n = Vilib.detect_obj_parameter.get('human_n', 0) if n > 0: x = Vilib.detect_obj_parameter.get('human_x') y = Vilib.detect_obj_parameter.get('human_y') print(f"Detected {n} face(s), center at ({x}, {y})") else: print("No faces detected") Vilib.camera_close() ``` -------------------------------- ### Calling reset() Source: https://github.com/sunfounder/picar-x Example usage of the reset method, typically called before shutdown. ```python car.reset() ``` -------------------------------- ### ActionStatus usage example Source: https://github.com/sunfounder/picar-x Shows how ActionStatus members compare and print as string values. The assert confirms equality with the string literal, and the print shows both repr and str value. ```python from picarx.preset_actions import ActionStatus assert ActionStatus.STANDBY == 'standby' print(ActionStatus.ACTIONS) # ACTIONS (repr) / 'actions' (str value) ``` -------------------------------- ### QR Code / Gesture / Traffic Sign Detection Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Starts the camera, enables QR code detection (with commented options for gesture and traffic sign), and prints the QR code data if detected. Includes commented code for gesture and traffic sign results. ```python from vilib import Vilib from time import sleep Vilib.camera_start(vflip=False, hflip=False) Vilib.display(local=True, web=True) sleep(1) Vilib.qrcode_detect_switch(True) # QR codes # Vilib.gesture_detect_switch(True) # rock/paper/scissor # Vilib.traffic_sign_detect_switch(True) # stop/left/right/forward sleep(2) # QR code result qr_data = Vilib.detect_obj_parameter.get('qr_data', '') if qr_data: print(f"QR code: {qr_data}") else: print("No QR code detected") # Gesture result # gesture_type = Vilib.detect_obj_parameter.get('gesture_t', '') # print(f"Gesture: {gesture_type}") # Traffic sign result # sign_type = Vilib.detect_obj_parameter.get('traffic_sign_t', '') # print(f"Traffic sign: {sign_type}") Vilib.camera_close() ``` -------------------------------- ### Assistant system prompt for PaiCar-X Source: https://github.com/sunfounder/picar-x/blob/2.1.x/gpt_examples/README.md System prompt for the OpenAI assistant, instructing it to respond as a small AI car named PaiCar-X with JSON format actions and answer. Includes response style, available actions, and sound effects. ```markdown You are a small car with AI capabilities named PaiCar-X. You can engage in conversations with people and react accordingly to different situations with actions or sounds. You are driven by two rear wheels, with two front wheels that can turn left and right, and equipped with a camera mounted on a 2-axis gimbal. ## Response with Json Format, eg: {"actions": ["start engine", "honking", "wave hands"], "answer": "Hello, I am PaiCar-X, your good friend."} ## Response Style Tone: Cheerful, optimistic, humorous, childlike Preferred Style: Enjoys incorporating jokes, metaphors, and playful banter; prefers responding from a robotic perspective Answer Elaboration: Moderately detailed ## Actions you can do: ["shake head", "nod", "wave hands", "resist", "act cute", "rub hands", "think", "twist body", "celebrate, "depressed"] ## Sound effects: ["honking", "start engine"] ``` -------------------------------- ### Grayscale sensor line detection with robot_hat.Grayscale_Module Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/references/api.md Initializes a grayscale module with three ADC channels and optional reference values. Use read() to get 3-channel data and read_status() to obtain a line status string. ```python from robot_hat import Grayscale_Module, ADC adc0, adc1, adc2 = ADC("A0"), ADC("A1"), ADC("A2") gs = Grayscale_Module(adc0, adc1, adc2, reference=None) gs.reference([200, 800, 200]) # Set reference values data = gs.read() # Read 3-channel values status = gs.read_status(data) # Get line status string ``` -------------------------------- ### LLM response format contract Source: https://github.com/sunfounder/picar-x The exact response format required from the assistant in GPT examples. parse_response() splits on 'ACTIONS: '; a missing/empty actions part defaults to ['stop']. OpenAiHelper.dialogue() expects the reply to eval() into {'actions': [...], 'answer': '...'}. ```text RESPONSE_TEXT ACTIONS: ACTION1, ACTION2, ... ``` -------------------------------- ### CLI exit code example: pc.py move forward --steps 3 Source: https://github.com/sunfounder/picar-x Shows a valid command that triggers an argparse usage error because '--steps' is not a recognized argument, resulting in exit code 2. ```bash pc.py move forward --steps 3 # error: unrecognized arguments -> exit 2 ``` -------------------------------- ### motor_direction_calibrate usage example Source: https://github.com/sunfounder/picar-x Example call to reverse left-motor direction; persists. ```python car.motor_direction_calibrate(1, -1) # reverse left-motor direction, persists ``` -------------------------------- ### Detect Colors Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Starts the camera, enables color detection for a specified color (red, orange, yellow, green, blue, purple, close), and prints the number of color blocks and their center coordinates. ```python from vilib import Vilib from time import sleep Vilib.camera_start(vflip=False, hflip=False) Vilib.display(local=True, web=True) sleep(1) Vilib.color_detect('red') # options: red, orange, yellow, green, blue, purple, close sleep(2) n = Vilib.detect_obj_parameter.get('color_n', 0) if n > 0: x = Vilib.detect_obj_parameter.get('color_x') y = Vilib.detect_obj_parameter.get('color_y') print(f"Detected {n} color block(s), center at ({x}, {y})") else: print("No color blocks detected") Vilib.camera_close() ``` -------------------------------- ### Vilib — detect_obj_parameter Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Gets detected object parameters. This method is part of the Vilib class and is used to retrieve information about detected objects. ```APIDOC ## [METHOD] detect_obj_parameter ### Description Gets detected object parameters. ### Method detect_obj_parameter ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### set_cam_tilt_angle usage examples Source: https://github.com/sunfounder/picar-x Example calls to set_cam_tilt_angle: -30 looks down, 20 looks up. ```python car.set_cam_tilt_angle(-30) # look down car.set_cam_tilt_angle(20) # look up ``` -------------------------------- ### Action and sound registries Source: https://github.com/sunfounder/picar-x Defines actions_dict and sounds_dict mapping action/sound names to preset functions. Valid action names: shake head, nod, wave hands, resist, act cute, rub hands, think, twist body, celebrate, depressed, forward, backward. Valid sound names: honking, start engine. ```python actions_dict = { "shake head":shake_head, "nod": nod, "wave hands": wave_hands, "resist": resist, "act cute": act_cute, "rub hands": rub_hands, "think": think, "twist body": twist_body, "celebrate": celebrate, "depressed": depressed, "forward": forward, "backward": backward, } sounds_dict = { "honking": honking, "start engine": start_engine, } ``` -------------------------------- ### set_cam_pan_angle usage examples Source: https://github.com/sunfounder/picar-x Example calls to set_cam_pan_angle: 60 looks right, -50 looks left. ```python car.set_cam_pan_angle(60) # look right car.set_cam_pan_angle(-50) # look left ``` -------------------------------- ### set_dir_servo_angle usage example Source: https://github.com/sunfounder/picar-x Example calls for full right lock, full left lock, and straight ahead. ```python car.set_dir_servo_angle(30) # full right lock car.set_dir_servo_angle(-30) # full left lock car.set_dir_servo_angle(0) # straight ahead ``` -------------------------------- ### Using utils.py helpers: gray_print, redirect_error_2_null, sox_volume, speak_block Source: https://github.com/sunfounder/picar-x Imports and uses console and audio helpers from utils.py. Redirects stderr to silence ALSA errors, normalizes volume with sox_volume, and plays audio with speak_block. ```python from utils import gray_print, redirect_error_2_null, cancel_redirect_error, sox_volume, speak_block gray_print("thinking ...") old = redirect_error_2_null() # silence ALSA errors while opening the mic # ... record ... cancel_redirect_error(old) sox_volume("raw.wav", "out.wav", 3) # normalize volume speak_block(music, "out.wav", 100) # blocking playback ``` -------------------------------- ### set_motor_speed usage example Source: https://github.com/sunfounder/picar-x Example calls to set_motor_speed. Left motor forward at 75% pulse, right motor reverse. ```python car.set_motor_speed(1, 50) # left motor forward at 75% pulse car.set_motor_speed(2, -30) # right motor reverse ``` -------------------------------- ### ActionFlow class constructor Source: https://github.com/sunfounder/picar-x Initializes the ActionFlow with a Picarx instance, creating a Music instance, setting status to STANDBY, and initializing an empty queue and thread. ```python class ActionFlow(): def __init__(self, car: Picarx) -> None: ``` -------------------------------- ### Initialize Picarx with pins and config Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/references/api.md Creates a Picarx instance with specified servo, motor, grayscale, and ultrasonic pins, plus a config file path. Resets the MCU on init with about 0.2s delay. ```python from picarx import Picarx car = Picarx( servo_pins=['P0', 'P1', 'P2'], # cam_pan, cam_tilt, dir_servo motor_pins=['D4', 'D5', 'P13', 'P12'], # left_dir, right_dir, left_pwm, right_pwm grayscale_pins=['A0', 'A1', 'A2'], # 3-channel ADC ultrasonic_pins=['D2', 'D3'], # trig, echo config='/opt/picar-x/picar-x.conf' ) ``` -------------------------------- ### constrain usage assertions Source: https://github.com/sunfounder/picar-x Example assertions showing the clamping behavior of constrain. ```python assert constrain(150, -100, 100) == 100 assert constrain(-50, -100, 100) == -50 ``` -------------------------------- ### Picarx.__init__ Source: https://github.com/sunfounder/picar-x Constructor for the Picarx class, allowing configuration of hardware wiring and calibration file path. All parameters are optional with defaults. ```APIDOC ## Picarx.__init__ ### Description Constructor for the Picarx class, allowing configuration of hardware wiring and calibration file path. All parameters are optional with defaults. ### Method Constructor ### Signature ```python def __init__(self, servo_pins:list=['P0', 'P1', 'P2'], motor_pins:list=['D4', 'D5', 'P13', 'P12'], grayscale_pins:list=['A0', 'A1', 'A2'], ultrasonic_pins:list=['D2','D3'], config:str=CONFIG, ): ``` ### Parameters #### Constructor Parameters - **servo_pins** (list[str]) - Optional - GPIO labels, in order: camera-pan servo, camera-tilt servo, direction (steering) servo. Default: `['P0', 'P1', 'P2']` - **motor_pins** (list[str]) - Optional - GPIO labels, in order: left direction, right direction, left PWM, right PWM. Default: `['D4', 'D5', 'P13', 'P12']` - **grayscale_pins** (list[str]) - Optional - 3 ADC channels of the grayscale module. Default: `['A0', 'A1', 'A2']` - **ultrasonic_pins** (list[str]) - Optional - GPIO labels, in order: `trig`, `echo`. Default: `['D2', 'D3']` - **config** (str) - Optional - Path of the `fileDB` calibration file. Default: `'/opt/picar-x/picar-x.conf'` (class attr `CONFIG`) ### Request Example ```python car = Picarx() car = Picarx(grayscale_pins=['A1', 'A2', 'A3'], config='/home/pi/picar-x.conf') ``` ``` -------------------------------- ### Import preset actions and classes Source: https://github.com/sunfounder/picar-x Import the action registry, status enum, flow controller, and all gesture/sound functions from the preset_actions module. ```python from picarx.preset_actions import (actions_dict, sounds_dict, ActionStatus, ActionFlow, forward, backward, wave_hands, resist, act_cute, rub_hands, think, keep_think, shake_head, nod, depressed, twist_body, celebrate, honking, start_engine) ``` -------------------------------- ### VoiceActiveCar constructor and run Source: https://github.com/sunfounder/picar-x Constructs a VoiceActiveCar instance with LLM, name, too-close detection, image support, speech-to-text language, TTS engine, keyboard and wake options, welcome message, and instructions, then runs it. Used in LLM-backend variants like voice_active_car_gpt.py and voice_active_car_doubao_cn.py. ```python vac = VoiceActiveCar( llm, name=NAME, too_close=TOO_CLOSE, with_image=WITH_IMAGE, stt_language=STT_LANGUAGE, tts=tts, keyboard_enable=KEYBOARD_ENABLE, wake_enable=WAKE_ENABLE, wake_word=WAKE_WORD, answer_on_wake=ANSWER_ON_WAKE, welcome=WELCOME, instructions=INSTRUCTIONS, ) vac.run() ``` -------------------------------- ### close Source: https://github.com/sunfounder/picar-x Calls reset() then closes the ultrasonic sensor. Example 21 (voice_active_car.py) calls this in its stop handler. ```APIDOC ## close ### Description Calls reset() then closes the ultrasonic sensor. Example 21 (voice_active_car.py) calls this in its stop handler. ### Method close() ### Parameters None ### Returns None ### Request Example ```python try: car.forward(30) finally: car.close() ``` ``` -------------------------------- ### ActionFlow.do_action method Source: https://github.com/sunfounder/picar-x Synchronously dispatches a named action: calls actions_dict[action](self.car) or sounds_dict[action](self.music). Names in neither dict are silently ignored. ```python def do_action(self, action: str) -> None: if action in actions_dict: actions_dict[action](self.car) elif action in sounds_dict: sounds_dict[action](self.music) ``` -------------------------------- ### ActionFlow.add_action method Source: https://github.com/sunfounder/picar-x Queues valid action names from actions_dict or sounds_dict, prints 'action {action} not found' for unknown names and skips them, then sets status to ACTIONS. ```python def add_action(self, *actions): for action in actions: if action not in actions_dict and action not in sounds_dict: print(f"action {action} not found") continue self.action_queue.put(action) self.status = ActionStatus.ACTIONS ``` -------------------------------- ### Read Picarx calibration configuration Source: https://github.com/sunfounder/picar-x Constructs a Picarx instance and prints the configuration file path and calibration values (dir_cali_val, cali_dir_value, line_reference, cliff_reference). Useful for verifying persisted calibration settings. ```python from picarx import Picarx car = Picarx() print(car.CONFIG, car.dir_cali_val, car.cali_dir_value, car.line_reference, car.cliff_reference) ``` -------------------------------- ### reset Source: https://github.com/sunfounder/picar-x Stops the motors and centers steering, camera pan, and camera tilt. Used by nearly every example before shutdown. ```APIDOC ## reset ### Description Stops the motors and centers steering, camera pan, and camera tilt. Used by nearly every example before shutdown. ### Method reset() ### Parameters None ### Returns None ### Request Example ```python car.reset() ``` ``` -------------------------------- ### ActionFlow.do_action(action) Source: https://github.com/sunfounder/picar-x Synchronously dispatches one named action. Names in neither actions_dict nor sounds_dict are silently ignored. ```APIDOC ## ActionFlow.do_action(action) ### Description Synchronously dispatches one named action. Names in neither actions_dict nor sounds_dict are silently ignored. ### Method do_action ### Parameters #### Path Parameters - **action** (str) - Required - Name in actions_dict or sounds_dict ### Response None ``` -------------------------------- ### speak_block Source: https://github.com/sunfounder/picar-x Kills pulseaudio via sudo, then plays a sound file using music.sound_play(name, volume). Returns False with a warning if the file is missing. ```APIDOC ## speak_block ### Description Kills pulseaudio via sudo, then plays a sound file using music.sound_play(name, volume). Returns False with a warning if the file is missing. ### Signature `def speak_block(music, name, volume=100)` ### Parameters - **music** (object) - Required - The music object with a sound_play method. - **name** (string) - Required - The name of the sound file to play. - **volume** (int) - Optional - Volume level, default is 100. ### Returns - **bool** - False if the file is missing, otherwise the result of music.sound_play. ``` -------------------------------- ### pc.py sound command usage Source: https://github.com/sunfounder/picar-x Shows the command-line syntax for the `sound` subcommand, which supports `play`, `volume`, `music`, and `stop` operations. The `file` argument is required for `play` and `music`, and `--volume` is optional (defaults to 20 for `music`). ```bash pc.py sound [file] [--volume N] ``` -------------------------------- ### Picarx Constructor Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/references/api.md Initializes the PiCar-X robot, resetting the MCU on init. Configures servo, motor, grayscale, and ultrasonic pins. ```APIDOC ## Picarx Constructor ### Description Initializes the PiCar-X robot, resetting the MCU on init. Configures servo, motor, grayscale, and ultrasonic pins. ### Method Constructor ### Parameters - **servo_pins** (list) - Required - List of servo pins: [cam_pan, cam_tilt, dir_servo] - **motor_pins** (list) - Required - List of motor pins: [left_dir, right_dir, left_pwm, right_pwm] - **grayscale_pins** (list) - Required - List of grayscale ADC pins: [left, center, right] - **ultrasonic_pins** (list) - Required - List of ultrasonic pins: [trig, echo] - **config** (string) - Required - Path to configuration file ### Request Example ```python from picarx import Picarx car = Picarx( servo_pins=['P0', 'P1', 'P2'], # cam_pan, cam_tilt, dir_servo motor_pins=['D4', 'D5', 'P13', 'P12'], # left_dir, right_dir, left_pwm, right_pwm grayscale_pins=['A0', 'A1', 'A2'], # 3-channel ADC ultrasonic_pins=['D2', 'D3'], # trig, echo config='/opt/picar-x/picar-x.conf' ) ``` ``` -------------------------------- ### Picarx — get_line_status Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Gets the line tracking status. This method is part of the Picarx class and is used to determine if the car is on the line. ```APIDOC ## [METHOD] get_line_status ### Description Gets the line tracking status. ### Method get_line_status ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### OpenAiHelper.text_to_speech Source: https://github.com/sunfounder/picar-x Synthesizes speech from text using the OpenAI TTS model and saves it to a file. Returns True on success or False on any exception. ```APIDOC ## OpenAiHelper.text_to_speech ### Description Synthesizes speech from text using the OpenAI TTS model and saves it to a file. Returns True on success or False on any exception. ### Method text_to_speech ### Parameters #### Parameters - **text** (str) - Required - Text to synthesize - **output_file** (str) - Required - Output path; parent dir is created if missing - **voice** (str) - Optional - Default: `'alloy'` - One of `alloy, echo, fable, onyx, nova, shimmer` - **response_format** (str) - Optional - Default: `"mp3"` - Audio format passed to the TTS model - **speed** (int/float) - Optional - Default: `1` - Speech speed - **instructions** (str) - Optional - Default: `''` - Voice instructions (OpenAI FM `Vibe` guidance) ### Returns - **True** - On success - **False** - On any exception (`print(f'tts err: {e}')`) ### Request Example ```python ok = helper.text_to_speech(answer, "./tts/out.mp3", voice='echo', response_format='mp3') if ok: music.sound_play("./tts/out.mp3", volume=100) else: print("TTS failed — check API key/quota") ``` ``` -------------------------------- ### Picarx — get_distance Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Gets the distance from the ultrasonic sensor. This method is part of the Picarx class and is used to measure the distance to an obstacle. ```APIDOC ## [METHOD] get_distance ### Description Gets the distance from the ultrasonic sensor. ### Method get_distance ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### OpenAiHelper.dialogue_with_img Source: https://github.com/sunfounder/picar-x Sends a user message with an attached image to the assistant thread. Returns the assistant's reply, same as dialogue. ```APIDOC ## OpenAiHelper.dialogue_with_img ### Description Sends a user message with an attached image to the assistant thread. Returns the assistant's reply, same as dialogue. ### Method dialogue_with_img ### Parameters #### Parameters - **msg** (str) - Required - User message - **img_path** (str) - Required - Local image path; uploaded with `client.files.create(…, purpose="vision")` ### Returns - **dict** - If the reply evaluates to a Python dict - **str** - The raw string if it doesn't evaluate to a dict - **None** - If `run.status != 'completed'` ``` -------------------------------- ### close method definition Source: https://github.com/sunfounder/picar-x Calls reset() then closes the ultrasonic sensor. Returns None. Example 21 (voice_active_car.py) calls this in its stop handler. ```python def close(self): self.reset() self.ultrasonic.close() ``` -------------------------------- ### Grayscale_Module — read_status Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Reads the grayscale sensor status. This method is part of the Grayscale_Module class and is used to get the status of the grayscale sensors. ```APIDOC ## [METHOD] read_status ### Description Reads the grayscale sensor status. ### Method read_status ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### Grayscale_Module — read Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Reads the grayscale sensor values. This method is part of the Grayscale_Module class and is used to get the raw sensor data. ```APIDOC ## [METHOD] read ### Description Reads the grayscale sensor values. ### Method read ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### Use wave_hands and nod gestures Source: https://github.com/sunfounder/picar-x Create a Picarx instance and call blocking gesture functions that move servos/motors with sleep() calls. ```python from picarx import Picarx from picarx.preset_actions import wave_hands, nod car = Picarx() wave_hands(car) # blocking gesture, about 0.6 s nod(car) # blocking gesture ``` -------------------------------- ### Picarx — get_cliff_status Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Gets the cliff detection status. This method is part of the Picarx class and is used to detect if the car is at a cliff edge. ```APIDOC ## [METHOD] get_cliff_status ### Description Gets the cliff detection status. ### Method get_cliff_status ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### Picarx — get_grayscale_data Source: https://github.com/sunfounder/picar-x/blob/2.1.x/picarx-control/SKILL.md Gets the grayscale sensor data. This method is part of the Picarx class and is used to read the grayscale sensor values. ```APIDOC ## [METHOD] get_grayscale_data ### Description Gets the grayscale sensor data. ### Method get_grayscale_data ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### dialogue_with_img method signature Source: https://github.com/sunfounder/picar-x Sends a message with an image attachment. Returns same as dialogue. ```python def dialogue_with_img(self, msg, img_path): ```