Main Content

read

Read data from serial port

Since R2019b

Description

example

data = read(device,count,datatype) reads the number of values specified by count in the form specified by datatype from the serial port connection device. For all numeric datatype types, data is a row vector of double values. For the text type datatype values of "char" or "string", data is of the specified type. The function suspends MATLAB® execution until the specified number of values are read or a timeout occurs.

Examples

collapse all

Create a connection to a serial port device. In this example, the serial port at COM3 is connected to a loopback device.

device = serialport("COM3",9600)
device = 

  Serialport with properties:

                 Port: "COM3"
             BaudRate: 9600
    NumBytesAvailable: 0

  Show all properties, functions

Write the values [1,2,3,4,5] in uint8 format.

write(device,1:5,"uint8")

Since the port is connected to a loopback device, the data you write to the device is returned to MATLAB. Read all the data.

read(device,5,"uint8")
ans = 1×5

     1     2     3     4     5

Input Arguments

collapse all

Serial port connection, specified as a serialport object.

Example: read(device,20,"uint32") reads data from the serial port connection device.

Number of values to read, specified as a positive integer value. If count is greater than the NumBytesAvailable property of device, the function suspends MATLAB execution and waits until the specified amount of data is read or a timeout occurs.

Example: read(device,5,"uint32") reads five values of uint32 data. Each uint32 value is four bytes, for a total of 20 bytes read.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Size and format of each value, specified as a character vector or string. datatype determines the number of bytes to read for each value and the interpretation of those bytes as a MATLAB data type.

Example: read(device,5,"uint16") reads five values of uint16 data. Each uint16 value is two bytes, for a total of 10 bytes read.

Data Types: char | string

Version History

Introduced in R2019b

See Also

Functions