用Python通过RS232从设备(位移测量)读取数据

2024-04-20 08:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个位移测量,我想让Python给我值,但我不知道如何接收数据

`import serial

port = "COM3"
baud = 115200

ser = serial.Serial(port, baud, timeout=1)

    # open the serial port
if ser.isOpen():
     print(ser.name + ' is open...')

while True:
    cmd = input("Enter command or 'exit':")
        # for Python 2
    # cmd = input("Enter command or 'exit':")
        # for Python 3
    if cmd == 'exit':
        ser.close()
        exit()
    else:
        ser.write(cmd.encode('ascii','strict')+'\r\n')
        out = ser.read()
        print('Receiving...'+out)

`

Tags: orcmdforinputifportexitserial
1条回答
网友
1楼 · 发布于 2024-04-20 08:41:49

write(...只接受binary数据。你知道吗

DocumentationpySerial API
write(data)
Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g.'hello'.encode('utf-8').

相关问题 更多 >