0
votes

I am trying to build a small program to control 3 led's. The led's are connected on pins 11 (red), 12 (yellow) and 13 (green).

For some to me unknow reason the following code does not seem to work. If I enter 1 in the serial input, the yellow led will light up. But after about 1 second it's turned off again and the red led is turned on. It looks to me like there is alway's a 0 on the serial input, but that can't be right is it?

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0) {
    changeLed(Serial.parseInt());
  }
}

void changeLed(int color) {
  turnAllLedsOff();
  turnOnLed(color);
}

void turnOnLed(int ledPin) {
  enum ledControl {RED, YELLOW, GREEN};
  if(ledPin == RED) {
    digitalWrite(11, HIGH);
  }
  if(ledPin == YELLOW) {
    digitalWrite(12, HIGH);
  }
  if(ledPin == GREEN) {
    digitalWrite(13, HIGH);
  }
}

void turnAllLedsOff() {
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
}
1

1 Answers

2
votes

I believe your Serial Monitor's line ending setting is set to Both NL & CR. One triggers Serial.parseInt() and the other triggers another Serial.parseInt(). So, each serial input, you are calling the function twice. And the second one always returns 0 as newline only (or carriage return only) is not valid digits. That is why your red LED gets turned on. Try other line ending settings.