serial_read(ser, length=-1, timeout=-1)
Features
This function reads the data from a serial port.
Parameters
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
Ser | serial.Serial | - | Serial instance |
Length | int | -1 | Number of bytes to read
|
timeout | int float | -1 | Read waiting time
|
Return
Value(res, rx_data) | Description | |
res | n | Number of bytes of the received data |
-1 | The port is not open. | |
-2 | serial.SerialException error occurred | |
rx_data | Number of bytes read (byte type) |
Exception
Exception | Description |
---|---|
DR_Error (DR_ERROR_TYPE) | Parameter data type error occurred |
DR_Error (DR_ERROR_VALUE) | Parameter value is invalid |
Example
ser = serial_open(port="COM", baudrate=115200, bytesize=DR_EIGHTBITS,
parity=DR_PARITY_NONE, stopbits=DR_STOPBITS_ONE)
res, rx_data = serial_read(ser)
#Wait indefinitely until data is received
res, rx_data = serial_read(ser, timeout=3)
#Wait until data is received, set a 3 seconds timeout
# If received within 3 seconds, the read data is returned immediately
# Return the value read so far after 3 seconds have elapsed
res, rx_data = serial_read(ser, length=100)
# Wait indefinitely until reading 100 bytes
res, rx_data = serial_read(ser, length=100, timeout=3)
#Wait until reading 100byte, set 3 seconds timeout
# If 100 bytes are received within 3 seconds, the read data is returned immediately.
# Return the value read so far after 3 seconds have elapsed
# Convert the received byte type to string type
rx_msg = rx_data.decode()
# rx_data is a byte type and decode() is used to convert it to a string type.
# For example, if rx_data = b”abcd”, then rx_msg=”abcd”.
res, rx_data = serial_close(ser)