在python中发送串行消息

时间:2015-10-14 13:16:57

标签: python python-2.7 pyserial

我正在尝试发送此命令":01050801FF00F2"在python 2.7中超连续,没有成功。 我使用的代码是:

import serial, sys ,socket
from time import sleep
port = "COM9"
baudRate = 9600
try:
     ser = serial.Serial(port, baudRate, timeout=1)
     if not ser.isOpen():
            ser.open()
except Exception, e:
   print("Error opening com port. Quitting."+str(e))
   sys.exit(0)
print("Opening " + ser.portstr) 

#this is few ways i am trying to send with
c = '01050801FF00F2'
ser.write(c.encode('utf-8'))
sleep(3)
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
                 #and discard all that is in buffer
c = ':01050801FF00F2'
ser.write(c.encode('hex'))

sleep(3)
ser.write(':01050801FF00F2')

2 个答案:

答案 0 :(得分:1)

如果这些是十六进制值,这应该有效:

c = '\x01\x05\x08\x01\xFF\x00\xF2'
ser.write(c)

答案 1 :(得分:0)

您是否尝试过使用bytearray发送命令?

也许你可以试试:

ser.write(b':01050801FF00F2')

ser.write(':01050801FF00F2'.encode())