how to send serial data using loop to arduino.

2 vues (au cours des 30 derniers jours)
Venkat damodaran Sudireddy
i have tried the following code in matlab, there are no errors, the command window is showing correct answers but the leds at pin 11,12 which I put on the arduino are not glowing.
one more thing is---->the RX led in glowing contineously.
what would might be the problem, why my leds at pins 11,12 are not glowing contineously.
somebody please help
///////////////////////////////////////////////////
clear all
clc
delete(instrfindall)
arduino=serial('COM5','BaudRate',9600); % create serial communication object on port COM5
fopen(arduino); % initiate arduino communication
while 1
for r=1:10
d=rem(r,2)
if d==1
fprintf(arduino,'1');
else
fprintf(arduino,'2');
end
end
end
fclose(arduino); % end communication with arduino
delete(arduino);
clear('arduino');
///////// * arduino code*///////////////////////////////////////////////////////////////////
int incomingByte = 0; // for incoming serial data
int led1 = 11;
int led2 = 12;
void setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{
incomingByte = Serial.read();
if(incomingByte=='1')
{
digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
}
else if(incomingByte=='2')
{
digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
}
else
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
}
}
  1 commentaire
Venkat damodaran Sudireddy
the leds are not glowing even if i removed the while loop

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 14 Mar 2016
Your code on the arduino side is counting on the fact that for serial ports, fprintf(fid, '1') means the same as fprintf(fid, '%s\n', '1') and so a newline is being queued along with the '1'. That newline is needed for the code to get to the "else" that turns off of the LEDs, since you do not turn either one off until you get a character that is not '1' or '2'
Your loop() code does not wait for serial input: it checks if there is some and does nothing if there is none. I do not know if your loop() routine will be called repeatedly by some code not shown ?

Catégories

En savoir plus sur MATLAB Support Package for Arduino Hardware dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by