How to control brightness of a LED using a microcontroller

Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

How to control brightness of a LED using a microcontroller

Post by Shane » Fri Jun 24, 2011 6:56 am

1.jpg
1.jpg (218.96 KiB) Viewed 3296 times

Code: Select all

// Six of the Arduino Digital Pins can be used as PWM (pulse width modulation)
 // outputs (D3, D5, D6, D9, D10 and D11). PWM works by varying the ON duty cycle
 // of a square wave output. This control feature is very useful for the control
 // of many devices, such as with the L293D H-Bridge as a variable motor speed
 // control. In this example, we will use the PWM output directly with an LED to
 // control its brightness. The PWM feature is accessed with the
 // analogWrite () function - where a value of 1023 will result in a 100% duty
 // cycle, a value of 511 in a 50% duty cycle, and a value of 0 in a 0% duty cycle.
 // In this tutorial, we will use the same circuit as in the Analog Input with a
 // Potentiometer tutorial, only shifting the code to control the LED by dimming
 // rather than varying its flash rate.

int potPIN = 0; // select the input pin for the potentiometer
 int ledPIN = 9; // select the output pin for the LED
 int potVAL = 0; // variable to store the value coming from the potentiometer

void setup() {
 Serial.begin(9600); // set the baud rate for the serial window
 pinMode(ledPIN, OUTPUT); // declare the ledPin as an OUTPUT, ANALOG IN is an
 // input by default
 }

void loop() {
 potVAL = analogRead(potPIN); // read the value from the potentiometer
 potVAL = (potVAL/4+10); // scale and shift the potVAL to be a useful
 // input for setting the PWM duty cycle
 analogWrite(ledPIN, potVAL); // output a square wave with proper duty cycle
 // to brighten and dim LED based on putVal input
 Serial.println(potVAL); // print potVAL in the arduino serial window
 }
Courtecy of UMASS AMHERST
Post Reply

Return to “Arduino”