python串行发送和接收数据

时间:2015-04-01 03:58:10

标签: python serial-port python-2.x stm32

我正在尝试通过COM端口4与STM32L152RB板进行通信,COM端口4接受来自COM4的命令并使用此代码在终端中显示结果但它不起作用...我是python的新手请让我知道我在做什么错。

#Global Variables
ser = 0


def init_serial():
    COMNUM = 4          #Enter Your COM Port Number Here.
    global ser          #Must be declared in Each Function
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1   #COM Port Name Start from 0

    #ser.port = '/dev/ttyUSB0' #If Using Linux

    #Specify the TimeOut in seconds, so that SerialPort
    #Doesn't hangs
    ser.timeout = 10
    ser.open()          #Opens SerialPort

    # print port open or closed
    if ser.isOpen():
        print 'dis' + ser.portstr




init_serial()

temp = raw_input('Type what you want to send, hit enter:\r\n')
ser.write('dis')         #Writes to the SerialPort

while 1:    
    bytes = ser.read()  #Read from Serial Port
    print 'You sent: ' + bytes      #Print What is Read from Port

0 个答案:

没有答案