Fading a LED In and out, with duration variables

if/else if/else... can work if you are clean about it. The if/else can easily get complicated and unreadable if folks start coding combinations of flag variables and logical tests. And a misplaced "else" or set of "{}" can also make logic errors undetectable. In more complicated systems, the switch-case can often be clearer because it enforces distilling down the set of conditions into one state variable and the organization of (mostly) mutually exclusive blocks of code.

I suggested a couple more "else if"s because it fits in with what you already have.

there are 2 types of state machines

  • where the action depends on the state
  • where the action depends on the transition

in the code i posted, there's really only one state, but 3 transitions:

  • normal inc/decrement
  • transition at max using maxDuration
  • transition at min

There's a more general state machine design where leaving a state triggers its "exit" action, transitioning to another state (or back to the same state) triggers the transition action, and entering a state triggers its "entry" action; also an event can trigger an action while remaining in a state. Any or all of those actions can be a no-op if they're not needed.

I imagine most applications need only some of those actions.

you're suggesting that the "exit" action is the same for each transition, where as each transition is unique and can effectively combine an "exit" and "enter" action if needed

Sometimes it's useful to have an "exit" action for a state that's the same regardless of which transition is taken. In that case it makes sense to separate the "exit" action from each of the transitions' actions so as not to duplicate the "exit" action in all transitions.

States needing a common exit from multiple previous states could be a good application for COMEFROM.

Did you just volunteer to port INTERCAL to Arduino? :smiley:

1 Like

Hello PixelWorks

What´s the task of the sketch in real life?

Do you want to build a flashing light for a lighthouse model?

No not a lighthouse, but close... It is for a prop spaceship. :wink:

1 Like