send serial commands in python

Solutions on MaxInterview for send serial commands in python by the best coders in the world

showing results for - "send serial commands in python"
Noah
16 Jan 2019
1import time
2import serial
3
4# configure the serial connections (the parameters differs on the device you are connecting to)
5ser = serial.Serial(
6    port='/dev/ttyUSB1',
7    baudrate=9600,
8    parity=serial.PARITY_ODD,
9    stopbits=serial.STOPBITS_TWO,
10    bytesize=serial.SEVENBITS
11)
12
13ser.isOpen()
14
15print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
16
17input=1
18while 1 :
19    # get keyboard input
20    input = raw_input(">> ")
21        # Python 3 users
22        # input = input(">> ")
23    if input == 'exit':
24        ser.close()
25        exit()
26    else:
27        # send the character to the device
28        # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
29        ser.write(input + '\r\n')
30        out = ''
31        # let's wait one second before reading output (let's give device time to answer)
32        time.sleep(1)
33        while ser.inWaiting() > 0:
34            out += ser.read(1)
35
36        if out != '':
37            print ">>" + out
38