Unable to do Serial Communication between Arduino and Matlab

6 views (last 30 days)
I am trying to send data from MATLAB to Arduino using the following code for Arduino and the second one for the MATLAB.
Both codes work fine and when I press 1 LED lights up and when press 2 LED switches off. But actually what I am trying to do is when MATLAB runs code it automatically sends 1 to the Arduino and the LED turns on. I have tried many changes but can't do this.
When I am trying to run the third code (given below) the Arduino status LED blinks to show that it received something, but my actual LED which is connected to pin 13 is still off.
int ledPin=13;
int matlabData;
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
if(matlabData==1)
digitalWrite(ledPin,HIGH); // turn light on
else if(matlabData==2)
digitalWrite(ledPin,LOW); // turn light off
}
}
(MATLAB)
clear all
clc
answer=1; % this is where we'll store the user's answer
arduino=serial('COM4','BaudRate',9600); % create serial communication object on port COM4
fopen(arduino); % initiate arduino communication
while answer
fprintf(arduino,'%s',char(answer));
answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
end
fclose(arduino);
(MY edit code)
clear all
clc
answer=1;
arduino=serial('COM4','BaudRate',9600);
fopen(arduino);
%while answer
printf(arduino,'%s',char(answer));
answer='1'
%end
fclose(arduino);

Answers (2)

Ishi
Ishi on 6 Mar 2017
Edited: Ishi on 6 Mar 2017
clear all
clc
answer=1;
arduino=serial('COM3','BaudRate',9600);
fopen(arduino);
while answer
answer=input('Enter 1 or 2, 0=EXIT PROGRAM: ');
fprintf(arduino,'%d', answer);
end
fclose(arduino);

Madhu Govindarajan
Madhu Govindarajan on 19 Nov 2015
If you are trying to turn on LEDs using MATLAB on an Arduino board, you can simplify this by downloading the support package from here - http://www.mathworks.com/hardware-support/arduino-matlab.html
And of course you can do much more using the support package.

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!