Button-Activated LED Fade

This code allows you to increase the brightness of an LED by holding down a button. Release the button to allow the light to dim to nothing.

Code

/* * Use a button to increase the brightness of an LED using analogWrite(). * When the button is released, the brightness descends. * Use the constrain function to keep the brightness between 0 and 255 * Remember analogWrite() only works on pins 3,5,6,9,10,11 */ int brightness; //brightness of the LED void setup() { pinMode(5, OUTPUT); //LED pinMode(12, INPUT_PULLUP); //button } void loop() { brightness = constrain(brightness, 0, 255); //constrain brightness between 0 and 255 analogWrite(5, brightness); //write 'brightness' to the LED delay(5); //pause at each brightness level if (digitalRead(12) == LOW) { //if the button is pressed brightness = brightness + 1; //increase the value of 'brightness' by 1 } else { //otherwise (if button not pressed) brightness = brightness - 1;//decrease brightness by one } } // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Challenges

How many can you complete? Change the code and hardware according to the challenges below. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!

Videos

Read the Code Walkthrough Text (click to open)

Concepts

New Concept: Digital Versus Analog

Some things in the world are very much 'on' or 'off', like a light switch or a car engine. In code, you can think of those types of things as 'digital'. Other things, like a dimmer switch or car's tire speed, are measured on a spectrum. They still have an 'off' position and a 'maximum' position, but there are many small steps between those extremes. These things are 'analog' in code. 

With Maker Board, analogWrite() has a range of outputs from 0 to 255. The analogRead() function has a scale of 0-1023 where it can take readings.

Quiz

If you're having trouble, try to run a program that can help you find the answer.

1. What is the range of the analogWrite() function?




2. What are the arguments needed by the constrain function?



Previous Lesson
Next Lesson