This function should output this string for 10 seconds. But after the durration (here 5 seconds) the string is "overwriten" to "OFF".
For this i used an additional variable called counter. It helps that the previousTime only gets updatet once every loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
if (inputString == "ON")
{
if (counter == 0)
{
previousMillis = clock(); // get once everytime "inputString" is set to "ON"
counter++;
}
if (currentMillis - previousMillis > durration) // do after 5 second
{
inputString = "OFF";
previousMillis = currentMillis;
counter = 0;
}
}
Without counter, the previousTime is updatet every loop and is then equal to CurrentMillis so the if-statement is always false.
I dont know but is there a better way to solve this problem?
you can rearrange it but the mechanics are the same (you can stuff it into an object, or hide it in a finite state machine, etc, but it will do the same things).
if you want to have a second event within a time window of a first event, you have to track all the bits. you can get the now-time vs the first event time and check that BOTH events are set, but at a minimum you need to know {the starting time of the first event, that the first event happened, and that the second event happened} along with the fixed data (how long the time window is, whatever else) and it has to handle repeated first events followed by a second event (and beyond that, do you allow complexity like E1a, E1b, E2a, E2b pattern that correctly matches first and second events together somehow... If you need to match the complexity you need more info of some sort or an algorithm for it.
This has similarities with Arduino stuff. (cf Arduino 'Debounce' ).
But it's not all that clear what you are trying to do. However here is a simplified rendition of what it might be about and the possibility of extending it.
It turns ON for the duration then turns OFF, and vice versa.
It turns ON for the duration then turns OFF, and vice versa.
I want something to be turned ON, but only for a speficic durration. If its not "ON", the code just "scips" this part and goes to the next event, which might be turned "ON" for some specific time. But for that i need that Variable counter, to not go every loop though the following: previousMillis = clock();.
@jonnin
you can rearrange it but the mechanics are the same (you can stuff it into an object, or hide it in a finite state machine, etc, but it will do the same things).
Ok, so there is not a completly different approach.