Serial Communication error between Matlab and Arduino Meg2560

i'm trying to just send a number from Matlab to my arduino. It does connect and communicate, however, the returned number from the arduino is not what matlab sent. Here is my Matlab Code:

arduino = serialport('COM7',9600,"Timeout",15);

pause(1)

% Send a number to Arduino

flush(arduino);

write(arduino,6, 'string');

pause(1);

% Read the number sent back by Arduino

receivedNumber = read(arduino, 1,'string');
disp(receivedNumber);

Arduino Code:

int duty_cycle;

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


}


void loop() {

  
  while(Serial.available()>0){
    duty_cycle = Serial.read();
    Serial.println(data_num);
    
  }
} 

When I do disp(receivedNumber), it keeps showing the number 0. If I change the data type in my matlab code to 'int8' it'll only return the number 48. Not sure why this is. I already read through the Serial Input Basics forum.

48 is the numerical value of the symbol or ASCII character '0'.

I see. So how can I get it to communicate back the correct number?

You got what you see because you changed it right there in that calculation. You received a character, not a number that can be use in a calculation.

Ahh, I set duty_cycle as an int rather, now. It still gives back a 0 to matlab

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