Communication with Matlab

As the instruments get smarter, and interfaces grow, its crucial to be able to link your software (Matlab) with the hardware or other software, or even other computers on the network. Matlab provides this opportunity via the Instrument Control Toolbox, which allows the creation of TCP/IP or UDP objects to communicate.

Of course, as usual the matlab documentation – Controlling Instruments using TCP/IP or UDP – is awesome, but here is a brief overview. In general, I would recommend to use TCP/IP as its a more “reliable” form of communication. UDP doesn’t check whether the receiver is ready, so data transfer is not guaranteed.

One would start off by first creating a TCP/IP object. This can be done as easily as t = tcpip('RemoteHost',RemotePort); Note that you need to know the correct port number. (in case of instruments, check manual). In case of computer-computer, the software to which you want to talk to, is the communication port. In general, if you just want to send some message across, both the source and destination could agree upon any unused port. RemoteHost is at best the IP address (Domain Names work too but at times need to be defined in your “hosts” file).

The next important step is to open and test the connection. fopen(t); does it for you. An error here indicates something is wrong, and could be possibly a firewall issue.

Now to the most important part, writing and reading data from this object. fprintf(t,'Data_in_string_format'); can put the data, and an fscanf(t) at the receiver end will show the information. In case some problem occurs, the fscanf(t) has a timeout, so that the process doesn’t hang permanently. In case of problem, an easy way to check would be to see get(t,'Status') and confirm it says “open”. Typically the function strfind(string,'pattern'); is what you would use to parse the received data.

Its important to properly close all connections before using the clear command. This can be done by following fclose(t); delete(t); In case this isn’t done, then the object remains open, however it cannot be addressed, and things get complicated. It may then require a Matlab restart for the fopen(t) to work again.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s