返回教程正文

配套源码

main.py

app/python/main.py
zdt_x57s_can Brick:把一台 ZDT X57S 封装成可复用对象app/python/main.py
Python69 行
  1. # SPDX-License-Identifier: MIT
  2. import time
  3. from arduino.app_utils import App
  4. from zdt_x57s_can import ZdtX57SCan, ZdtX57SCanError
  5. MOTOR_IDS = (1, 2, 3, 4)
  6. motors = tuple(ZdtX57SCan(motor_id) for motor_id in MOTOR_IDS)
  7. probe_complete = False
  8. next_probe_time = 0.0
  9. last_error = None
  10. def read_all_motor_speeds():
  11. """
  12. @description : 由测试App组合四个单电机对象并依次读取实时速度
  13. @param : 无参数
  14. @return : 电机地址到实时RPM的字典
  15. """
  16. speeds = {}
  17. for motor in motors:
  18. try:
  19. speeds[motor.motor_id] = motor.read_speed()
  20. except ZdtX57SCanError as error:
  21. raise ZdtX57SCanError(
  22. f"motor {motor.motor_id}: {error}"
  23. ) from error
  24. return speeds
  25. def loop():
  26. """
  27. @description : 等待Linux原生CAN网关就绪并对1至4号电机执行一次无运动探测
  28. @param : 无参数
  29. @return : 无返回值
  30. """
  31. global probe_complete, next_probe_time, last_error
  32. current_time = time.monotonic()
  33. if not probe_complete and current_time >= next_probe_time:
  34. try:
  35. speeds = read_all_motor_speeds()
  36. print(
  37. "[zdt-x57s] 四电机CAN通信正常: "
  38. + ", ".join(
  39. f"id{motor_id}={speeds[motor_id]}RPM"
  40. for motor_id in MOTOR_IDS
  41. ),
  42. flush=True,
  43. )
  44. probe_complete = True
  45. last_error = None
  46. except ZdtX57SCanError as error:
  47. error_text = str(error)
  48. if error_text != last_error:
  49. print(
  50. "[zdt-x57s] 等待CAN网关或电机应答: " + error_text,
  51. flush=True,
  52. )
  53. last_error = error_text
  54. next_probe_time = current_time + 3.0
  55. time.sleep(0.05)
  56. App.run(user_loop=loop)