Controlling Brightness of LED through Code(PWM control)
Firstly, make the connections as shown below
Connect the positive leg of LED which is the longer leg to the digital pin 6 of Arduino. Then connect the 220 ohm resistor to the negative leg of LED and connect the other end of resistor to the ground pin of Arduino.
Arduino Code(Program control)
Code for LED to fade. Copy the code to the IDE and burn it to the arduino board.The for loop iteration brings about a change in the intensity of light emitted in an ascending order. If you wish to se the change of light intensity in a lower way you may bring about changes in the delay provided as the last statement of the for loop.
//Initializing LED Pin
int led_pin = 6;
void setup() {
//Declaring LED pin as output
pinMode(led_pin, OUTPUT);
}
void loop() {
//Fading the LED
for(int i=0; i<255; i++){
analogWrite(led_pin, i);
delay(5);
}
for(int i=255; i>0; i–){
analogWrite(led_pin, i);
delay(5);
}
}
Arduino Code to manually control the Brightness of LED(manual control)
In the previous connections, add the 10k ohm potentiometer and connect the two ends of potentiometer to 5V and GND of Arduino and then connect the center of potentiometer to the A0 pin of Arduino.
Arduino Code
Upload the code in the Arduino IDE and on moving the knob of the potentiometer, the brightness of the LED will change.
Here the major change is instead of the for loop which generated values as input “analogWrite”. The value given to analogWrite is read using the “analogRead()” function and the parameter passed inside this function is “pot_pin” which is the potentiometer pin that detects the change in the knob of the potentiometer.
int led_pin = 6;
int pot_pin = A0;
int output;
int led_value;
void setup() {
pinMode(led_pin, OUTPUT);
}
void loop() {
//Reading from potentiometer
output = analogRead(pot_pin);
//Mapping the Values between 0 to 255 because we can give output
//from 0 -255 using the analogwrite funtion
led_value = map(output, 0, 1023, 0, 255);// output is in the range 0-1023 and is converted into the range 0-255 and copied/mapped to led_vlaue
analogWrite(led_pin, led_value);
delay(1);
}
Burn the above given code to the Arduino board and control the LED by turning the potentiometer. When the potentiometer knob is turned a respective change is seen at the intensity of the LED also.