diff --git a/ch-11/1-measuring-wheel-speeds/code.py b/ch-11/1-measuring-wheel-speeds/code.py index fa7e5e7..5a55df4 100644 --- a/ch-11/1-measuring-wheel-speeds/code.py +++ b/ch-11/1-measuring-wheel-speeds/code.py @@ -14,7 +14,7 @@ async def motor_speed_loop(): left_last = left_new right_speed = robot.ticks_to_m * (right_new - right_last) / Settings.time_interval right_last = right_new - robot.uart.write(f"{left_speed:.3f},{right_speed:.3f},0\n".encode()) + robot.send_line(f"{left_speed:.2f},{right_speed:.2f},0") async def stop_motors_after(seconds): await asyncio.sleep(seconds) @@ -28,21 +28,22 @@ async def command_handler(): Settings.speed = float(command[1:]) elif command.startswith("T"): Settings.time_interval = float(command[1:]) - elif command == "O": + elif command == "G": robot.stop() - elif command.startswith("O"): + elif command.startswith("G"): await asyncio.sleep(5) asyncio.create_task(stop_motors_after(float(command[1:]))) robot.set_left(Settings.speed) robot.set_right(Settings.speed) elif command.startswith("?"): - robot.uart.write(f"M{Settings.speed:.1f}\n".encode()) - robot.uart.write(f"T{Settings.time_interval:.1f}\n".encode()) + robot.send_line(f"M{Settings.speed:.1f}") + robot.send_line(f"T{Settings.time_interval:.1f}") await asyncio.sleep(3) await asyncio.sleep(0) try: - asyncio.create_task(motor_speed_loop()) + motor_task = asyncio.create_task(motor_speed_loop()) asyncio.run(command_handler()) finally: + motor_task.cancel() robot.stop() diff --git a/ch-11/1-measuring-wheel-speeds/robot.py b/ch-11/1-measuring-wheel-speeds/robot.py index e529414..8905355 100755 --- a/ch-11/1-measuring-wheel-speeds/robot.py +++ b/ch-11/1-measuring-wheel-speeds/robot.py @@ -59,3 +59,6 @@ def set_left(speed): def set_right(speed): set_speed(right_motor, speed) + +def send_line(message): + uart.write(f"{message}\n".encode())