2
votes

I am sending a string data to Arduino from Matlab using the following code:

clear s;
s=serial('COM4','BAUD', 9600);  % Baud rate and COM port
fopen(s);
value1=('11,222;333<444>555?666');
display('data sent');
fprintf(s,'%s\n',value1);
fclose(s);

I am receiving and processing the string in Arduino using the following code:

String command;
int i;
float data_rec;
void setup() {
  // put your setup code here, to run once:
  command="11,222;333<444>555?666";
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() >0){
    String command=Serial.readString();
    parseCommand(command);
    data_rec=Serial.parseInt();
    Serial.println("data_rec");
    Serial.println(data_rec);
  }
}

void parseCommand(String com){
  String F_d;
  String E_m;
  String L_p;
  String S_v;
  String H_d;
  String L_t;

  F_d=com.substring(0,com.indexOf(','));
  E_m=com.substring(com.indexOf(',')+1,com.indexOf(';'));
  L_p=com.substring(com.indexOf(';')+1,com.indexOf('<'));
  S_v=com.substring(com.indexOf('<')+1,com.indexOf('>'));
  H_d=com.substring(com.indexOf('>')+1,com.indexOf('?'));
  L_t=com.substring(com.indexOf('?')+1,com.length());

 Serial.println(com);
 Serial.println("F_d:");
 Serial.println(F_d);
 Serial.println("E_m:");
 Serial.println(E_m);
 Serial.println("L_p:");
 Serial.println(L_p);
 Serial.println("S_v:");
 Serial.println(S_v);
 Serial.println("H_d:");
 Serial.println(H_d);
 Serial.println("L_t:");
 Serial.println(L_t);
}

This does not work with Matlab. However, when I send the same string from the Serial Monitor, it seems to work.

Why aren't I getting any output for the Matlab code? I am checking the data sent and received by Arduino over serial by monitoring the serial port using Serial Monitoring Studio.

2

2 Answers

1
votes

You are probably using the wrong terminator on your serial connection.

I don't have an Arduino handy, but the terminator CR/LF should work.

The change to your code is:

s=serial('COM4','BAUD', 9600, 'Terminator','CR/LF');  % Baud rate and COM port

Good luck, and if the first try isn't successful, try the other two terminators.

I'm 90% certain this will solve your problem, I learned about this quirk the hard way on some motor controllers. :)

0
votes

You have to set a break. Because the Arduino restarts after fopen ...

clear s;
s=serial('COM4','BAUD', 9600);  % Baud rate and COM port
fopen(s);
pause(1);
value1=('11,222;333<444>555?666'); 
display('data sent');
fprintf(s,'%s\n',value1);
fclose(s);