Python 如何检查设备是否已连接 Pyserial
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21050671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if device is connected Pyserial
提问by Asmastas Maz
I am connecting with my Arduino through a USB port and sending data to it by using PySerial module. At first I can check if the device is connected by using this code:
我通过 USB 端口与我的 Arduino 连接并使用 PySerial 模块向它发送数据。首先,我可以使用以下代码检查设备是否已连接:
try:
ser = serial.Serial("COM3", 9600)
except serial.serialutil.SerialException:
print "Arduino not connected"
Now what I want to do is to check periodically if the Arduino is still connected to the computer. I tried ser.isOpen()but this returns true even if the Arduino is disconnected. I would also like to know how to reconnect the device. I mean once you disconnect the device the program can no longer send any data to Arduino.
现在我想做的是定期检查 Arduino 是否仍然连接到计算机。我试过,ser.isOpen()但即使 Arduino 断开连接,这也会返回 true。我也想知道如何重新连接设备。我的意思是一旦你断开设备,程序就不能再向 Arduino 发送任何数据。
回答by mchant
You can set a timeout.
您可以设置超时。
import serial
ser = serial
try:
ser = serial.Serial("COM3", 9600, timeout=10)
while ser.read():
print 'serial open'
print 'serial closed'
ser.close()
except serial.serialutil.SerialException:
print 'exception'
回答by archetipo
i suggest to use a python thread class to istantiate a serial connection, in the run methos put your while loop , set an var that you use for kill iy at the end, the second public var that you use for store data if have receive and load data in main method.. soon paste an example
我建议使用 python 线程类来实例化串行连接,在运行方法中放置你的 while 循环,最后设置一个用于 kill iy 的变量,第二个用于存储数据的公共变量,如果有接收和在 main 方法中加载数据.. 很快粘贴一个例子
class Arduino():
def __init__(self,Port='/dev/ttyUSB0',Boud=9600,connState=0):
self.parent=self
self.port=Port
self.boud=Boud
self.connState=connState
self.timeount=1
self.ser=None
self.connect()
def connect(self):
try:
self.ser=serial.Serial(self.port,self.boud,timeout=0.0001)
self.connState=1
return [1,'connect']
except:
self.connState=0
return [0,'no hardware found']
def loadData(self):
self.buffer=self.ser.read(1)
if (self.buffer!=''):
try:
print self.buffer
except Exception, e:
pass
ard=Arduino()
while True:
if ard.connState:
ard.loadData()
else:
print "Arduino not found"
break
and start with:
并开始:
import threading
class ThController( threading.Thread ):
# Override Thread's __init__ method to accept the parameters needed:
def __init__( self,parent):
self.parent = parent
threading.Thread.__init__ ( self )
def run ( self ):
while self.parent.ctrlattive:
j=json.loads(data)
self.parent.data=j
回答by Harshan Gowda
import serial
import time
ser = serial.Serial()
ser.braudrate = 115200
ser.port = "/dev/ttyUSB0"
ser.open()
print(ser.name)
if ser.isOpen():
print("serial is open!")
ser.close()
回答by Muhammad Satrio Pakarti
For example to detect ttyUSB0:
例如检测 ttyUSB0:
import os
x=os.system("ls /dev/ttyUSB0")
if x==0:
print "connected"
else:
print "disconnected"
回答by Peter
Unfortunately, the best way I can find to do this is to try some communication and see if it fails. A pretty safe way would be:
不幸的是,我能找到的最好的方法是尝试一些沟通,看看它是否失败。一个非常安全的方法是:
try:
ser.inWaiting()
except:
print "Lost connection!"
You'll probably still want to close the connection with a ser.close() after the connection is lost, although you may need to place that in a "try:except" block also.
在连接丢失后,您可能仍希望使用 ser.close() 关闭连接,尽管您可能还需要将其放置在“try:except”块中。
回答by Gsk
Most of the answers propose 2 approaches:
大多数答案提出了两种方法:
- In some point of the code, send some sort of message through serial to check if your device is still alive
- Start a separate thread and continuously check if the device is alive by opening a communication
- 在代码的某个点,通过串行发送某种消息以检查您的设备是否还活着
- 启动一个单独的线程并通过打开通信不断检查设备是否处于活动状态
The problem with the first solution is that you are notalways checking the connection, but only checking in some specific points: this solution isn't very elegant and if badly written could even be not working.
第一个解决方案的问题是您并不总是检查连接,而只是检查某些特定点:这个解决方案不是很优雅,如果写得不好甚至可能无法正常工作。
The second solution solves the problem of the first solution, but introduces a new problem: checking the connection, or worst sending a message, in a threaded loop will cause problem or may even interrupt the connection to the device from other functions.
第二种解决方案解决了第一种解决方案的问题,但引入了一个新问题:检查连接,或者最坏的发送消息,在线程循环中会导致问题甚至可能会中断其他功能与设备的连接。
A solution that allows you to constantly check the connection without monopolizing the communication involves the reading of the existing COM:
一种允许您在不独占通信的情况下不断检查连接的解决方案涉及读取现有 COM:
import serial.tools.list_ports
myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
print myports
output:
输出:
[(u'COM3', u'Arduino Due Programming Port (COM3)', u'some more data...'),
(u'COM6', u'USB Serial Port (COM6)', u'some more data...'),
(u'COM100', u'com0com - serial port emulator (COM100)', u'some more data...')]
then we save the tuple that contains our port:
然后我们保存包含我们端口的元组:
arduino_port = [port for port in myports if 'COM3' in port ][0]
then we create a function that checks if this port is still present:
然后我们创建一个函数来检查这个端口是否仍然存在:
import time
def check_presence(correct_port, interval=0.1):
while True:
myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
if arduino_port not in myports:
print "Arduino has been disconnected!"
break
time.sleep(interval)
At last, we run this function as a daemon thread:
最后,我们将此函数作为守护线程运行:
import threading
port_controller = threading.Thread(target=check_presence, args=(arduino_port, 0.1,))
port_controller.setDaemon(True)
port_controller.start()
in this way, you'll check each 0.1 secs if the arduino is still connected, and the thread will end when arduino is disconnected or all other activities have ended
这样,您将每 0.1 秒检查一次 arduino 是否仍处于连接状态,当 arduino 断开连接或所有其他活动已结束时,线程将结束

