Image

Creative laboratory → Alternating LED switching off

#Arduino #Scetches
Date of publication: 04.09.2024

Alternating LED switching off


Since the LED is quite bright, the camera doesn't capture this effect well. In reality, everything looks good.

Arduino sketch:

const byte  PinLeds [] = { A0, A1, A2, A3, A4, A5 };

int         Nleds = sizeof(PinLeds);
int         idxLed;

const char *CharList [] = { "|", "/", "-", "\\"};
int         Nchar       = sizeof(CharList)/sizeof(char*);
int         idxChar;

void fLeds ()
{
    for (int n = 0; n < Nleds; n++)
        digitalWrite (PinLeds [n], HIGH);

    digitalWrite (PinLeds [idxLed], LOW);

    if (Nleds <= ++idxLed)
        idxLed = 0;
}

void fChars ()
{
    Serial.print   (CharList [idxChar]);
    Serial.print   ('\r');

    if (Nchar <= ++idxChar)
        idxChar = 0;
}

struct Job {
    const unsigned long MsecPeriod;
    void (*func) (void);
    const char         *desc;

    unsigned long msec;
};

Job jobs [] = {
    {  500, fLeds,  "leds"  },
    {  200, fChars, "chars" },
};

const int Njobs = sizeof(jobs)/sizeof(Job);

void loop ()
{
    unsigned long msec = millis ();

    for (int j = 0; j < Njobs; j++)  {
        if (msec - jobs [j].msec >= jobs [j].MsecPeriod)  {
            jobs [j].msec += jobs [j].MsecPeriod;

            jobs [j].func ();
        }
    }
}

void setup()
{
    Serial.begin(9600);

    for (int n = 0; n < Nleds; n++)
        pinMode (PinLeds [n], OUTPUT);
}

This code turns on all the LEDs and turns off each one in turn at a configurable speed, and also the Serial monitor displays characters that can be displayed on the display.

The example clearly displays the state of the device, and the switching of the LEDs symbolizes that it is not frozen.





No Comments Yet