繁体   English   中英

从 Python 中的串行读取

[英]Read from serial in Python

我有体重秤

哪个连接到串口,我想知道当前正在读取的重量。 这是我在 Python 中使用的代码。

import serial

s = serial.Serial(port="COM3")
s.read(10)

它建立了连接,但它只是继续加载并且没有提供任何 output。

我也试过:

ser = serial.Serial()
ser.baudrate = 9600
ser.port = 'COM3'
print(ser)

这是 output:

Serial<id=0x192eaed4c40, open=True>(port='COM3', baudrate=9600, bytesize=8, parity='N', 
stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)

谢谢你。

如果您连接的设备没有写入 10 个字节,则您的读取调用将阻塞,直到它获得所有这 10 个字节。

通常,作为读者的你必须对设备说“嘿,我在这里,你能给我数据吗”,然后他们才会返回给你一些东西。 此外,您可以检查ser.in_waiting属性以查看是否有可以读取的数据(以及有多少数据)

import serial


ser = serial.Serial(
    port = "COM2",
    timeout = 1,
    baudrate=9600,
    parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.SEVENBITS,




)

ser.write(str.encode("W"))


weight = ser.read(8)
print(weight.decode('ascii'), weight)
You want to get the input from the weight scale device. You should follow the following steps:
1. Firstly, check the connection between the device and computer is normal (cable, USB port, computer). You can use the terminal software.
2. If the connection is ok. Now let's start with the following code: 
port='COM8',
 baudrate = 2400,
 parity=serial.PARITY_EVEN,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.SEVENBITS,
 timeout=None
)

while 1:
 x = ser.readline()
 print(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM