MATLAB-Arduino Serial Communication

Hello, I am not familiar with serial ports, so I would appreciate it if someone can validate the following MATLAB code and Arduino sketch. I want to send an integer from MATLAB to the Arduino. I want the integer to be sent back and displayed in MATLAB. I am not able to receive the correct integer back.

MATLAB code:

s = serial('/dev/tty.KeySerial1')
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',9600);
set(s,'Parity','none');
fopen(s);
a='b';
while (a~='a');
    a=fread(s,1,'uchar');
end 
if (a=='a')
    disp('serial read');
end 
fprintf(s,'%c','a');
mbox= msgbox('serial com set up complete'); uiwait(mbox);
fprintf(s, '%d\n', 589367);
fscanf(s,'%s')

Arduino sketch:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  // check serial communication 
  Serial.println('a');
  char a='b';
  while (a !='a')
  { a=Serial.read();
  }

}

void loop() {
  // put your main code here, to run repeatedly:
  while(Serial.available()==0); 
  int val=Serial.parseInt();
  Serial.print("integer received: ");
  Serial.println(val);
}

The result displayed on MATLAB :
'interreceived: -457'

Thanks

did you try to use the 'Test & Measurement Tool' within matlab instead of your MATLAB code to see what you get as reply when you send something to the arduino using 'Serial'?

do you get the same result?

https://uk.mathworks.com/help/instrument/using-the-test-measurement-tool.html

I am not familiar with Matlab but for receiving data on the Arduino have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

The technique in the 3rd example will be the most reliable. It is what I use for Arduino to Arduino and Arduino to PC communication.

You can send data in a compatible format with code like this (or the equivalent in any other programming language)

Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker

…R