简体   繁体   中英

Arduino Matlab serial communication speed

I have some issues in a simple Arduino - Matlab (both 2014 and 2016) serial communication. I have a simple Arduino sketch that collects values from a sensor and send them via serial. Arduino waits for a character 'r' for starting the reading/sending procedure

void loop()
{    
  if(Serial.available()) 
  {
    cmd = Serial.read();
    if(cmd == 'r') 
    {
      while(1)
      {
        accelgyro.read();
        //acc
        raw_values[0] = accelgyro.a.x;
        raw_values[1] = accelgyro.a.y;
        raw_values[2] = accelgyro.a.z;    

        //gyro
        raw_values[3] = accelgyro.g.x;
        raw_values[4] = accelgyro.g.y;
        raw_values[5] = accelgyro.g.z;

        for (j=0; j<6; j++)
        {
            Serial.write (highByte(raw_values[j]));
            Serial.write (lowByte(raw_values[j]));
        }     
       delay(2);
      }
    }
  }
}

And the correspondent Matlab code:

Arduino = serial('COM6','BaudRate',115200);
fopen(Arduino);
flushinput(Arduino)

acqSize = 1000;

pause(2)

'start'
fwrite(Arduino,'r');
tStart = tic;

while( i <=acqSize)

    if(Arduino.BytesAvailable>packetSize-1)

        lastData = fread(Arduino,packetSize) ;
        raw_matrix(:,i) =  byteToInt(lastData);
        raw_matrix(7,i) = toc(tStart);
        tStart = tic;
        i=i+1
    end
    pause(0.001);
end

where packetsize is number of bytes sent per cycle from Arduino, ie, 12

The problem is that the speed is really low, I checked the time between two reading and what I obtain is depicted in the following pic在此处输入图片说明

I have a good speed except for these spikes that periodically occur. In these cases the interval between two readings is greater than 0.1 s.

Timing in Matlab is not vary accurate as the one on your Arduino. Embedded hardware and small OSs (Operationg systems) like the one used for Arduino are hard real-time and can hold up the timing very accurate. However, Matlab needs to be run on OSs like Windows, Linux or so. These are not real-time OSs and the timing can not be accurate and predictable. So the jitter in timing may increase if OS is busy doing something else. Also, "pause(0.001)" is not achievable even for a very strong CPU. If CPU consumption is not an issue for you, you can remove the "pause" or you can use a code that take the CPU and returns faster like this:

function delay(seconds)
  % function pause the program
  % seconds = delay time in seconds
  tic;
  while toc < seconds
  end
end

More discussion can be found here: Pause function in matlab for 1 millisecond

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM