Building on the previous post, where we learned how to read a potentiometer, we now use that information to control the brightness of a LED.
Using Pulse Width Modulation (PWM), we send the full 5 volts to the LED and current limiting resistor, but we change the on and off times of the 5v. The more time the signal is on, the brighter the LED.
The following sketch adds a couple of lines to the previous sketch to control the output. Connect a LED and an appropriate resistor between Pin 7 and Gnd. Flat side of the LED points to Gnd. You can determine the correct resistor at http://led.linear1.org/1led.wiz, but a 120-150 ohm is usually workable.
int ledPin = 7; // LED connected to digital pin 7 int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value
pinMode(ledPin, OUTPUT); // sets the pin as output
val = analogRead(analogPin); // read the input pin
analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
Next we will discuss powering heavier loads with a MOSFET.
Become the Maker you were born to be. Try Arduino Academy for FREE!