Editorial Solution

As we can analyze from the above-mentioned task, we have to vary the LED's brightness at a specific time interval.

As we know we use PWM to control LED brightness. 

For PWM, we use analogWrite(value) function, where we provide “value” from 0 to 255.

Calculating Delays

Rise Delay:

Now we have to make the LED brightness 0 to 100% in 2 seconds, let’s calculate the delay for each brightness step.

Delay for each step = (2 Seconds/ 256) = 7.8125 milliseconds.

Fall Delay:

Delay for each step = (1 second/ 256) = 3.906 milliseconds.

Since it is in fraction, we can provide the delay in microseconds for better accuracy.

To provide a delay in microseconds we can use delayMicroseconds();.

Let’s do the hardware connection, 

We can use any PWM pins. 

Let’s use pin no 9 as PWM.

Let’s Connect the LED. Here we have a 3mm RED LED with a drop voltage of 2 volts. considering a 10mA current pass-through it. 

The Resistor value,

R = (Vcc - Vled) / I 

   = (5-2)/0.010 

   = 300

So we will use a standard resistor value of 300Ω.

Circuit connection

Code

void setup() {
  pinMode(9, OUTPUT);  // Set pin 9 as an output to control the LED
}

void loop() {
  /*
   Fade in: Gradually increase brightness from 0 to 255 over 2 seconds
   - There are 256 brightness levels (0 to 255)
   - Total time for fade-in: 2000 milliseconds (2 seconds)
   - Delay per step: 2000 ms / 256 = ~7.812 ms or 7812 microseconds
  */
  for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(9, brightness);  // Set the LED brightness (PWM value)
    delayMicroseconds(7812);     // Pause for 7812 microseconds per step 
  }

  /*
   Fade out: Gradually decrease brightness from 255 to 0 over 1 second
   - There are 256 brightness levels (255 to 0)
   - Total time for fade-out: 1000 milliseconds (1 second)
   - Delay per step: 1000 ms / 256 = ~3.906 ms or 3906 microseconds
  */
  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(9, brightness);  // Set the LED brightness (PWM value)
    delayMicroseconds(3906);	// Pause for 3906 microseconds per step
  }
}

 

Output

 

Output video


 

Submit Your Solution