1
votes

I am trying to establish a serial link in Matlab with an Arduino board. Reading data from the board goes well. However, writing data to the board takes about a second for each block of information I send.

The code I am running to write data:

s = serial(comprt,'BaudRate',9600,'DataBits',8);
fopen(s);
fprintf(s, '%c', 'c');
fprintf(s, '%u %u %u %u \n', [A B C D]);
pause(1);
fprintf(s, '%c', 'a');
pause(1);

A, B, C, D are 8-bit numbers anywhere from 0 - 255, 'c' and 'a' are characters commands that do stuff on the Arduino board and tap into the firmware on the board.

If I do not include the pause(1) commands, so when I do not stop Matlab from executing the next command for at least a second, the serial information doesn't get through.

Can anyone help me to speed up writing stuff to the serial port? I checked with the Arduino editor, and when I enter equivalent commands via their interface, everything is fine. So the delays are not related to the Arduino board or device drivers, it's definitely on the Matlab side of things.

1
Try adding a 2 second delay immediately after opening the connection. That may allow you to remove the other delays.all or None
Dear figs, many thanks. After opening the serial I do wait a while and this is not the issue I'm afraid. I just showed the critical commands where the problem must be, according to some trouble shooting.AliceD

1 Answers

1
votes

I have used MATLAB quite a bit with Arduino. Ex: see here (http://www.instructables.com/id/Arduino-to-MATLAB-GUI-Live-Data-Acquisition-Plotti/) [see link in instructable for my GitHub Arduino and MATLAB code] and here (https://www.youtube.com/watch?v=wY3oh2GIfCI).

I believe your problem IS on your Arduino side of things.

Add this line to your setup() function:

Serial.setTimeout(100); //this will make the Arduino wait a max of only 100ms per incoming set of serial data, before moving on

Read here: http://arduino.cc/en/Serial/SetTimeout

Then, decrease the timeout progressively until you get bad results, to minimize wasted waiting time. Then increase it a bit again to ensure it's set high enough.

This is a quick and dirty method. Basically, your Arduino is set to wait 1 sec by default before continuing on, once incoming data is read in.

A better method is to use a terminating character. Ex: have the MATLAB send a terminating Newline character, and use the Arduino function Serial.readBytesUntil() to read up to the terminating character. Then, the serial input timeout will never be reached, and you can set the timeout to be long again (Ex: 1 sec), without actually having to wait for that delay.