By Trent Jarvi, MathWorks
Many MATLAB users who analyze data, develop and verify algorithms, or create software applications leave the MATLAB environment to import data from external hardware. This extra step creates inefficiencies by forcing the user to manually transfer data from one environment to another and to learn and maintain multiple software tools.
Using a Garmin handheld Global Positioning System (GPS) receiver with an RS-232 serial interface as an example, this article demonstrates how you can use MATLAB and Instrument Control Toolbox to work with diverse external devices without leaving the MATLAB environment. It explains how to communicate with a serial device, interact with the device in MATLAB, and automatically generate a MATLAB script that can be shared, reused, or incorporated into a MATLAB application.
The MATLAB scripts used in this article are available for download.
For many serial port applications, you can communicate with your instrument without detailed knowledge of how the serial port works. Communication is established through a serial port object, serial, which you create in the MATLAB® workspace. For information about creating the serial object, see Serial Port Object. Write a MATLAB program for blinking the LED and save it as a.m file. Run the MATLAB Program and the LED connected to Arduino should start blinking as per the program. Applications of Arduino MATLAB Interface. By interfacing Arduino with MATLAB, we can acquire Sensor Data from Arduino and start plotting various graphs.
RS-232 serial devices, such as GPS receivers, and instruments, such as oscilloscopes and signal generators, can be configured and controlled in MATLAB with Instrument Control Toolbox (Figure 1). Our example uses a consumer-grade Garmin ETrex 12-channel GPS device, typically used while hiking and boating. The example uses electrical and data communications specified by National Marine Electronics Association (NMEA) 183 communication, which should work with any GPS device capable of serial communication. You could use other protocols, including Garmin’s proprietary protocol, if you have access to the specifications.
To find out what serial devices and instruments are available for communication, we can use MATLAB command-line functions, such as instrhwinfo
, instrfind
, and serial
. Alternatively, we can use TMTool, a graphical user interface provided by Instrument Control Toolbox that lets you locate, configure, and control serial devices and instruments without writing MATLAB script (Figure 2). First, we will explore available hardware assets using a hierarchical tree.
Communicating with a device to acquire data often requires establishing a connection to its communication interface. With TMTool we can configure, control, and acquire data from devices through well-established interfaces, including serial, GPIB, TCP/IP and UDP (Figure 3). We can also use TMTool to communicate with instruments using VISA, LXI, or IVI and VXIplug&play drivers.
In Figure 4, the serial node has been expanded to show the serial ports available for communication. The GPS is configured to broadcast NMEA format data, a common option in consumer-grade GPS receivers.
Matlab Graphical Interface
After connecting the GPS receiver to COM1, we select the Configure tab for COM1 and set it to match the serial port parameters. NMEA defines these parameters as baud rate 4800 bits per second, 8 data bits, 1 stop bit and no parity.
After configuring the serial port parameters, we open the connection via the serial port. The Connection status changes to Connected, indicating that communication with the GPS through the Communicate tab is now possible. The NMEA standard specifies that data must be transmitted as ASCII characters in new line-terminated strings. Using the dropdown menu, we set the “Receiving data” parameters to comply with this specification.
We can now send data to the hardware and read the responses. For our example, all we need to do is read the data broadcast from the GPS. We can confirm that we are communicating properly and that the data of interest is available by clicking the Read button several times to observe that properly formatted strings are being acquired in the sequential log. After a few attempts, the GPS coordinates of interest appear in the results, together with several other NMEA data types. Finally, we close the connection to the GPS device to capture the disconnect as MATLAB script in the session log for later reference.
Once we have configured the port, read the strings, and acquired the data in which we are interested, we can repeat this series of tasks in the future by simply exporting the generated script to a MATLAB file called get_gps_location.m
. We can then execute the MATLAB script that was automatically generated when we interacted with TMTool (Figure 6).
So far, we have configured the hardware and acquired the data, but some of the data that we acquired, such as waypoints and time information, is not specific to the GPS location. With TMTool, we can automatically filter out this unwanted data, just as we automated the hardware configuration and data acquisition by adding MATLAB script to a MATLAB instrument driver. TMTool automatically updates the MATLAB script generated in the Session Log tab. Once we have exported the updated script MATLAB_GPS_example.m
, we can insert MATLAB routines to filter the data stream.
To acquire and process the GPS data, simply execute the MATLAB_GPS_example.m
file on the command line.
While the MATLAB workflow discussed so far will be sufficient for some applications, others might benefit from incorporating the MATLAB script into a reusable driver. We can incorporate the MATLAB script into a reusable driver by using MIDEdit, a driver development tool in Instrument Control Toolbox (Figure 7). MIDEdit lets you incorporate lower-level commands into higher-level commands that are easier to access. After launching MIDEdit from the command line, we create a new generic instrument driver through the File->New context menu.
To demonstrate the use of a self-contained, reusable driver in MATLAB, we will add just two pieces of functionality to the driver: configure the GPS device and acquire the GPS location. With MIDEdit we could also create more advanced drivers comprising hundreds of lines of code.
To configure the GPS device, we browse to the automatically generated MATLAB script in the TMTool session log. This script sets the baud rate and then opens the port. We can now copy this information into a driver. Within MIDEdit, we select the Connect tab from the Initialization and Cleanup node and set the Function Style to M-Code. We then paste the script from TMTool into the function created in the driver editor. Noting that the serial interface may be obtained from the variable obj passed into this function, the MATLAB script is adjusted to use the serial port interface.
To acquire the GPS location, we select the Function node in MIDEdit and add a new function called getLocation()
. This function will obtain the latitude, longitude, and cardinals. In the MATLAB code editor pane, we paste in the MATLAB script that reads the NMEA lines. As in our first example, we modify the function to return an array representing the GPS location. We add logic that instructs getLocation()
to find only the GPS coordinates in the NMEA stream and to return the location. More functions could be added for each type of NMEA information found in the stream. Finally, we save the driver to our workspace as nmeareceiver.mdd
.
The driver is now ready to be used with the GPS device. We use TMTool to expand the Instrument Drivers node and create a new interface object by right-clicking the Interface Objects node under the Instrument Objects node. We select a serial port interface object and set the port to the serial port to which the GPS is connected. The interface object could be configured, opened, and read using the process described in the previous section, but this time we will use the instrument driver to perform our acquisition and analysis tasks.
We select the Instrument Objects node and enter the information for the instrument driver nmeareceiver.mdd
by right-clicking and selecting new Device Object. We then connect the GPS to the serial port represented by the interface object. It is possible to change the interface if the device and driver support more than one interface. When completed, the nmeareceiver
instance will appear under the Device Objects node.
We can now connect to the GPS using the Connect button. Under the Functions tab, we can execute the getLocation()
function, resulting in the current location being acquired. We can export the results to the workspace for further analysis.
MATLAB script is automatically generated when you interact with the driver in TMTool. As when working with the GPS device without using a driver, this generated script lets you reuse your work later to communicate with the device
We can enhance the reusability of the driver by adding functions, such as the datum being used, date and time, or waypoints. The driver can be shared with users who do not need to understand in detail how to communicate with their device.
We used a GPS device to demonstrate how to configure and acquire data from external hardware without leaving the MATLAB environment. We used MATLAB and Instrument Control Toolbox to communicate with this hardware without writing a MATLAB script, demonstrated how to reuse our work using a MATLAB script automatically generated to communicate with the hardware, and how to incorporate functionality into MATLAB function calls through drivers. Using MATLAB improves work efficiency by eliminating the need to manually transfer data from one environment or learn and maintain multiple software tools.
Published 2007
Products Used
Learn More
View Articles for Related Capabilities
Troubleshooting Serial Port Interface
Serial communication is a low-level protocol for communicatingbetween two or more devices. Normally, one device is a computer, andthe other device can be another computer or a:
modem
printer
scientific instrument such as an oscilloscope or afunction generator
The serial port sends and receives bytes of information in aserial fashion — 1 bit at a time. These bytes are transmittedusing either a binary format or a text (ASCII) format.
For many serial port applications, you can communicate withyour instrument without detailed knowledge of how the serial portworks. Communication is established through a serial port object,which you create in the MATLAB® workspace.
Supported Platforms
The serial port interface is supported on these platforms:
Linux® 64-bit
macOS 64-bit
Microsoft® Windows® 64-bit
The serial port interface is supported on the same platforms as MATLAB. For updates to the list of currently supported platforms, see https://www.mathworks.com/support/sysreq/current_release/.
Adaptor Requirements
Use RS-232 interface standard with the serial port communication.Over the years, several serial port interface standards for connectingcomputers to peripheral devices have been developed. These standardsinclude RS-232, RS-422, and RS-485 — all of which are supportedby the serial port object. Of these, the most widely used standardis RS-232, which stands for Recommended Standard number 232.
In this guide, it is assumed you are using the RS-232 standard.
You need to connect the two devices with a serial cable. Formore information, see Connecting Two Devices with a Serial Cable.
Serial ports consist of two signal types: data signals and controlsignals. To support these signal types, as well as thesignal ground, the RS-232 standard defines a 25-pin connection. However,most PCs and UNIX® platforms use a 9-pin connection. In fact,only three pins are required for serial port communications: one forreceiving data, one for transmitting data, and one for the signalground. For more information, see Serial Port Signals and Pin Assignments.
Matlab Serial Interface Number
Configuration and Connection
Make sure that you have the correct instrument driverinstalled for your device. Refer to your device documentation andthe vendor website.
Make sure that your device is supported in Instrument Control Toolbox™.See Is My Hardware Supported?.
Make sure that Instrument Control Toolbox recognizes your serial ports, by using the
instrhwinfo
function with theserialport
interface name. For example:If your computer has more than one serial port, your output would look like this:
In this example the output listed three ports. List the available serial ports:
Tip
You can also use Windows device manager to see a list of available serial ports.
Make sure you can create your serial port object.You must provide one argument to create the object, the name of anavailable port. For example, create a serial object called
s
usingportCOM1
.If you do not get an error, the object was created successfully.
When you have connected, you can communicate with your device. If you have problems sending or receiving, you may need to configure communication settings such as
BaudRate
,DataBits
,Parity
,StopBits
, orTerminator
. Make sure you configure these communication parameters to match those of the connected device.See Writing and Reading Text Data and Writing and Reading Binary Data forcommunication examples.
Other Troubleshooting Tips for Serial Port
Verify Port
Verify that the serial (COM) port is listed in Windows ControlPanel > Device Manager > Ports.
Sending and Receiving
If you have problems sending or receiving, you may need to configure communication settings such as BaudRate
, DataBits
, Parity
, StopBits
, or Terminator
. Make sure you configure these communication parameters to match those of the connected device.
VISA
For serial communication, you can also use VISA with a VISA resource name, as defined in a VISA vendor utility, such as Keysight Connection Expert.
Third-party Software
For troubleshooting serial port communication, you can alsouse a third-party serial communication software, such as PuTTY orTera Term, to isolate the issue.
Incorrect Data
When doing binary data communication with read
and write
, make sure the correct data type – for example int16
, uint16
, double
– is being used with read
and write
. You should use the same data type as the instrument uses.
If reading and writing data types other than uint8
or int8
,make sure the ByteOrder
is correct.