#!/usr/bin/env python3import evdevfrom ev3dev2.motor import LargeMotor, MediumMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, SpeedPercentfrom ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3from ev3dev2.sensor.lego import SoundSensor, ColorSensor, UltrasonicSensorfrom time import sleep
# Motorsleft_motor = LargeMotor(OUTPUT_B)right_motor = LargeMotor(OUTPUT_C)claw_motor = MediumMotor(OUTPUT_A)
# Sensorsmic = SoundSensor(INPUT_1)color = ColorSensor(INPUT_2)ultra = UltrasonicSensor(INPUT_3)
# Find PS4 controllerdevices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]controller = Nonefor device in devices: if 'Wireless Controller' in device.name: controller = device break
if not controller: print("No PS4 controller found. Make sure it’s paired via Bluetooth.") exit(1)
print("PS4 controller connected:", controller.name)
# Event codes for PS4AXIS_LY = 1 # Left stick YAXIS_RX = 3 # Right stick XBTN_X = 304 # Cross (X)BTN_O = 305 # Circle (O)
# Control variablesspeed_left = 0speed_right = 0claw_open = False
for event in controller.read_loop(): if event.type == evdev.ecodes.EV_ABS: # Joysticks if event.code == AXIS_LY: # Normalize from -32768..32767 to -100..100 val = -event.value / 32767 * 100 speed_left = val speed_right = val elif event.code == AXIS_RX: val = event.value / 32767 * 50 # Turning factor speed_left += -val speed_right += val
left_motor.on(SpeedPercent(int(speed_left))) right_motor.on(SpeedPercent(int(speed_right)))
elif event.type == evdev.ecodes.EV_KEY: # Buttons if event.code == BTN_X and event.value == 1: # Press X print("Open claw") claw_motor.on_for_seconds(SpeedPercent(50), 1) elif event.code == BTN_O and event.value == 1: # Press O print("Close claw") claw_motor.on_for_seconds(SpeedPercent(-50), 1)
# Print sensors periodically print("Sound:", mic.sound, "Color:", color.color, "Distance:", ultra.distance_centimeters) sleep(0.1)
[Enter code here]