Skip to main content
1 of 6
Michel Keijzers
  • 13k
  • 7
  • 43
  • 59

To be honest, I don't understand exactly the problems, but I try to give some guideline and hope you can use the idea to fix your problems.

What you need is a so called 'state machine'.

I think (according to your problem) that you have 6 states:

0 Idle (no sequence)
1 One LED on
2 Two LEDs on
3 Three LEDs on
4 Four LEDs on
5 No LEDs on 

For this you can best use an enum type and global variable with similar values:

enum EState
{
    Idle,
    OneLedOn,
    TwoLedsOn,
    ThreeLedsOn,
    FourLedsOn,
    NoLedsOn
}

EState _state;

You need a function to check the new state, depending on the current state. In words something like:

current     When                          Action         New 
state                                                      state
--------    ----------------------------  ---------------- -----
Idle        digitalRead(RTS_IN) == HIGH   Start counter    OneLedOn
OneLedOn    digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            1 second has passed           Start counter    TwoLedsOn
TwoLedsOn   digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            1 second has passed           Start counter    ThreeLedsOn
ThreeLedsOn digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            1 second has passed           Start counter    ThreeLedsOn
FourLedsOn  digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            1 second has passed           Start counter    NoLedsOn
NoLedsOn    digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            1 second has passed           Start counter    OneLedn

I don't have a compiler so I do it out of my head.

void Process()
{
    switch (_state)
    {
    case Idle:
        if ((digitalRead(RTS_IN) == HIGH)
        {
            _time = millis();
            _state = OneLedOn;
        }
        break;
    case OneLedOn:
        if ((digitalRead(RTS_IN) == LOW)
        {
            SwitchLedsOff();
            _state = Idle;
        }
        else if (millis() > time + 1000)
        {
            _time = 0;
            _state = OneLedOn;
        }
        break;
    case TwoLedsOn:
       ...
}

The function SwitchLEDsoff sets all LEDs to low, and you only need one unsigned long _time global variable which you update when a new state starts and check in most states.

Note that high likely you can optimize this, but the main goal is to let you understand how to use a state machine and to use it in this sketch and future sketches.

Michel Keijzers
  • 13k
  • 7
  • 43
  • 59