Monica Houston
Published

LED Brightness Controlled With Two Buttons

Instead of the usual potentiometer setup, I wrote a sketch that controls LED brightness using two buttons.

Full instructions provided19,813
LED Brightness Controlled With Two Buttons

Story

Read more

Code

light_code.ino

C/C++
Arduino Code
const int brightnessUp = 10;     // the number of the pushbutton pin
const int brightnessDown = 9;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
const int maxBrightness = 12; //this can be any number - it's the number of steps between dimmest and brightest. 

// variables will change:
int brightness = maxBrightness;
int interval=1;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);      
  // initialize the pushbutton pins as an input:
  pinMode(brightnessUp, INPUT);     
  pinMode(brightnessDown, INPUT);   
  Serial.begin(9600);
}

void loop(){
    if (digitalRead(brightnessUp) == HIGH && brightness < maxBrightness){ 
      brightness = brightness + interval; 
      //if the brightness Up button is pushed, add one degree of brightness to the current level
      Serial.println(brightness); //for debugging purposes
    }
    if (digitalRead(brightnessDown) == HIGH && brightness > 0){
      brightness = brightness - interval;
      //if the brightness Down button is pushed, subtract one degree of brightness from the current level
      Serial.println(brightness); //for debugging purposes
    }
    delay(100);
    analogWrite(ledPin, map(brightness, 0, maxBrightness, 0, 255));    
    //this code maps the max brightness constant to the max LED brightness
  
}

Credits

Monica Houston

Monica Houston

75 projects • 446 followers
I don't live on a boat anymore.

Comments