故障排除 python 串行通信

Troubleshooting python serial communication

我正在尝试使用 python 脚本来控制旋转阀。我可以通过 PuTTY 做到这一点,但不能使用我的脚本。代码如下所示。我还在提供示例命令的阀门定位器用户手册中包含了 PuTTY 设置和 link。

import serial

ser = serial.Serial()
ser.port = 'COM7'
ser.baudrate = 9600
ser.bytesize = serial.SEVENBITS
ser.parity = serial.PARITY_ODD
ser.xonxoff = 0
ser.rtscts = 0
ser.dsrdtr = 0
ser.stopbits = 1
ser.timeout = 1
ser.open()

if ser.isOpen():
    print(ser.name + ' is open...')
    while True:
        cmd = input("Enter command or 'exit':")
        if cmd == 'exit':
            ser.close()
            break
        else:
            # ser.write(cmd.encode('ascii'))
            # ser.write(bytes(cmd, 'utf-8'))
            ser.write(str.encode(cmd))
            out = ser.readline()
            print('Receiving... ' + str(out))

您 link 的手册说它需要在每个命令的末尾有一个 <CR>

另外,您的 putty 配置说它添加了 crlf

您可以这样更改代码:

ser.write(str.encode(cmd + '\r\n'))