Borrar filtros
Borrar filtros

Unable to do Serial Communication between Arduino and Matlab

3 visualizaciones (últimos 30 días)
Aamir Ishaq
Aamir Ishaq el 28 de Mayo de 2015
Editada: Ishi el 6 de Mzo. de 2017
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);

Respuestas (2)

Ishi
Ishi el 6 de Mzo. de 2017
Editada: Ishi el 6 de Mzo. de 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 el 19 de Nov. de 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.

Categorías

Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by