This is my first project using Arduino UNO. Using the code given we can change the intensity of LED automatically.
This code increments and decrements the intensity of LED in 255 steps with selective delay. This code uses analogWrite(PWM) in 8 bit mode. That means intensity can be controlled in 255 steps. I tried different code logic for this project.
10mm LED is connected to pin number 10 on Arduino UNO board.
There are 2 while loops in this version. Initially intensity is high. Hence first while loop is used to decrement intensity from 255 to 0 with delay of 5 milliseconds.
while(intensity != 0)
{
analogWrite(10, intensity);
delay(d);
intensity = intensity - 1;
}
This while loop ends when intensity becomes 0 and the second while loop starts. In this loop intensity increments from 0 to 255.
while((intensity < 255) && (intensity >= 0))
{
analogWrite(10, intensity);
delay(d);
intensity = intensity + 1;
}
int intensity = 255;
int d = 5;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 10 as an output.
pinMode(10, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
while(intensity != 0) //this loop is to decrement intensity
{
analogWrite(10, intensity);
delay(d);
intensity = intensity - 1;
}
while((intensity < 255) && (intensity >= 0)) //increment intensity
{
analogWrite(10, intensity);
delay(d);
intensity = intensity + 1;
}
}
Second version of the codeTwo variables intensity and flag are used in this version. When flag becomes 0 intensity increments. When intensity becomes high i.e 255 flag becomes 1. When flag becomes 1 intensity decrements and so on.
int intensity = 0;
int flag = 0;
int d = 5;
void setup() {
pinMode(10, OUTPUT);
}
void loop() {
analogWrite(10, intensity);
delay(d);
if(flag == 0)
intensity = intensity + 1;
if(intensity == 255)
flag = 1;
if(flag == 1)
intensity = intensity - 1;
if(intensity == 0)
flag = 0;
}
These 2 versions are a bit lengthy so I tried to make it short. The 3rd version is the outcome.
Third version of the codeI used abs() and intensity++ in this version. Intensity starts increasing from -255 to 255 then goes back to -255 and the loop continues.
int intensity = 255;
int d = 5;
void setup() {
pinMode(10, OUTPUT);
}
void loop() {
analogWrite(10,abs(intensity));
delay(d);
if(intensity++ == 256)
intensity = -255;
}
Final version of the codeThis is the shortest code so far after all the trial and errors.
int intensity = 255;
int
int d = 5;
void setup() {
pinMode(10, OUTPUT);
}
void loop() {
analogWrite(10, intensity);
delay(d);
intensity = intensity + intensitychange;
if((intensity == 0) || (intensity == 255))
{
intensitychange = -intensitychange;
}
}
Comments