我正在尝试通过USB串行端口(ttyUSB0)向微控制器发送文本命令,控制器应以'Y'或'N'响应并执行命令。命令以以下格式表示:“ @ 01a”,其中@开头的符号0是A通道的位置,1是B通道的位置,“ a”是A + B的校验和。
我还是python的初学者,所以欢迎大家提供帮助。
p.s。当我使用腻子进行连接时,一切正常 操作系统是Ubuntu 16.04 LTS
这是我的代码:
import time
import serial
import binascii
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=19200,
)
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
AT = chr(int('1000000',2))
A = chr(int('100000',2))
B = chr(int('100000',2))
AB = chr(int('1000000',2))
input = AT + A + B + AB
print input
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
#write data
ser.write(input)
# print("write data: AT+CSQ")
time.sleep(0.5) #give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "