1

I've two LEDs connected to the arduino uno's pin 12 and 13. I want to control the LEDs independently from the MATLAB serial command.

Here is my MATLAB serial command from where I'm sending char array

s = serial('COM4','BaudRate',9600);
fopen(s);
output = [2,1];
data = char(output);
fprintf(s,'%d',data);
fprintf(s);

And this is my Arduino code to receive char array

char d[4];
void setup()
{
   Serial.begin(9600);
   pinMode(12,OUTPUT);
   pinMode(13,OUTPUT);
}

void loop()
{
    if(Serial.available()>0)
  {
    for(int i=0;i<3;i++)
    {
      d[i] = Serial.read();
    }
    d1 = d[0]-'0';
    if (d1 == 1)
   {
    digitalWrite(12, HIGH);
    delay(1000);
     digitalWrite(12, LOW);
    delay(1000);
    }
  else if (d1 == 2)
    {
    digitalWrite(12, HIGH);
    delay(2000);
    digitalWrite(12, LOW);
    delay(1000);
    }
    d2 = d[1]-'0';
    if (d2 == 1)
   {
    digitalWrite(13, HIGH);
    delay(1000);
     digitalWrite(13, LOW);
    delay(1000);
    }
  else if (d2 == 2)
    {
    digitalWrite(13, HIGH);
    delay(2000);
    digitalWrite(13, LOW);
    delay(1000);
    }
  }
}

The MATLAB command is intended to keep the LED on for the given seconds. When I tried this code for one LED(sending only single char) it worked fine. But when I tried it for two LEDs it turns on only LED connected to pin 12 twice.

Eg: MATLAB command output = [2,1], turns on LED(pin 12) for 2 sec and then for 1 sec but I want it should be to turn on LED(pin 12) for 2 sec and LED (pin 13) for 1 sec.

2
  • And the question is? Commented Mar 17, 2017 at 14:13
  • If you look at the serial data sent in a terminal what is it? If the serial data is "2,1" then you want d2 = d[2]-'0'; not d2 = d[1]-'0'; Also instead of a load of if statements wouldn't be easier to get the time by multiplying the value by 1000? digitalWrite(12, HIGH);delay(d1*1000); Commented Mar 17, 2017 at 14:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.