LED RGB

So I made some code to have my LED's turn on 1 by 1, perhaps anyone knows how to make this better using variables.

const int PIN_LED_RED = 4;
const int PIN_LED_GREEN = 5;
const int PIN_LED_BLUE = 6;
const int PIN_LED_YELLOW = 7;

void setup() {
  Serial.begin(9600);;
  pinMode(PIN_LED_RED, OUTPUT);
  pinMode(PIN_LED_GREEN, OUTPUT);
  pinMode(PIN_LED_BLUE, OUTPUT);
  pinMode(PIN_LED_YELLOW, OUTPUT);
}

void loop() {
  digitalWrite(PIN_LED_RED, HIGH);
  delay(1000);
  digitalWrite(PIN_LED_GREEN, HIGH);
  digitalWrite(PIN_LED_RED, LOW);
  delay(1000);
  digitalWrite(PIN_LED_GREEN, LOW);
  digitalWrite(PIN_LED_BLUE, HIGH);
  delay(1000);
  digitalWrite(PIN_LED_YELLOW, HIGH);
  digitalWrite(PIN_LED_BLUE, LOW);
  delay(1000);
  digitalWrite(PIN_LED_YELLOW, LOW);
  delay(1000);
}

What exactly do you want to use variables for ?

You could replace the delay() parameter with an int variable set to 1000 but it would behave the same way. Are you envisaging changing the value of such a variable using user input or something like that ?

No, thought that maybe this code could be simplified but if it is adequate then that's fine.

It could be shortened. That probably won't make it simpler.

If you increased the number of LEDs or the length or complexity of the sequence, your code could become much longer and making major changes to it could become quite painful and tedious. Then, it could be made shorter and relatively simpler.

Also, if you change it in a way that needs to react to external inputs such as buttons, then you would probably need to remove the delay() functions and completely re-write it in a style/technique often called a "state machine". This could not be called "simpler", but it would be necessary to get the code to react quickly to button presses.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.