通过串口或TCP与Thymio-II机器人通信
thymiodirect的Python项目详细描述
胸腺嘧啶
Python包,通过串行端口(有线USB或无线USB加密狗上的虚拟端口)或TCP端口(asebaswitch或Thymio模拟器)连接到具有本机二进制协议的Thymio II robot。在
示例
下面的步骤是从您通过键入获得的帮助中借用的
import thymiodirect
help(thymiodirect)
导入所需的类:
^{pr2}$设置Thymio所连接的串行端口(根据您的配置,默认端口不是您想要的):
port = Connection.serial_default_port()
创建一个带有回调的Thymio
连接对象,当robot准备好并启动连接时(或稍等几秒钟),就会收到通知:
th = Thymio(serial_port=port,
on_connect=lambda node_id:print(f"{node_id} is connected"))
th.connect()
获取第一个(或唯一)胸腺的id:
id = th.first_node()
获取变量:
th[id]["prox.horizontal"]
设置变量(标量或数组):
th[id]["leds.top"] = [0, 0, 32]
定义在获取新变量值后调用的函数。 前后接近传感器用于使机器人向前或向后移动。移动或停止的决定基于这些传感器读数的差异。在
prox_prev = 0
def obs(node_id):
global prox_prev
prox = (th[node_id]["prox.horizontal"][5]
- th[node_id]["prox.horizontal"][2]) // 10
if prox != prox_prev:
th[node_id]["motor.left.target"] = prox
th[node_id]["motor.right.target"] = prox
print(prox)
if prox > 5:
th[id]["leds.top"] = [0, 32, 0]
elif prox < -5:
th[id]["leds.top"] = [32, 32, 0]
elif abs(prox) < 3:
th[id]["leds.top"] = [0, 0, 32]
prox_prev = prox
安装此功能:
th.set_variable_observer(id, obs)
把你的手放在机器人后面,让它向前移动,或者把你的手放在它前面,使机器人向后移动。在
删除此功能:
th.set_variable_observer(id, None)
默认情况下,所有的Thymio变量每秒取10次。这可以通过传递给Thymio
构造函数的选项来更改。下面是如何每秒5次(每0.2秒)获取一个包含prox.horizontal
和prox.ground
的变量数据块:
th = Thymio(serial_port=port,
on_connect=lambda node_id:print(f"{node_id} is connected"),
refreshing_rate=0.2,
refreshing_coverage={"prox.horizontal", "prox.ground"})
- 项目
标签: