LEDs Fading Speed Control

Solving Approach:

How do you plan to solve it?

 

 

Code

#include <stdint.h>

/* PWM output pins */
#define PWM1 3
#define PWM2 5
#define PWM3 6
#define PWM4 9
#define PWM5 10

/* Analog input */
#define POT  A0

/* PWM limits (8-bit resolution) */
#define BRIGHTNESS_MIN 0
#define BRIGHTNESS_MAX 255

/* Fade direction state */
typedef enum {
    FADE_UP,
    FADE_DOWN
} FadeDirection_t;

void setup(void)
{
    /* Configure PWM pins as outputs */
    pinMode(PWM1, OUTPUT);
    pinMode(PWM2, OUTPUT);
    pinMode(PWM3, OUTPUT);
    pinMode(PWM4, OUTPUT);
    pinMode(PWM5, OUTPUT);

    /* Analog input does not strictly need pinMode(),
       but setting it improves readability */
    pinMode(POT, INPUT);
}

void loop(void)
{
    /* Persistent timing state
       static ensures the value survives across loop() calls */
    static uint32_t previous_time_ms = 0;

    /* Persistent fade state */
    static FadeDirection_t direction = FADE_UP;
    static uint8_t brightness = 0;   // 8-bit matches PWM hardware

    uint32_t current_time_ms = millis();

    /* Read ADC (10-bit) and downscale to 8-bit (0–255)
       Fast, deterministic, no floating point */
    uint8_t adc8 = analogRead(POT) >> 2;

    /* Map pot position to update interval (fade speed)
       Smaller value → faster fade
       Larger value → slower fade */
    uint16_t interval_ms = map(adc8, 0, 255, 10, 100);

    /* Non-blocking timing check */
    if ((current_time_ms - previous_time_ms) >= interval_ms) {
        previous_time_ms = current_time_ms;

        /* ---- State update ---- */
        if (direction == FADE_UP) {
            if (brightness < BRIGHTNESS_MAX) {
                brightness++;
            } else {
                direction = FADE_DOWN;
            }
        } else { // FADE_DOWN
            if (brightness > BRIGHTNESS_MIN) {
                brightness--;
            } else {
                direction = FADE_UP;
            }
        }

        /* ---- Output update ----
           LEDs alternate brightness for visual contrast */
        analogWrite(PWM1, brightness);
        analogWrite(PWM2, 255 - brightness);
        analogWrite(PWM3, brightness);
        analogWrite(PWM4, 255 - brightness);
        analogWrite(PWM5, brightness);
    }
}



 

Output

Video

Add video of output (know more)

 

 

 

 

Photo of Output

Add a photo of your hardware showing the output.

 

 

 

 

 

Upvote
Downvote

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!