Advertisement
MinaDarsh

Arduino RGB LED with Potmeter and Mode Switching

Jul 24th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. int r = 6;              // select the output pin for the Red LED
  2. int g = 5;              // select the output pin for the Green LED
  3. int b = 3;              // select the output pin for the Blue LED
  4. int potPin = 4;         // select the input pin for the potentiometer
  5. int buttonPin = 8;      // select the input pin for the button
  6. int buttonState = 0;    // current state of the button
  7. int buttonCounter = 0;  // counter to prevent switching while button is pressed
  8. int val = 0;            // variable to store the value coming from the sensor
  9. int mode = r;           // mode for setting which colour to change, defaults to red
  10.  
  11. void setup()
  12. {
  13.   pinMode(r, OUTPUT);    
  14.   pinMode(g, OUTPUT);
  15.   pinMode(b, OUTPUT);
  16.   pinMode(buttonPin, INPUT);
  17. }
  18.  
  19. void loop()
  20. {
  21.   buttonState = digitalRead(buttonPin);
  22.   if (buttonState == HIGH && buttonCounter == 0)
  23.   {
  24.     buttonCounter++;
  25.     if (mode == r)
  26.     {
  27.         mode = g;
  28.     }
  29.     else if (mode == g)
  30.     {
  31.         mode = b;
  32.     }
  33.     else //(mode == r)
  34.     {
  35.         mode = r;
  36.     }
  37.   }
  38.   if (buttonState == LOW)
  39.   {
  40.     buttonCounter = 0;
  41.   }
  42.   val = analogRead(potPin);         // read the value of the potentiometer
  43.   val = map(val, 0, 1023, 0, 255);  // convert analog input to 8 bits (0 to 255)
  44.   setIntensity(mode, val);          // and throw that value to setIntensity() to set the LEDs brightness
  45. }
  46.  
  47. void setIntensity(int colour, int colourValue)
  48. {
  49.   analogWrite(colour, colourValue);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement