Need Help with the code

Hi! There,
I need help with the arduino project that I am working on to learn about arduino programming but I got stuck because of some issue in my code. So, anyone can help me with this.

Here’s the project:
Using the RGB LED have button 1 turn on the RGB light, cycling through the three colours in repetition(ex:Red→ Green→ Blue → Red→ ect.) with a 500 msec delay. Then use the second button to shut off the lights. The light should shut off immediately after the currentcolour and not continue to cycle after the button is pressed.

I have written the code so far this but in this code the button 1 is working properly but the button 2 is not :

int RGBRedPin = 9 ;
int RGBGreenPin = 10 ;
int RGBBluePin = 11;
int button1Pin = 2; 
int button2Pin = 3;
int flag = 0;

void setup() {
  pinMode(RGBRedPin, OUTPUT);
  pinMode(RGBGreenPin, OUTPUT);
  pinMode(RGBBluePin, OUTPUT); 
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
}

void loop() {
  if (digitalRead(button1Pin)==HIGH) { 
    if(flag==0) {
    flag = 1;
    }
  }
   
  else if (digitalRead(button2Pin)==HIGH) {
    if(flag==1) {
      flag=0;
    }
  }
  if(flag==1) {
    digitalWrite(RGBRedPin, HIGH);
    digitalWrite(RGBGreenPin, LOW);
    digitalWrite(RGBBluePin, LOW);
    delay(500);
    digitalWrite(RGBRedPin, LOW);
    digitalWrite(RGBGreenPin, HIGH);
    digitalWrite(RGBBluePin, LOW);
    delay(500);
    digitalWrite(RGBRedPin, LOW);
    digitalWrite(RGBGreenPin, LOW);
    digitalWrite(RGBBluePin, HIGH);
    delay(500);
  }
  if(flag==0) {
     digitalWrite(RGBRedPin, LOW);
    digitalWrite(RGBGreenPin, LOW);
    digitalWrite(RGBBluePin, LOW);
  }
}

Hey Guys,

Finally, make the project run.

int RGBRedPin = 9 ;
int RGBGreenPin = 10 ;
int RGBBluePin = 11;
int button1Pin = 2; 
int button2Pin = 3;
int flag = 0;

void setup() { 
  pinMode(RGBRedPin, OUTPUT);
  pinMode(RGBGreenPin, OUTPUT);
  pinMode(RGBBluePin, OUTPUT); 
  pinMode(button1Pin, INPUT_PULLUP); 
  pinMode(button2Pin, INPUT_PULLUP);
}

void loop() { 
  if (digitalRead(button1Pin)==HIGH) { 
    if(flag==0) {
    flag = 1;
    }
  }
   
  else if (digitalRead(button2Pin)==HIGH) {
    if(flag==1) {
      flag=0;
    }
  }
  if(flag==1) {
    digitalWrite(RGBRedPin, HIGH);
    digitalWrite(RGBGreenPin, LOW);
    digitalWrite(RGBBluePin, LOW);
    delay(500);
    if (digitalRead(button2Pin)==HIGH) {
      flag=0;
      return;
    }
    digitalWrite(RGBRedPin, LOW);
    digitalWrite(RGBGreenPin, HIGH);
    digitalWrite(RGBBluePin, LOW);
    delay(500);
    if (digitalRead(button2Pin)==HIGH) {
      flag=0;
      return;
    }
    digitalWrite(RGBRedPin, LOW);
    digitalWrite(RGBGreenPin, LOW);
    digitalWrite(RGBBluePin, HIGH);
    delay(500);
  }
  if(flag==0) {
    digitalWrite(RGBRedPin, LOW);
    digitalWrite(RGBGreenPin, LOW);
    digitalWrite(RGBBluePin, LOW);
  }
}

Great to hear that. Continue your learning and certification at LearnVern.

1 Like