python 将 raw_iput 中的值作为字符串返回。我希望将这些字符串转换为十六进制字符。所以:
example = '\x05\x06\x40\x00\x02\x05'
tx = raw_input("\nTX: ") #user enters 05 06 40 00 02 05
我该怎么做那个 tx == 例子?
到目前为止我的代码:
import base64
import serial
import crcmod
import binascii
s_port = 'COM1'
b_rate = 2400
#method for reading incoming bytes on serial
def read_serial(ser):
buf = ''
while True:
inp = ser.read(size=1) #read a byte
buf = buf + inp #accumalate the response
if '\xff' == inp: #if the incoming byte is 0xff
print buf.encode("hex") # never here
break
return buf.encode("hex")
#method to calc the checksum
def calc_crc(hstr):
crc16 = crcmod.predefined.mkCrcFun('crc-16')
hstr = hstr.replace(' ','')
data = base64.b16decode(hstr)
chsum = hex(crc16(data))
return chsum
#create a serial opening
ser = serial.Serial(
port=s_port,
baudrate=b_rate,
timeout=0.1
)
while True:
example = '\x05\x06\x40\x00\x02\x05\xF6\x5C' #last 2 bytes are CRC
tx = raw_input("\nTX: ") #user enters 05 06 40 00 02 05
crc = calc_crc(tx) #checksum is calculated as 0xf65c, correct
tx = binascii.hexlify(tx.replace(' ', '')) #convert ascii string into hex as is but how???????????
print tx #gives me 303530363430303030323035
cmd = tx + crc # concatenate tx and crc so the command is complete
ser.write(cmd)
rx = read_serial(ser)
print "RX: " + str(rx)