Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I would like to send more than 150 integers(16-bit) from Matlab(R2015a) to Arduino(Mega 2560). For this reason, I am sending those numbers in an array. However, the buffer size is 64 bytes. My solution is here: After Matlab writes the array to buffer, it waits a message(number) from Arduino. After Arduino reads the buffer, it sends a message(number) to the Matlab.

Matlab Code:

arduino=serial('COM5','BaudRate',9600);
fopen(arduino);
q=150;
X=rand(1,q);

d=floor(q/64);
r=rem(d,64);

n=1;
while(n<=d+1)

    if(n~=d+1)
        Z=[];
        for w=(64*(n-1)+1):64*n
            Z=[Z X(w)];
        end

        fprintf(arduino,'%d',Z);

        b1=fread(arduino,1);

        if(b1==99)
            n=n+1;
        end
    else
        Z=[];
        for w=1:r
            Z=[Z X(w)];
        end

        fprintf(arduino,'%d',Z);

        b2=fread(arduino,1);

        if(b2==99)
            n=n+1;
        end
    end       
end


fclose(arduino);

Arduino Code:

char matlabdata[64];
int index;
int mode=0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if(mode==0){
    if(Serial.available()>0){

       index = Serial.readBytesUntil(' ',matlabdata,64); 
       matlabdata[index] = '\0'; 
       mode=1;
    }    
  }

  else if(mode==1){
    Serial.write(B01100110);
    mode=0;
    for(int x=0; x<64;x++){
      matlabdata[x]='\0';
    }
  }

  Serial.flush();


}

Matlab Error:

Unexpected error: The number of bytes written must be less than or equal to OutputBufferSize-BytesToOutput..
share|improve this question

Using serial.fprintf you are writing text to your device, this requires one byte for each digit. From your description I assume that you want to write individual bytes, use serial.fwrite for this purpose.

share|improve this answer
    
Daniel, I would like to write the array into buffer at one connection. How can I handle it with fwrite? – blknt Nov 14 '15 at 12:54
    
I don't understand your question. – Daniel Nov 14 '15 at 13:04
    
I would like to send the array to Arduino using buffer once. – blknt Nov 14 '15 at 13:06

You should add OutputBufferSize,InputBufferSize, like this:

arduino=serial('COM7','BaudRate',115200,'OutputBufferSize',2400,'InputBufferSize',2400);

where '2400' is size of array. Good luck !

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.