C6 — Analogue outputs

Level 2 — The Dimmer Switch
Complete the challenge
int ledPin = 10; // define the pin for the LED
int upButtonPin = 6; // define the pin for the "up" button
int downButtonPin = 7; // define the pin for the "down" button
int upButtonState = 0; // create a variable for what the up button is doing
int downButtonState = 0; // create a variable for what the down button is doing
int brightness = 0; // create a variable for the brightness of the LED
void setup() {
pinMode(ledPin, OUTPUT); // set up the ledPin as an OUTPUT
pinMode(upButtonPin, INPUT_PULLUP); // set up the buttonPin as an INPUT_PULLUP
pinMode(downButtonPin, INPUT_PULLUP); // set up the buttonPin as an INPUT_PULLUP
}
void loop() {
upButtonState = digitalRead(upButtonPin); // read the state of the up pushbutton
downButtonState = digitalRead(downButtonPin); // read the state of the down pushbutton
if (upButtonState == LOW) { // check if the up pushbutton is pressed.
brightness = brightness + /* ADD CODE HERE */; // increase the brightness by 1
}
if (downButtonState == LOW) { // check if the down pushbutton is pressed.
brightness = brightness - /* ADD CODE HERE */; // decrease the brightness by 1
}
if (brightness > 255) { // Don't let brightness get bigger than 255
brightness = 255;
}
if (brightness < 0) { // Don't let brightness get smaller than 0
brightness = 0;
}
/* ADD CODE HERE */ // set the brightness of the LED
delay(10); // wait a little while before checking again
}
To set the brightness of the LED, use the analogWrite() function.
Put in analogWrite(ledPin, brightness);