Newsletters - MATLAB News & Notes
Programming Patterns
Importing Data via the Serial Port Object in MATLAB
by Peter Webb
There are many tools that you can use to import real-world data into MATLAB, including the Instrument Control Toolbox, the Data Acquisition Toolbox , the Datafeed Toolbox, MAT-files, and the MATLAB Engine interface.
These tools are all means to a common end: connecting MATLAB to your data so that you can quickly develop algorithms for analysis and visualization.
Among the simplest yet least well known of these tools is the serial port object in MATLAB, a mechanism that enables two-way communication with any device that has a serial port interface. This article describes the use of the serial port object to import data from a Global Positioning Satellite (GPS) device.
How the Serial Port Object Works
MATLAB programs that communicate with a serial device via the serial port object use a five-step pattern.
| Step | MATLAB Functions | Inputs |
| 1. Create the serial port object. |
serial | COM port |
| 2. Set up device and communication channel properties. |
set, get | Serial port object, properties |
| 3. Connect to the serial port. |
fopen | Serial port object |
| 4. Send and receive data, and commands. |
fread, fwrite, etc. | Serial port object, data |
| 5. Disconnect from the device and free resources. | fclose and delete | Serial port object |
Because the device on the serial port works like a special kind of file, you can use file I/O functions to send commands to and read data from the serial device. Serial devices communicate with each other via protocols, or sequences of commands and responses. These protocols are either synchronous (blocking) or asynchronous (near- real-time). The serial port object supports both types of protocol.
Before reading the data, you'll need to connect to the serial device using the fopen function. When your communication parameters differ from the serial port object defaults, you'll need to set the communication parameters before using fopen.
Since the serial port object is partially implemented in Java, it will not be accessible if you use the nojvm switch to start MATLAB without Java.
Reading Data from a GPS Device
By analyzing signals from a network of orbiting satellites, a GPS unit can determine its location (latitude and longitude) to within roughly 10 meters. Many GPS units are also capable of determining elevation and speed and maintaining "track logs"(recording position data) for one or more more trips. Most GPS units support both synchronous and asynchronous serial protocols. Synchronous protocols are typically proprietary, but most devices do support a standard asynchronous protocol, NMEA-0182. You can use the serial port object to implement either type of protocol.
Before reading any further, please visit MATLAB Central and download SerialGPS.zip (www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3223&objectType=file), which contains the sample application. The sample application will read data only from Garmin GPS devices and has been tested only with eTrex handhelds, but the principles of serial device communication demonstrated by the sample application are applicable to most serial devices.
The sample application reads, analyzes, and visualizes data from a GPS track log. The main function of the application, DisplayTrack, is only four lines long. The first three lines implement the five-part serial port object communication pattern, while the fourth produces the analysis and visualization:
gps, pid, version, text, protocols] = ... OpenGPS(port);
tracks = ReadTracks(gps);
CloseGPS(gps);
AnalyzeTracks(tracks)
The OpenGPS function implements steps 1, 2, and 3 of the serial port object pattern:
gps = serial(port);
set(gps, 'BaudRate', 9600, 'DataBits', 8, ... 'Parity', 'none', 'StopBits', 1);
fopen(gps);
The serial function creates a serial port object that references the indicated serial port (usually 'COM1'or 'COM2'). Once the call to the set function has established the communications parameters for the session, the fopen function creates a connection to the serial port (which must not be in use by any other program).
The ReadTracks function implements step 4 using the proprietary Garmin communication protocol. Details of this protocol are available on the Garmin Web site at www.garmin.com/support/commProtocol.html. ReadTracks returns a structure array, each entry of which contains five data fields:
latitude, longitude, time, altitude, and depth.
In step 5, the CloseGPS function disconnects the serial port object from the GPS device and frees up the associated MATLAB resources.
fclose(gps);
delete gps;
Finally, the AnalyzeTracks function creates a figure window that displays two-dimensional and three-dimensional views of the track log data and statistics from the trip, such as average speed and total distance traveled. Figure 1 displays GPS data taken on a walkthrough the Natick Town Forest (located near the MathWorks headquarters).
![]() |
Figure 1. Analysis of Natick Town Forest GPS data. Click on image to see enlarged view. |
The overhead view shows the latitude and longitude of the points along the trail, the elevation profile illustrates the topography, and the 3-D track data combines the location and elevation data. The plot command makes the display of two-dimensional data very simple:
% Display the bird's eye view
subplot(2,2,2);
plot(long, lat);
title('Overhead (north up)', 'fontweight', 'bold');
The plot3 and patch commands create a representation of the path through three dimensions (latitude, longitude, and elevation):
% Display the 3D data
subplot(2,2,3);
plot3(long, lat, alt);
axis tight; minAlt = min(alt);
for j=1:length(long)-1
patch([long(j) long(j+1) long(j+1) long(j)], ...
[lat(j) lat(j+1) lat(j+1) lat(j)], ...
[alt(j) alt(j+1) minAlt minAlt], 'b'); end
Using the patch command to fill in the area under the curve makes the path much easier to visualize. Despite its simple interface, the serial port object can support complex applications for analyzing real-world data. By establishing a synchronous or an asynchronous two-way communication channel, the serial port object lets you easily control many types of instruments, sensors, and other electronic devices, and bring the data generated by those devices into MATLAB for analysis. The rich set of numerical and graphical commands in MATLAB make this analysis easy, leaving you more time to focus on what really matters: turning this data into solutions to real-world problems.
For more information visit:
|
Store
