Friday, August 3, 2018

Python send bit byte and read bit byte using 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
 
# Connect to board using serial port with speed 'baudrate' 
def connect_to_board(baudrate):
    try:
        ser.baudrate = baudrate
        if (ser.isOpen() == False):
            ser.open()
        ser.flushInput()  # flush input buffer, discarding all its contents         
        ser.flushOutput()  # flush output buffer, aborting current output 
        return True 
    except Exception as e:
        print("Error open serial port: " + str(e))
        return False 
 
# Connect to board with number of try 
def try_connect_to_board(baudrate, count_of_Try):
    tryCount = count_of_Try
    connection = connect_to_board(baudrate)
    while tryCount > 0 and connection == False:
        connection = connect_to_board(baudrate)
        tryCount = tryCount - 1 
        time.sleep(1)
    if tryCount == 0 and connection == False:
        print("Critical error in opening serial port")
        exit()

# Close serial port 
def Close_serial_board():
    try:
        ser.close()
        return True    except Exception as e:
        print("Error open serial port: " + str(e))
        return False 
 
# Set reset in line 
def try_Set_line_in_reset():
    try:
        Resetbyte = (b'\xf0')
        tryCount = 4         
        lineState = 0
        ser.write(Resetbyte)
        time.sleep(0.5)  # give the serial port sometime to receive the data 
        response = ser.readline()
        while response == b'\xf0' or response == b'' and tryCount != 0:
            ser.write(Resetbyte)
            time.sleep(0.5)
            response = ser.readline()
            tryCount = tryCount - 1 
            print('Try reset line state - {}' + str(tryCount))
        if response != b'\xf0' or b'':
            print('Device detected - {} '.format(response))
            lineState = 1 
    except Exception as e:
        print("There is a problem in reseting line state: " + str(e))
    return lineState

# Send 1 bit information, 1 or 0 
def SendBit(bit):
    try:
        if bit == 0:
            Zerobyte = (b'\x00')
            ser.write(Zerobyte)
            #time.sleep(0.5)             
            cheakBit = ser.read(1)
            if cheakBit != b'\x00':
                print("Readed 0 bit not the same")
        elif bit == 1:
            Onebyte = (b'\xff')
            ser.write(Onebyte)
            #time.sleep(0.5)             
            cheakBit = ser.read(1)
            if cheakBit != b'\xff':
                print("Readed 1 bit not the same")
        else:
            print("Sended bit is not correct")
    except Exception as e:
        print("Error in sending bit : " + str(e))
        exit()

# Send 1 byte of information
 def SendByte(byte):
    try:
        sendByte = []
        for i in range(8):
            bit = byte & 0x01;
            SendBit(bit)
            sendByte.append(bit)
            time.sleep(0.1)
            byte = byte >> 1     
    except Exception as e:
        print("error open serial port: " + str(e))
        exit()

#Read 1 bit information, FF or 0 
def ReadBit():
    try:
        Zerobyte = (b'\xff')
        ser.write(Zerobyte)
        time.sleep(0.1)
        cheakBit = ser.read(1)
        if cheakBit == b'\xff':
            return 1 
        else:
            return 0 
    except Exception as e3:
        print("error open serial port: " + str(e3))
        exit()

# Read 1 byte information 
def ReadByte():
    byte = []
    for i in range(8):
        #print("Operation number is {}".format(i)) 
        bit = ReadBit()
        #time.sleep(0.1)         
        byte.append(bit)
    #print(byte)
    byte.reverse()
    byte = ''.join(map(str, byte))
    #print(byte) 
    byte = int(byte, 2)
    #print(byte) 
    byte = hex(byte)
    return byte

 
'''
How to use
try_connect_to_board(115200, 5) 
SendByte(0xcc)
ReadByte() 
''' 

No comments:

Post a Comment