I have tried fading the RGB Led with different colour format and sequence. Working of Code :-
- When value of number is 1, the Red LED fades gradually and glow up with the delay interval of 10ms with fade amount 5.
- When value of number is 2, the Green LED works as above.
- The change of state from Red to green takes 4 seconds.
Blue Led Code can also be added to this and various other colour combinations can be made, which will complex the code and add up difficulty is debugging and finding errors because every combination should have different name for fading so that it doesn't conflict with other combinations.
Here is my code. However, I need some suggestions regarding quality of my code. Is it the efficient way to do code. How can I improve the code. Any constructive suggestions would be of great help.
int RED_LED = 12; // the PWM pin the LED is attached to
int BLUE_LED = 14;
int GREEN_LED = 15;
int RedLedBrightness = 0; // how bright the LED is
int GreenLedBrightness = 0; // how bright the LED is
int RedFadeAmount = 5;
int GreenFadeAmount = 5;
unsigned long previousMillis = 0;
const long interval = 10;
unsigned long previousMillis2 = 0;
const long interval2 = 4000;
int j = 0;
void setup()
{
pinMode(RED_LED, OUTPUT);
pinMode(BLUE_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
Serial.begin(115200)
}
void loop()
{
if (millis() - previousMillis2 >= interval2)
{
previousMillis2 = millis();
j += 1;
if (j > 2)
{
j = 1;
}
Serial.print("\n");
Serial.println(j);
}
SpecialFunction(j);
}
void SpecialFunction(int Number)
{
if (millis() - previousMillis >= interval)
{
previousMillis = millis();
if (Number == 1)
{
RedGradualChange();
}
else if (Number == 2)
{
GreenGradualChange();
}
}
}
void RedGradualChange(void)
{
analogWrite(GREEN_LED, 0);
GreenLedBrightness = 0; // how bright the LED
GreenFadeAmount = 5;
analogWrite(RED_LED, RedLedBrightness);
RedLedBrightness = RedLedBrightness + RedFadeAmount;
if (RedLedBrightness <= 0 || RedLedBrightness >= 1020)
{
RedFadeAmount = -RedFadeAmount;
}
}
void GreenGradualChange(void)
{
analogWrite(RED_LED, 0);
RedLedBrightness = 0;
RedFadeAmount = 5;
analogWrite(GREEN_LED, GreenLedBrightness);
GreenLedBrightness = GreenLedBrightness + GreenFadeAmount;
if (GreenLedBrightness <= 0 || GreenLedBrightness >= 1020)
{
GreenFadeAmount = -GreenFadeAmount;
}
}
How can I improve the code
- this is not a reasonable question for this site. It is too broad. With all due respect to Majenko who is trying to help you, this is a very broad question. Plus, you keep editing the code so that answers don't make any sense. Please read How do I ask a good question?. – Nick Gammon♦ Sep 26 '16 at 8:06