Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8051

Python • Re: Using Multiple Bluetooth devices with RPi 5 and python

$
0
0
Awesome! Very much appreciated!! Based on your suggestions I changed the "time.sleep(0.05)" to "time.sleep(0.4)" and now it is working a lot closer to my intent. The issue I have to overcome now is if I hold the joystick in a position for a bit of time and then let it return to neutral, the "speak" function repeats the the associated "saying" a number of times. I need to have it not repeat the text if the joystick's state hasn't changed.
However, I'm very pleased to have it working as it is currently, PROGRESS! Below is the current code.

Code:

#!/usr/bin/env python3import pygameimport subprocessimport boardimport queueimport threadingimport timeimport sysimport EYESfrom adafruit_ht16k33 import matrix# Create the I2C interface.i2c = board.I2C()matrix = matrix.Matrix8x8(i2c)matrix.brightness = 0.90# Clear the matrix initiallymatrix.fill(0)matrix.show()# --- Configuration ---# Threshold to ignore small stick movements (deadzone)DEADZONE = 0.05# --- End Configuration ---queue_speak = queue.Queue()def speak(text, speed=120, pitch=20, voice="en-us+m7"):    queue_speak.put({ "text": text,                      "speed": speed,                      "pitch": pitch,                      "voice": voice})    def speak_runner():    while True:        try:            e = queue_speak.get(block=True)        except queue.Empty:            continue         try:            command = [                "espeak-ng",                f"-s{e['speed']}",                f"-p{e['pitch']}",                f"-v{e['voice']}",                e['text']            ]            subprocess.run(command, check=True)        except subprocess.CalledProcessError as e:            print(f"Error speaking: {e}")        except FileNotFoundError:            print("espeak-ng command not found")   def draw_eye(pattern):    for y in range(8):        for x in range(8):            matrix[x, y] = pattern[y][x]    matrix.show()    def mix_joystick_inputs(axis4, axis3):    """    MIxes two joystick axes for tank-style steering (e.g., throttle/yaw)    Returns: (left_motor, right_motor)    """    # Aplly Deadzone    if abs(axis4) < DEADZONE: axis4 = 0    if abs(axis3) < DEADZONE: axis3 = 0        # Mixing Algorithm (Tank Drive)    # axis3: Forward/Backward (Throttle)    # axis2: Left/Right (Steering)    left = axis4 + axis3    right = axis4 - axis3        # Normalize values to be within -1.0 to 1.0 range    left = max(-1.0, min(1.0, left))    right = max(-1.0, min(1.0, right))        return left, rightpygame.init()pygame.joystick.init()# Check for joysticksif pygame.joystick.get_count() == 0:   print("No joystick detected.")   #return    # Initialize the first joystickjoystick = pygame.joystick.Joystick(0)joystick.init()print(f"Detected joystick: {joystick.get_name()}")time.sleep(1)if __name__ == "__main__":    thread_speak = threading.Thread(target=speak_runner)    thread_speak.start()            speak(' Ready For Testing.')    time.sleep(2.0)    try:        while True:            pygame.event.pump() # Process event queue                            # Axis 4 is Steering, Axis 3 is Throttle            # Note: Pygame axes are usually -1.0 to 1.0            steering = joystick.get_axis(3)            throttle = -joystick.get_axis(4) #Invert if forward is negative                            left_motor, right_motor = mix_joystick_inputs(throttle, steering)                            #Print mixed values (or send to motor controller)            #print(f"L:{left_motor:.2f} R:{right_motor:.2f}")                            time.sleep(0.4) # Small delay for readable output                        leftM = left_motor * 30            rghtM = right_motor * 30                                if leftM < 0 and rghtM < 0:                speak(' Backing Up. ')                draw_eye(EYES.BLINK)                #time.sleep(0.2)                        elif leftM < 0 and rghtM > 0:                speak(' Turning Left.')                draw_eye(EYES.LEFT2)                #time.sleep(0.2)                        elif leftM > 0 and rghtM < 0:                speak(' Turning Right. ')                draw_eye(EYES.RIGHT2)                #time.sleep(0.2)                            else:                draw_eye(EYES.STRGHT)                                      except KeyboardInterrupt:        print("Close serial communication.")        #ser.close()        matrix.fill(0)        matrix.show()        sys.exit() Thank You!!

Statistics: Posted by briank1179 — Sat Feb 28, 2026 10:45 pm



Viewing all articles
Browse latest Browse all 8051

Trending Articles