C6 — Analogue outputs

Level 1 — Change the brightness of an LED

Complete the challenge

int ledPin = 10;                 // define the pin the LED is on
int buttonPin = 6;              // define the pin for the button
int buttonState = 0;            // create a variable for what the button is doing

void setup() {
    pinMode(ledPin, OUTPUT);           // set up the ledPin as an OUTPUT
    pinMode(buttonPin, INPUT_PULLUP);  // set up the buttonPin as an INPUT_PULLUP
}

void loop() {
    buttonState = digitalRead(buttonPin);  // read the state of the pushbutton value
    if (buttonState == HIGH) {            // check if the pushbutton is pressed.
        analogWrite(ledPin, 60);           // turn the LED partly on if the buttonState is HIGH
    } else {
        analogWrite(ledPin, 255);          // turn LED full on if the buttonState is LOW
    }
}

Claim your achievement