Friday, August 3, 2018

Python send data in serial port and receive data from serial port

import serial, time

# initialization and open the port# possible timeout values:# 
1. None: wait forever, block call# 
2. 0: non-blocking mode, return immediately# 
3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB1" 
ser.baudrate = 115200 
ser.bytesize = serial.EIGHTBITS   
# number of bits per bytes 
ser.parity = serial.PARITY_NONE   
# set parity check: no parity 
ser.stopbits = serial.STOPBITS_ONE   
# number of stop bits
#ser.timeout = None 
#block read 
ser.timeout = 1  # non-block read# ser.timeout = 2 
#timeout block read
ser.xonxoff = False  # disable software flow control
ser.rtscts = False  # disable hardware (RTS/CTS) flow control 
ser.dsrdtr = False  # disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2  # timeout for write
 
import re

# Send 1 command is serial port and receive data array
def sendCmd(input):
    try:
        ser.write(input.encode())
        time.sleep(0.1)
        dataArray = []
        data = ser.readline()
        startSendingdata_time = time.clock()
        print("Sending data in serial port: {}".format(input))
        # cheaktimer if data isn't going for 3 sec         
        if len(data) == 0:
            lostData_time = time.clock()
        while len(data) == 0 and (lostData_time - startSendingdata_time) < 3:
            time.sleep(1)
            lostData_time = time.clock()
            print("There isn't any data, system is waiting")
        while not len(data) == 0:
            data = ser.readline()
            # cheak if data has spases and non-data information             
            if data != b'# \r\n' and data != b'# ' and data != b'':
                data = (data[0:-2])
                data = data.decode('ascii')
                dataWithout_non_printable_characters = re.sub(r'(\x1b[/[])[0-9]?[;]?[0-9]?[0-9]{1}m', "", data)
                dataArray.append(dataWithout_non_printable_characters)
    except Exception as e:
        print("Can't send data in serial port: " + str(e))
        exit()
    return dataArray

'''
How to use - for example linux pwd command: 
sendCmd('pwd' + '\r\n')
 
answer: 
'/root'
''' 

No comments:

Post a Comment