const int buttonPin = 2; // the number of the pushbutton pin
const int redPin = 9; // the number of the red LED pin
const int greenPin = 10; // the number of the green LED pin
const int bluePin = 11; // the number of the blue LED pin
int buttonState = 0; // variable for reading the pushbutton status
int lastButtonState = 0; // variable to store the previous state of the button
int colorState = 0; // variable for tracking the current color
void setup() {
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input (with external pull-up resistor)
pinMode(redPin, OUTPUT); // initialize the red LED pin as an output
pinMode(greenPin, OUTPUT); // initialize the green LED pin as an output
pinMode(bluePin, OUTPUT); // initialize the blue LED pin as an output
digitalWrite(redPin, LOW); // start with all LEDs off
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
}
void loop() {
buttonState = digitalRead(buttonPin); // read the state of the pushbutton
if (buttonState == LOW && lastButtonState == HIGH) { // check if the pushbutton is pressed
colorState++; // increment color state
if (colorState > 2) { // wrap around color states
colorState = 0;
}
changeColor(colorState); // change the color of the LED
delay(1000); // delay for 500 milliseconds
}
lastButtonState = buttonState; // update the last button state
}
void changeColor(int state) {
switch (state) {
case 0:
setColor(255, 0, 0); // Red
break;
case 1:
setColor(0, 255, 0); // Green
break;
case 2:
setColor(0, 0, 255); // Blue
break;
}
}
void setColor(int red, int green, int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}