Python:写入和读取串行端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19143360/
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
Python: Writing to and Reading from serial port
提问by RageCage
I've read the documentation, but can't seem to find a straight answer on this. I have a list of all COM Ports in use by Modems connected to the computer. From this list, I try to open it, send it a command, and if it says anything back, add it to another list. I'm not entirely sure I'm using pyserial's read and write functions properly.
我已经阅读了文档,但似乎无法找到直接的答案。我有一个连接到计算机的调制解调器使用的所有 COM 端口的列表。从这个列表中,我尝试打开它,向它发送一个命令,如果它有任何回复,则将其添加到另一个列表中。我不完全确定我是否正确使用了 pyserial 的读写功能。
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
print ser.read(64)
if ser.read(64) is not '':
print port
except serial.SerialException:
continue
i+=1
I'm not getting anything out of ser.read(). I'm always getting blank strings.
我没有从 ser.read() 中得到任何信息。我总是得到空字符串。
采纳答案by Chaosphere2112
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
ser.read(64)
应该是ser.read(size=64)
;ser.read 使用关键字参数,而不是位置参数。
Also, you're reading from the port twice; what you probably want to do is this:
此外,您正在从端口读取两次;你可能想要做的是:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
回答by PHMADEIRA
a piece of code who work with python to read rs232 just in case somedoby else need it
一段使用 python 读取 rs232 的代码,以防万一其他人需要它
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()