Sending an integer variable from Matlab to Arduino

Hi guys,

I’m stuck on something and was looking for a little help. I want to do something complicated for a machine vision project, but my sticking point seems to lie in something rather trivial. I’m able to send information back and forth between Matlab and Arduino, but like a bad game of telephone, it gets all jumbled. For now let’s just say I want to set the frequency with which an LED blinks in Matlab and send the frequency to Arduino to actually drive the led. I want Matlab to send a variable that can be used with the delay() function in Arduino. So in Matlab I have,

clear all;

answer=1; % this is where we'll store the user's answer

arduino=serial('/dev/tty.usbmodem411','BaudRate',9600); % create serial communication object on port COM4
fopen(arduino); % initiate arduino communication
 
while answer
    fwrite(arduino, answer, 'int16') % send answer variable content to arduino
    answer=input('Enter led value(0=EXIT PROGRAM): '); % ask user to enter value for variable answer
end

fclose(arduino); % end communication with arduino

______________________________________

In Arduino I have

int ledPin=13;
int matlabData = 1000;

void setup() 
{
  pinMode(ledPin,OUTPUT);
  Serial.begin(9600);
}

void loop() 
{

  if(Serial.available()>0) // if there is data to read
  {
    matlabData=Serial.read(); // read data
  }
  else
  {
    Serial.print(matlabData);
    digitalWrite(ledPin,HIGH); // turn light on
    delay(matlabData);  
    digitalWrite(ledPin,LOW); // turn light off
    delay(matlabData);  
  }
  
}

Before I send a command from Matlab to Arduino for the desired delay, the LED blinks at 1000ms intervals. But if I type 1000 into the Matlab script, the LED doesn’t have a 1 second period. I believe the issue is with Matlab and Arduino (and I) not understanding the format of the variable passed between the different platforms. Any help would be GREATLY appreciated.

Thanks again everyone,
FB

edit by mod: please add code using proper tags

So what does the line in your code

Serial.print( matlabdata ) ;

actually print out ?

And can you run Serial.print( ) to the serial monitor, while you are also using serial from matlab to the arduino ??

Hi Michinyon,

Thank you for the reply. I actually didn't realize that line of code was in there. It is a relic from when I tried to pass the variable to the serial monitor, but I haven't figured out how to do that while simultaneously being connected to Matlab. So it does not in fact print out a value.

FB