Is it possible to read from or write to a serial port with MATLAB?

6 views (last 30 days)
I would like to know if it is possible to read from or write to a serial port with MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 10 Apr 2023
Edited: MathWorks Support Team on 13 Apr 2023
There are several ways to interface MATLAB with the serial port.
1. As of MATLAB 6.0 (R12), a serial port interface is provided, allowing you to connect to a computer's serial communications (COM) port. This interface is established through a serial port object, which you create using the SERIAL function. The serial port object supports functions and properties that allow you to:
- Configure serial port communications
- Use serial port control pins
- Write and read data
- Use events and actions
- Record information to disk
Here is an example serial session connecting MATLAB to the serial port (COM1) with a baud rate of 4800:
s = serial('COM1');
set(s,'BaudRate',4800);
fopen(s);
fprintf(s,'*IDN?')
out = fscanf(s);
fclose(s)
delete(s)
clear s
The *IDN? command above is a typical instrument command and can be replaced by any command that is valid for your specific device. *IDN queries the device for identification information, which is returned to out. If your device does not support this command, or if it is connected to a different serial port, you should modify the above example accordingly.
The serial port interface is supported only for Microsoft Windows, Linux, and Sun Solaris platforms.
Additionally, the Instrument Control Toolbox provides advanced serial port support such as a GUI for communicating with the serial object, and methods for determining the available hardware. For more information on the advanced serial port support offered by the Instrument Control Toolbox, refer to the related solution below.
2. Through the use of MEX-files, one could develop C or Fortran routines that interface MATLAB with the serial port. One such CMEX-file implementation, called CPORT, is available from the MATLAB Central File Exchange
Please note that, although some users have reported success with this function, MathWorks does not guarantee or warrant the use or content of MATLAB Central File Exchange submissions. Any questions, issues, or complaints should be directed to the contributing author.
For more information on MEX-files, refer to the MEX-files Guide at:
3. The MATLAB Java interface enables you to access Java API class packages. Using the Java interface, one could create an interface to the serial port. An example of such an interface is described in the MATLAB documentation. See the "Calling Java from MATLAB" portion of the External Interfaces subsection.

More Answers (0)

MathWorks Support

Categories

Find more on Java Package Integration in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!