MATLAB Language Using serial ports Automatically processing data received from a serial port


Example

Some devices connected through a serial port send data to your program at a constant rate (streaming data) or send data at unpredictable intervals. You can configure the serial port to execute a function automatically to handle data whenever it arrives. This is called the "callback function" for the serial port object.

There are two properties of the serial port that must be set to use this feature: the name of the function you want for the callback (BytesAvailableFcn), and the condition which should trigger executing the callback function (BytesAvailableFcnMode).

There are two ways to trigger a callback function:

  1. When a certain number of bytes have been received at the serial port (typically used for binary data)
  2. When a certain character is received at the serial port (typically used for text or ASCII data)

Callback functions have two required input arguments, called obj and event. obj is the serial port. For example, if you want to print the data received from the serial port, define a function for printing the data called newdata:

function newdata(obj,event)
    [d,c] = fread(obj);  % get the data from the serial port
    % Note: for ASCII data, use fscanf(obj) to return characters instead of binary values
    fprintf(1,'Received %d bytes\n',c);
    disp(d)
end

For example, to execute the newdata function whenever 64 bytes of data are received, configure the serial port like this:

s = serial(port_name);
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 64;
s.BytesAvailableFcn = @newdata;

With text or ASCII data, the data is typically divided into lines with a "terminator character", just like text on a page. To execute the newdata function whenever the carriage return character is received, configure the serial port like this:

s = serial(port_name);
s.BytesAvailableFcnMode = 'terminator';
s.Terminator = 'CR';  % the carriage return, ASCII code 13
s.BytesAvailableFcn = @newdata;