gri*_*ett 7 python arduino pythoncard pyserial
我正在构建一个使用Python远程控制的机器人,通过简单的GUI通过Internet发送控制消息.
我的代码部分工作得很好,GUI和控制系统,但我被卡住了.我正在尝试使用视差ping传感器来获取Arduino Mega中对象信息的距离,并将该值发送到我的Python控制脚本以显示在远程GUI上.
我遇到的主要问题是如何集成将使用已建立的COM端口与Arduino的Python代码,并发送消息告诉Arduino轮询ping传感器,然后发送到将接收值的Python程序,然后让我将该值插入我的GUI.
我已经有了这个代码来控制Arduino,它可以用我简单的GUI工作.
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
from PythonCard import model
class MainWindow(model.Background):
def on_SpdBtn_mouseClick(self, event):
spd = self.components.SpdSpin.value
def on_FBtn_mouseClick(self, event):
spd = self.components.SpdSpin.value
ser.write('@')
ser.write('F')
ser.write(chr(spd))
def on_BBtn_mouseClick(self, event):
spd = self.components.SpdSpin.value
ser.write('@')
ser.write('B')
ser.write(chr(spd))
def on_LBtn_mouseClick(self, event):
spd = self.components.SpdSpin.value
ser.write('@')
ser.write('L')
ser.write(chr(spd))
def on_RBtn_mouseClick(self, event):
spd = self.components.SpdSpin.value
ser.write('@')
ser.write('R')
ser.write(chr(spd))
def on_SBtn_mouseClick(self, event):
spd = self.components.SpdSpin.value
ser.write('@')
ser.write('S')
ser.write('0')
def on_PngDisBtn_mouseClick(self, event):
ser.write('~')
ser.write('P1')
ser.write('p2')
app = model.Application(MainWindow)
app.MainLoop()
Run Code Online (Sandbox Code Playgroud)
我真正想做的是改进上面的代码并添加一个按钮来点击告诉Python向Arduino发送消息以检查ping传感器并返回值.我非常了解Arduino代码,但我在过去两周才开始使用Python.
基本上,您只需向 Arduino 发送一个合适的命令,就像您已经在做的那样,然后等待 Arduino 发回一些信息;它的 python 端可能看起来像这样
ser.write('foo')
retval = ser.readline() # read a complete line (\r\n or \n terminated),
#or you could use read(n) where n is the number of bytes you want (default=1)
ping_data = retval.strip() # strip out the newline, if you read an entire line
Run Code Online (Sandbox Code Playgroud)
当然,这会给你一个字符串,你可能希望将其转换为 int 或 float 以便稍后在计算中使用它(对字符串使用 int(ping_data) 或 float(ping_data) ,或 struct.unpack如果它是一个字节序列,需要首先将其解包为正常的内容,但这完全取决于您如何表示传感器数据)。