OK, that’s something to start with.
First, it’s important to know that applying a pull-up resistor on the Particle devices is not done that way
digitalWrite(led1, HIGH); // turn on pull up resistor
And for the logic of the code I’m not pretending to provide the only correct way but just some hints I found useful for my own way of coding.
One thing I try to avoid is the “hassle” of multi variant conditions like your
if (ledRunning == false && ledLastState==HIGH) and it’s counterpart(s).
In case of state changes I like to first check whether the state has actually changed and only proceed with the extra work if it has.
e.g. like this
static int prevState = -1; // start of with a "tri-state" condition - static var will keep value across calls
int currState = digitalRead(led1);
// do whatever needs to be done independent of state change
if (currState == prevState) return;
prevState = currState;
delay(50); // lazy debounce
// do what needs to happen on state change
This way you can concentrate on the actual meaning of the state rather than having to consider the change vs. no-change in all possible combinations of variants.
Also if you use a
Particle.variable() you could keep updating the accumulated on-time in the “change independent part” and wouldn’t need to wait for
led1 to go out.
Another hint would be this
You are (in essence - forget about the details for the moment) writing this
if (ledLastState == HIGH)
ledRunning = true;
ledRunning = false;
In combination with the explicit state-change-check, this could be reduced to
ledRunning = ledLastState; // LOW is equivalent to false, and everything NOT false is considered true
Like in maths, try to “factor out” the things that are common to all cases and write them only once. This makes the code easier to read and also stresses the actual dependencies more direct than by having them nested in some conditional branches.
Here in particular this approach reveals the fact that
ledRunning is actually superfluous as it’s always the same as
prevState in my code) and hence can be dropped.