Go Down

Topic: Sending Array from Arduino to MATLAB (Read 3608 times) previous topic - next topic

MrFisher

Hi everyone,
I've come across a problem sending serial data from my Arduino to MATLAB.  I should note, I am technically doing this on a Teensy 3.1, but the problem is reproducible on an Uno.

As part of a testing program I have written, I send a 900-element array of uint8 data from MATLAB to the Arduino and then back again.  Sending the data from MATLAB to the Arduino works great, no problems.  I can echo this array to the serial monitor and everything is peachy. 

However, I want to be able to send this array directly back into MATLAB (eventually in near real-time).  After doing some reading, it appears that one can either use the fread function directly or fscanf inside a loop to read a fixed amount of binary data into MATLAB from the (connected) serial port.  However, no matter what I try, I always receive a "Warning: The specified amount of data was not returned within the Timeout period."  Here is some minimal example code that reproduces the problem:

Arduino
Code: [Select]
const int button1=8;

byte data_array[900];

void setup(){
Serial.begin(115200);
pinMode(button1,INPUT);
digitalWrite(button1,HIGH);
}

void loop(){
if(Serial.available()){Serial.readBytes((char*)data_array,900);}

if(digitalRead(button1)==LOW){
    delay(5);
   while(digitalRead(button1) ==LOW){delay(5);}
for(int i=0;i<900;i++){Serial.print(data_array[i]);}
  }
   
}


MATLAB
Code: [Select]
COM1=serial('/dev/tty.usbmodem26511','BaudRate',115200,'OutputBufferSize',900,'InputBufferSize',900);
fopen(COM1);
pause(1);

data_in=uint8(randi(240,[900,1]));
fwrite(COM1,data_in,'uint8');
data_out=fread(COM1,900,'uint8');

fclose(COM1);


As I said, the Arduino can print data_array just fine to a standard Serial terminal.

Things I have tried:
1.  Setting the MATLAB input buffer and read length to very low values, e.g. 100, in case a few bytes were missing from the received array.
2.  Replacing fread with fscanf (formatted for decimals) in a loop.
3.  Setting different timeout periods for the MATLAB serial reads.

I've seen a few people with similar issues on different forums, but I can't find anybody who seems to have resolved the problem.  I would be appreciative of any help.

Thanks,
MrFisher

XuechunWang

I have the same question like u. Have u solved it?

Go Up