通过rs232将十六进制代码发送到投影机

时间:2018-09-12 11:03:30

标签: python serial-port

我想通过rs232控制投影。需要时将发送代码7E 30 30 30 30 20 31 0D。但是我不能正确地用python编写代码。我找到了此解决方案,但它给了我一个错误:

Traceback (most recent call last):
  File "C:\Python27\12.py", line 35, in <module>
    ser.write(cmd.decode('hex')+'\r\n')
  File "C:\Python27\lib\encodings\hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string

代码:

import serial
import time

port = "COM1"
ser = serial.Serial(port,9600,timeout=0.5)
print(ser.name + ' is open.')

def bits_to_hex(user64bit): # convert the 8-bit user input to hex
    numInt = int(user64bit, 2)
    strHex = hex(numInt)
    userHex = strHex[2:].zfill(2)
    # make sure the payload is a two-digit hex
    return userHex


while True:
    input = raw_input("Enter HEX cmd or 'exit'>> ")
    if input == 'exit':
        ser.close()
        print(port+' is closed.')
        exit()

    elif len(input) == 64:
    # user enters new register value, convert it into hex
        newRegisterValue = bits_to_hex(input)
        ser.write(newRegisterValue.decode('hex')+'\r\n')
        print('Saving...'+newRegisterValue)
        print('Receiving...')
        out = ser.read(1)
        for byte in out:
            print(byte) # present ascii

    else:
        cmd = input
        print('Sending...'+cmd)
        ser.write(cmd.decode('hex')+'\r\n')
        print('Receiving...')
        out = ser.read(1)
        for byte in out:
            print(byte) # present ascii

0 个答案:

没有答案