1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| import serial import keyboard import time
SERIAL_PORT = "COM7" BAUD_RATE = 9600 ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
PWM = 30 DIRECTION = { "FORWARD": 1, "BACKWARD": 0 }
def send_command(wheel, direction, speed): """ 向下位机发送控制命令。 :param wheel: 轮子标识符 ('A', 'B', 'C', 'D') :param direction: 方向 (0 或 1) :param speed: 速度 (0-255) """ command = f"{wheel}{direction}{speed:03d}" ser.write((command + "\n").encode()) print(f"Sent: {command}")
def stop_all_motors(): """发送停止所有轮子的命令。""" ser.write("S0000\n".encode()) print("Sent: S0000 (Stop all motors)")
def control_car(): """ 通过键盘控制小车。 W: 前进 S: 后退 A: 左转 D: 右转 Q: 停止 """ global PWM try: print("Use W/A/S/D to control the car, Q to stop, +/- to adjust speed.") while True: if keyboard.is_pressed("w"): send_command("A", DIRECTION["FORWARD"], PWM) send_command("B", DIRECTION["FORWARD"], PWM) send_command("C", DIRECTION["FORWARD"], PWM) send_command("D", DIRECTION["FORWARD"], PWM)
elif keyboard.is_pressed("s"): send_command("A", DIRECTION["BACKWARD"], PWM) send_command("B", DIRECTION["BACKWARD"], PWM) send_command("C", DIRECTION["BACKWARD"], PWM) send_command("D", DIRECTION["BACKWARD"], PWM)
elif keyboard.is_pressed("a"): send_command("A", DIRECTION["BACKWARD"], PWM) send_command("B", DIRECTION["FORWARD"], PWM) send_command("C", DIRECTION["BACKWARD"], PWM) send_command("D", DIRECTION["FORWARD"], PWM)
elif keyboard.is_pressed("d"): send_command("A", DIRECTION["FORWARD"], PWM) send_command("B", DIRECTION["BACKWARD"], PWM) send_command("C", DIRECTION["FORWARD"], PWM) send_command("D", DIRECTION["BACKWARD"], PWM)
elif keyboard.is_pressed("q"): stop_all_motors() time.sleep(0.2)
elif keyboard.is_pressed("+"): PWM = min(255, PWM + 10) print(f"Speed increased to: {PWM}") time.sleep(0.2)
elif keyboard.is_pressed("-"): PWM = max(0, PWM - 10) print(f"Speed decreased to: {PWM}") time.sleep(0.2)
time.sleep(0.1)
except KeyboardInterrupt: print("Program terminated.") stop_all_motors()
if __name__ == "__main__": control_car()
|