Hey!
I just got my first arduino, and decided to try and make a RGB-led to dim from zero to full to zero first in red, then in blue and then in green. It works for red and blue, but then, instead of green, the blue led goes twice! I appreciate an answer. It is probably really basic, but I cant figure it out
Here is the code:
int red=5; //pin for red led is 5
int green=6; //pin for green led is 6
int blue=9; //pin for blue led is 9
int value=0; //the output value to declare how strong the led will glow (0-255)
int dim=5; //the amount the led will change in strenght each loop
int mycounter=0; //value to keep track of the amount of cycles, so that the arduino knows when to switch to the new color
int mycounterchange=1; //the amount the counter will change for each cycle
void setup() {
// put your setup code here, to run once:
pinMode(red,OUTPUT); // red light is an output
pinMode(green,OUTPUT); //green light is an output
pinMode(blue,OUTPUT); //blue light is an output
Serial.begin(9600); //seral communication to see if the code is doing what i intended
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print(value); // printing in serial monitor
Serial.print(" "); // separate led strenght value from counter
Serial.println(mycounter); //printing the counter
if(mycounter<=105){ //105 loops seem to be what is needed to dim from 0 to 255 and down to 0
analogWrite(green,LOW); //i only want the red light to glow first
analogWrite(blue,LOW); // ditto
analogWrite(red,value); // ditto
value=value+dim; //to make the dim effect, i will add the dim amount to the strenght value from the last loop
if(value>255){ // to dim down instead of continuing up, the dim amounbt goes negative after the LED output reaches 255
dim=-dim;
}
if(value<0){ //when getting down to 0 output, it starts going up agian
dim=-dim;
}
}
else if(105<mycounter<=210){ //so for the second led dim from 0 to 255 and back i want the blue light to go.
analogWrite(green,LOW);
analogWrite(blue, value);
analogWrite(red,LOW);
value=value+dim;
if(value>255){
dim=-dim;
}
if(value<0){
dim=-dim;
}
}
else if(210<value<=315){ // for the third dim cycle i want the green to go.
analogWrite(green,value);
analogWrite(blue,LOW);
analogWrite(red,LOW);
value=value+dim;
if(value>255){
dim=-dim;
}
if(value<0){
dim=-dim;
}
}
mycounter=mycounter+mycounterchange; //adding one to the counter at the end of each cycle
if(mycounter>315){
mycounterchange=-mycounterchange; //after the 3 cycles, it will go backwards
}
if(mycounter<0){
mycounterchange=-mycounterchange; //when reaching 0, it will start over agian
}
delay(30);
}