Unable to do Serial Communication between Arduino and Matlab

조회 수: 4 (최근 30일)
Aamir Ishaq
Aamir Ishaq 2015년 5월 28일
편집: Ishi 2017년 3월 6일
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);

답변 (2개)

Ishi
Ishi 2017년 3월 6일
편집: Ishi 2017년 3월 6일
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 2015년 11월 19일
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.

카테고리

Help CenterFile Exchange에서 MATLAB Support Package for Arduino Hardware에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by