I'm trying to get an RGB led to make different light effects when a button is pressed. My intention is for the led to start with a series of colors, go to a fixed color (in my case green) and, finally, go to a rainbow-like effect with all possible colors. The problem I found is that when I press the button it doesn't change the mode, because it doesn't recognize when I press it. I understand that the problem is that the delay function prevents the Arduino from reading the value of the button, but I don't know how to replace it, nor how to make the code recognize the button at any time. Can somebody help me? I leave the code below in case it helps. For the record, I don't know how to program and that this is a project I wanted to do for myself, but of course it's getting hard.
//LED FORMATO RGB
#define LED_ROJO 9
#define LED_VERDE 11
#define LED_AZUL 10
#define botonpin 3
int rojo = 0;
int verde = 0;
int azul = 0;
int time = 3;
int time2 = 2000;
int i = 1;
int estadoboton = 0;
void cambiarcolor (int rojo,int verde,int azul)
{
analogWrite(LED_ROJO, rojo);
analogWrite(LED_VERDE, verde);
analogWrite(LED_AZUL, azul);
}
void setup()
{
pinMode(LED_ROJO, OUTPUT);
pinMode(LED_VERDE, OUTPUT);
pinMode(LED_AZUL, OUTPUT);
pinMode(botonpin,INPUT);
Serial.begin(9600);
}
void loop()
{
if (digitalRead(botonpin) == HIGH){
(i++);
if (i>3) i =1;}
Serial.println(i);
delay(200);
switch (i){
case 1:
cambiarcolor(255, 0, 0);
delay(time2);
cambiarcolor(0, 255, 0);
delay(time2);
cambiarcolor(0, 0, 255);
delay(time2);
break;
case 2:
analogWrite(LED_VERDE,255);
break;
case 3:
for (int verde=255;verde>=0;verde--){
cambiarcolor(0,verde,255);
delay(time);
}
for (int rojo=0;rojo<=255;rojo++){
cambiarcolor(rojo,0,255); delay(time);
}
for (int azul=255;azul>=0;azul--){
cambiarcolor(255,0,azul);
delay(time);
}
for (int verde=0;verde<=255;verde++){
cambiarcolor(255,verde,0);
delay(time);
}
for (int rojo=255;rojo>=0;rojo--){
cambiarcolor(rojo,255,0);
delay(time);
}
for (int azul=0;azul<=255;azul++){
cambiarcolor(0,255,azul);
}
break;
}
}
This is the circuit I've been using, I don't even know if it's done right:
