AdSense

Tuesday 10 February 2015

Serial communication with Matlab or C#

(Deutsche Version) In the last post, I showed how to read out a heartbeat sensor (Read out heartbeat sensor). In this post, I want to explain how to read this data with Matlab or C#. I want to start with Matlab. At first, you have to open a serial port:

s = serial('COM3');
fopen(s);


You simply have to plug in the number of your COM port. Afterwards you can read all existing characters:

str = fscanf(s);

Keep in mind that it can also occur that the Arduino has only sent half of its message when the computer is reading all existing characters, and in the next read instruction from the computer, the rest of the message (and possibly further messages) is read in. In the end you should close the port:

fclose(s);

Now, I want to explain how to do this in C#. Again, you have to open a port:

port = new SerialPort("COM3", 9600);
port.Open();

Afterwards, you can read in all existing characters (analog to the example with Matlab):

string indata = sp.ReadExisting();

In C#, you don't have to close the port because this happens automatically when closing the program.

No comments:

Post a Comment