Let the future tell the truth and evaluate each one according to his work and accomplishments. The present is theirs; the future, for which I really worked, is mine. (Nikola Tesla)

17/06/2011

Serial Communication in MATLAB - 1

In these series of article about serial communication in MATLAB, I explain how we can use MATLAB to interact with hardware which are connected to a PC through a serial port. Notebooks mostly don't have serial port, but USB ports. So, you can use a USB to Serial Converter as well.

We firstly learn some basic concepts like terminator, buffer, parameters, etc.


-Terminator-

We may roughly say that a terminator is used to specify the end of a message. For instance, the format in asynchronous serial communication for a 10-bit character frame is just like a start bit, followed by 8 data bits and one stop bit in the end. The stop bit here defines a stop period. Again, we may roughly say that the same logic is reasonable for terminator.

So, what are we going to do to configure terminator? We can use any integer value ranging between 0-127 for defining an ASCII character or we can directly configure terminator to the ASCII character. We may configure its value as "CR" or "13" which is carriage return. We may also configure its value as "LF" or "10" which is line feed. We may also configure terminator to CR/LF which is a carriage return followed by a line feed or vice versa. We can also set it as 1-by-2 cell array, first cell is the read terminator and the second one is the write terminator.

While we are writing string data to the device connected to the serial port object, we use 'fprintf' command. 'fprintf' also adds the terminator character at the end of the string that you send. It is new line (\n) by default or it is specified by the terminator property which you set while you are defining serial port object at first. So, you have a chance to change it as how it's defined in the documentation of external device. In your works, you can use "HHD Serial Port Monitor" to see what MATLAB sends as terminator.

While we are getting string data from external device, we use 'fscanf' command. As in the 'fprintf' command, 'fscanf' command also uses terminator. Any reading operation is completed when a terminator, which is specified by terminator property, is read. For instance if your device use "LF" (\n) as terminator, you can set your terminator property of serial port object as "LF" in MATLAB and so the reading process is completed when MATLAB gets terminator value from device.



ShareThis