首页 > 解决方案 > 将python脚本连接到微控制器

问题描述

我正在尝试通过 USB 串行端口(ttyUSB0)向微控制器发送文本命令,控制器应以“Y”或“N”响应并执行命令。命令以下面的形式'@01a'给出,其中@是开始符号0是A通道的位置,1是B通道的位置,'a'是A+B的校验和。

我被困住了,并且是 python 的初学者,所以欢迎和感谢任何帮助。

ps 当我使用腻子连接时,一切都按预期工作,操作系统也是 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 "

标签: pythonserial-port

解决方案


推荐阅读