Pyserial 测试

4 投票
2 回答
7028 浏览
提问于 2025-04-17 10:53

我刚接触Pyserial和硬件方面的知识。现在我想运行在http://pyserial.sourceforge.net/shortintro.html#opening-serial-ports上提供的示例应用程序。

import serial

ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()

我已经把这个程序写在一个Python文件里并运行了。现在如果我想测试这个应用程序,看看我发送的字符串是否正确(比如:Hyperterminal或者其他的),我该怎么做呢?有没有人能指导我一下?

2 个回答

2

测试物理串口的另一种简单方法是用一根线、螺丝刀、鳄鱼夹或者手边的任何东西,把RX(接收)和TX(发送)连接在一起。这样一来,你发送的所有信息都会被自己接收到。之后你可以用下面的代码来接收这些信息:

import serial

ser = serial.Serial(0, timeout = 1)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
msg = ser.read("100") #read the content of the input buffer until you get 100 byte or a timeout event
print(msg) #print the content you might need to decode it print(decode(msg))
ser.close()

要让这段代码正常工作,关键是要把RX和TX连接在一起。很多教程都会教你怎么做这个。

2

虚拟串口

在测试中使用虚拟串口。

在Windows系统上,我使用com0com,而在Linux系统上则使用socat

然后,使用Putty来查看你发送的数据。

撰写回答