Pab*_*res 6 python serial-port pyserial
我正在从串口读取由arduino发送的数据。
我有两个文件,我分别使用它们来编写一些代码并尝试不同的事情。在其中之一中,我读取数据并使用 matplotlib 图形绘制它。当我使用完它后,它仍然与我的计算机保持连接并发送数据。所以,我需要做的是“重置”端口。也就是说,关闭打开的端口并再次打开它,并阻止它发送数据,这样我就可以使用arduino尝试对此文件的代码进行一些修改。
因此,为了完成此任务,我的意思是,要重置端口,我创建了另一个文件并编写了以下代码:
import serial
print "Opening port"
try:
serial_port = serial.Serial("com4", 9600)
print "Port is open"
except serial.SerialException:
serial.Serial("com4", 9600).close()
print "Port is closed"
serial_port = serial.Serial("com4",9600)
print "Port is open again"
print "Ready to use"
Run Code Online (Sandbox Code Playgroud)
但这段代码似乎不起作用。端口仍然连接并发送数据。所以,这意味着我无法使用我的代码关闭端口,然后再次重新打开它。
我究竟做错了什么?如何阻止arduino发送数据?或者我怎样才能重置Arduino?
希望你能帮我。
我成功地找出了我遇到的真正问题,但这不是我想象的那样。问题不在于端口是开放的,尽管我使用了closePyserial 的功能。真正的事情是,端口正在按照我的意愿关闭,但设备(arduino)仍在发送数据。因此,我更改了代码来重现这种情况。
这是代码:
print "Abriendo puerto"
ser = serial
try:
ser = serial.Serial("com4", 9600, timeout = 1)
serial_port = "Open"
print "The port %s is available" %ser
except serial.serialutil.SerialException:
print "The port is at use"
ser.close()
ser.open()
while ser.read():
print "Sending data"
ser.setBreak(True)
time.sleep(0.2)
ser.sendBreak(duration = 0.02)
time.sleep(0.2)
ser.close()
time.sleep(0.2)
print "The port is closed"
exit()
Run Code Online (Sandbox Code Playgroud)
有了这段代码,我要做的是:
1)我打开串口
2)如果设备正在发送数据,我打印“正在发送数据”
3)1秒后,我尝试关闭端口并停止设备发送数据
我尝试了最后两件事,使用close关闭端口的功能,并阅读我尝试过的文档,setBreak正如sendBreak您在上面的代码中看到的那样(我故意留下它们)。但设备仍在发送数据,这意味着代码不起作用。
那么,有没有办法告诉arduino“停止发送数据”,或者我可以重置设备吗?
我做了一件非常相似的事情,两种方式都取得了成功。
第一种方式是让Arduino不断发送数据。这里的问题是,当您的 python 代码唤醒并开始从串行端口读取数据时,Arduino 可能位于其程序中的任何位置。简单的解决方案是修改 Arduino 代码以发送某种“重新启动”行。在这种情况下,你的Python代码需要做的就是等待“重新启动”,然后读取真实数据,直到它再次看到“重新启动”。我的线路很嘈杂,因此我的代码通过多个周期读取(并解析)以确保它获得良好的数据。
resetCount = 0;
while resetCount < 3:
line = s.readline().rstrip("\r\n")
if string.find(line, "restart") != -1 :
resetCount += 1
elif resetCount > 0 :
fields = string.split(line, " ")
dict[fields[0]] = fields
Run Code Online (Sandbox Code Playgroud)
第二种方法是使用 Arduino 实现命令响应协议,其中 Arduino 仅在请求时发送数据。在这种情况下,您的 python 代码将命令发送到 Arduino(下例中的“RT”),然后从 Arduino 读取数据,直到看到“已完成”行或超时。
dict = {}
regex = re.compile('28-[0-9A-Fa-f]{12}') # 28-000005eaa80e
s = serial.Serial('/dev/ttyS0', 9600, timeout=5)
s.write("RT\n");
while True:
line = s.readline().rstrip("\r\n")
print line
if string.find(line, "completed") != -1:
break;
fields = string.split(line)
if (regex.match(fields[0]) != None and len(fields) == 4) :
dict[fields[0]] = fields
s.close()
Run Code Online (Sandbox Code Playgroud)
小智 0
我认为你必须在创建后立即执行serial_port.open()才能真正打开端口。
看起来它也只是打开端口并在成功时退出。也许我在这里遗漏了一些东西。我从未使用过 pySerial,我只是按照文档进行操作。