MATLAB Programming/Writing and Reading to A Serial Port

Now that we've covered basic file input output (I'll get into more detailed file manipulation later) we can move on to the next step.

In the section Basic Reading and Writing data we already had the data in the form of a spreadsheet. How did it get to that spreadsheet and how do we send it some where else? This question will attempt to be answered in the following section. There are many ways to transmit and recieve data. I've even heard of this newfangled thing called the easternet or internet or whatever, but for now we will assume we are in a University lab with no internet connection (don't laugh I've been in this situation more times than I like to remember). In this case, we will use the computer's serial port, which implements the RS-232 physical layer protocol. Although this protocol is very slow (usually no more than 9600 bits/s), it's very simple to implement and thus it's used widely on embedded devices.

MATLAB provides us with there style of reading and writing to the serial port.

  1. You must create a serial port object.
object=serial(port,'Property name',propertyValue);

Example: I will now create a serial object called serialOne

serialOne=serial('COM1', 'BaudRate', 9600);

(for those of you more familiar with C this should look very similar to creating a handle: In fact it is the MATLAB way of making handles)

Most computers call the serial ports COM and then some number usually 1-4 (depending on how many there are). This also includes DB-9, DB-25 and other various DB type connectors.


2. Now that the computer knows there is a serial port object you have to tell it to open

the object. Use the fopen command

3. Write to the port
4. Close object.

Example:

serialOne=serial('COM1', 'BaudRate', 9600);
fopen(serialOne);
fprintf(serialOne,'textFile.txt');
fclose(serialOne);

further readingEdit

Last modified on 7 November 2010, at 04:41