Serial Communication, datatype issue

Hi all, I met a problem using serial communication between MATLAB and Arduino.
My MATLAB code is computing variables in real-time and sending the result to Arduino via Serial Port. It works well when there is only one variable to write into the serial port. But I have three variables to write into the serial pot and to be received by the Arduino controller. I want to send an array to Arduino so that three variables are ordered well so that it can be taken easily by Arduino but failed.
The code is used to autonomously compute desired motor actuation and send the command to different motors for actuation via Serial Communication.
The method I used to receive data on the Arduino side is like this:

float parameters[3];

void setup(){
  Serial.begin(9600);
  while(!Serial || Serial.available() <= 0);
  for (int i=0; i<3; i++){
    parameters[i] = Serial.parseFloat();
  }
}
void loop(){
  for(size_t i=0; i<3; ++i){
    Serial.print(parameters[i]);
    Serial.print(i<2 ? '\t' : '\n');
  }
}

The MATLAB side to send the data is like this:

measurement_interval = 5.0;ec_ref_thickness = 2.0;e_ref_thickness = 3.0;
parameters = [measurement_interval ec_ref_thickness e_ref_thickness];
arduino = serialport("COM11",9600);
fprintf(arduino, '%f', parameters);
fprintf(arduino, '\n');
output = fread(arduino,3,'float');

Based on some online tutorials, seems I successfully passed the data between MATLAB and Arduino. However, what I get on MATLAB is 3x1 double array
[6.33692931462093e-10;
4.00259270172398e-11;
4.99087882133154e-10]
There is some error about datatype, which is updated as above. Are there any suggestions? Appreciate a lot!

That code doesn't receive anything. It just prints the contents of the parameters array. Please post your entire sketch.

How will you know if the Arduino looses sync with the MATLAB serial output?

Have a look at the serial input basics tutorials. I think example 3 will help you.

1 Like

Hi, I just updated the data receiving part, please have a look.

Thanks very much! I will have a look.

If you are dealing with simple tab, space, comma, etc. delimited lines, then the textparser library may be of interest.

Example:

#include <textparser.h> 

// We assume that the line is of the form "1, 123, 234"
TextParser parser(", ");
char buf[80];

// ...

void loop() {
  size_t bytesRead = Serial.readBytesUntil('\n', buf, sizeof(buf));
  buf[min(bytesRead, sizeof(buf) - 1)] = 0;

  byte data[3];
  parser.parseLine(buf, data);
  // `data` now contains 1, 123 and 234.

If it takes the MATLAB program more than one second to write the line, you might want to have a look at Serial.setTimeOut.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.