Arduino to Matlab Serial Data Connection

Hi all, first post on these forums so I apologize if didn’t do things according to a correct format.

I’m building a GUI in Matlab that sends data values through a serial connection. The goal is to update variables on the Arduino through the GUI, and then send the values of the variables back to Matlab to confirm they were changed.

I have two different variables to update, so my approach for updating is to convert the int values I send in to strings appended to an ‘identifying letter’ (ex. 123 becomes ‘a123’ for variable a and 456 becomes ‘b456’ for variable b etc.). The arduino receives the string, analyzes the identifier and extracts the number to store it in the variable.

My issue is that the data coming back to Matlab is really erratic, or just completely wrong. I’m not sure what I am doing wrong. The Arduino Code is posted below:

//inputs
const int numSettingInputs=2;
double inputDataArray [numSettingInputs];
String charValue = "";
int setTemp=20;
int setFan=0;

//outputs
int currentTemp=20;


double StrToDouble(String str)
{
  char carray[sizeof(str) + 1]; //determine size of the array
  str.toCharArray(carray, sizeof(carray)); //put sensorString into an array
  return atof(carray);
}


void outputSensorData()
{
  Serial.println(setTemp);
  Serial.println(setFan);
}

void identify (String strValue)
{
  //separate
  char identifier;
  identifier = strValue[0];
  int strLen=sizeof(strValue);
  char value [strLen-1];
  for (int i=0;i<(strLen-1);i++)
  {
    value[i]=strValue[i+1];
  }
  //Serial.println(StrToDouble(value));
  
  //identify
  if (identifier = 'a')
  {
    setTemp=StrToDouble(value);
  }
  else if(identifier='b')
  {
    setFan=StrToDouble(value);
  }
}

void setup()
{
  Serial.begin(9600);
  for (int i=0;i<numSettingInputs;i++)
  {
    inputDataArray[i]=0;
  }
}

void loop()
{  
  //get serial data
  if(Serial.available()>0)
  {
    charValue=String(Serial.readString());
  }
  char p [sizeof(charValue)];
  charValue.toCharArray(p,sizeof(charValue));
  
  //identify data and modify existing settings
  identify (p);

  //output sensor data
  outputSensorData();
}

I did not include the entirety of my matlab code for the sake of brevity, but I am establishing a connection through the command:

s=serial('COM3','BaudRate',handles.baudRate);

I send string values (which I checked are in correct form) with:

fprintf(s,output);

I scan for and format incoming strings with:

try
        if s.BytesAvailable()>0;
        t=fscanf(s,'%f');
        end
    catch 
        disp('Error!');
    end

What does readString() do? I can’t see it in the Arduino reference

You seem to have very complicated code to do something simple.

Maybe the examples in serial input basics will be useful

…R