Another millis() question

Can somebody please point out what I am missing to make this sequence work? The aim is to

  1. push a button. redStart remembers what the time is.
  2. this button push also turns 7 LEDs off and 2 red LEDs on
  3. after the stated interval, the 2 red LEDs go off and the first of 7 turns on.
  4. after the second stated interval, the next of the 7 turns on,
  5. and so forth until all 7 are restored to their original ON state.

The currentMillis() is never updated, so the original 'snapshot' of the time recorded should just increase, right? I don't want this to be a loop, after the last of the group of 7 comes on, the function waits to repeat itself with the next button press.

In this part of the sketch (there is a lot more that does not cross over with this sequence), when the button is pressed, only the first thing happens (7 off, 2 on). and then it sits.

What am I missing/forgetting/not understanding? I am using the "Button" library that comes with arduino . I have tried it the traditional way as well, but this is not the issue.

I eventually want to put the interval times in an array and tidy this up, but one thing at a time. Here it is. The answer is probably staring me in the face.

/*

this is just a part of a bigger sketch, all of which works great. I have only included this portion that I cannot get to work because I am a dufus

unsigned long redStart = 0;  // Time when Red Alert started
const unsigned long eventInterval0 = 10000;
const unsigned long eventInterval1 = 11000;
const unsigned long eventInterval2 = 13000;
const unsigned long eventInterval3 = 15000;
const unsigned long eventInterval4 = 18000;
const unsigned long eventInterval5 = 20000;
const unsigned long eventInterval6 = 22000;
const unsigned long eventInterval7 = 24000;
const unsigned long eventInterval8 = 26000;*/


// I call this function in a main sketch, as I do with two other functions
// "if(button.isPressed()){ FN_redAlert}"

void FN_redAlert() {
  {
    Serial.println("The button is pressed");
    redStart == millis();
    Serial.println("RED ALERT!");
  }

  if (redStart <= eventInterval0) {
    for (int i; i < 8; i++) {  //red alert lights on, spotlights off
      digitalWrite(dryDock[i], LOW);
      digitalWrite(redPin1, HIGH);
      digitalWrite(redPin2, HIGH);
    }  // this is all that works.

    if (redStart >= eventInterval1) {   // red alert finishes, first spotlight set turns on
      Serial.println("Ice Ice Baby1");  //I got this from a tutorial on millis(). It just kinda stuck
      digitalWrite(dryDock[0], HIGH);   //first light group of the sequence
      digitalWrite(redPin1, LOW);       //red lights go off
      digitalWrite(redPin2, LOW);
    }

    if (redStart >= eventInterval2) {  //second spotlight group turns on
      Serial.println("Ice Ice Baby2");
      digitalWrite(dryDock[1], HIGH);
    }

    if (redStart >= eventInterval3) {  //third spotlight group turns on
      Serial.println("Ice Ice Baby3");
      digitalWrite(dryDock[2], HIGH);
    }

    if (redStart >= eventInterval4) {  //fourth spotlight group turns on
      Serial.println("Ice Ice Baby4");
      digitalWrite(dryDock[3], HIGH);
    }

    if (redStart >= eventInterval5) {  //fifth spotlight group turns on
      Serial.println("Ice Ice Baby5");
      digitalWrite(dryDock[4], HIGH);
    }

    if (redStart >= eventInterval6) {  //six spotlight group turns on
      Serial.println("Ice Ice Baby6");
      digitalWrite(dryDock[5], HIGH);
    }

    if (redStart >= eventInterval7) {  //seventh and last spotlight group turns on
      Serial.println("Ice Ice Baby7");
      digitalWrite(dryDock[6], HIGH);
      Serial.println("end");
    }
  }
}  // end of function- waits for another button press.

Thanks.

"repeat" implies a loop() ... what you mean is the loop() is held-up (latched) until button-event, loop() progresses, and the loop ends and repeats but there is that button-event that must be satisfied before continuing. Think of it as a loop but with the first event an event-lock. Everything else is a state-machine.

That is correct. Thanks.

Jim Smagata
647-890-4397
Freelance Tech Theatre Services

Hello smacks999

Try and check these untested mods.

/*

this is just a part of a bigger sketch, all of which works great. I have only included this portion that I cannot get to work because I am a dufus

unsigned long redStart = 0;  // Time when Red Alert started
const unsigned long eventInterval0 = 10000;
const unsigned long eventInterval1 = 11000;
const unsigned long eventInterval2 = 13000;
const unsigned long eventInterval3 = 15000;
const unsigned long eventInterval4 = 18000;
const unsigned long eventInterval5 = 20000;
const unsigned long eventInterval6 = 22000;
const unsigned long eventInterval7 = 24000;
const unsigned long eventInterval8 = 26000;*/


// I call this function in a main sketch, as I do with two other functions
// "if(button.isPressed()){ FN_redAlert}"

void FN_redAlert(unsigned long millisAtButtonPressed) 
{
    Serial.println("The button is pressed");
//    redStart == millis();
    Serial.println("RED ALERT!");

  static unsigned signed long redStart=0;

  if (millisAtButtonPressed-redStart <= eventInterval0) {
    for (int i; i < 8; i++) {  //red alert lights on, spotlights off
      digitalWrite(dryDock[i], LOW);
      digitalWrite(redPin1, HIGH);
      digitalWrite(redPin2, HIGH);
    }  // this is all that works.

    if (millisAtButtonPressed-redStart >= eventInterval1) {   // red alert finishes, first spotlight set turns on
      Serial.println("Ice Ice Baby1");  //I got this from a tutorial on millis(). It just kinda stuck
      digitalWrite(dryDock[0], HIGH);   //first light group of the sequence
      digitalWrite(redPin1, LOW);       //red lights go off
      digitalWrite(redPin2, LOW);
    }

    if (millisAtButtonPressed-redStart >= eventInterval2) {  //second spotlight group turns on
      Serial.println("Ice Ice Baby2");
      digitalWrite(dryDock[1], HIGH);
    }

    if (millisAtButtonPressed-redStart >= eventInterval3) {  //third spotlight group turns on
      Serial.println("Ice Ice Baby3");
      digitalWrite(dryDock[2], HIGH);
    }

    if (millisAtButtonPressed-redStart >= eventInterval4) {  //fourth spotlight group turns on
      Serial.println("Ice Ice Baby4");
      digitalWrite(dryDock[3], HIGH);
    }

    if (millisAtButtonPressed-redStart >= eventInterval5) {  //fifth spotlight group turns on
      Serial.println("Ice Ice Baby5");
      digitalWrite(dryDock[4], HIGH);
    }

    if (millisAtButtonPressed-redStart >= eventInterval6) {  //six spotlight group turns on
      Serial.println("Ice Ice Baby6");
      digitalWrite(dryDock[5], HIGH);
    }

    if (millisAtButtonPressed-redStart >= eventInterval7) {  //seventh and last spotlight group turns on
      Serial.println("Ice Ice Baby7");
      digitalWrite(dryDock[6], HIGH);
      Serial.println("end");
    }
  }
  redStart=millis();
}  // end of function- waits for another button press.

Have a nice day and enjoy coding in C++.

Great, thanks. The compiler says it has a problem with:

static unsigned signed long redStart=0;
7:31: error: 'signed' and 'unsigned' specified together for 'redStart'

can you put both in the same line? would it be "signed" because it is time, which can't be negative?

Try this mods

/*

this is just a part of a bigger sketch, all of which works great. I have only included this portion that I cannot get to work because I am a dufus

unsigned long redStartLocal = 0;  // Time when Red Alert started
const unsigned long eventInterval0 = 10000;
const unsigned long eventInterval1 = 11000;
const unsigned long eventInterval2 = 13000;
const unsigned long eventInterval3 = 15000;
const unsigned long eventInterval4 = 18000;
const unsigned long eventInterval5 = 20000;
const unsigned long eventInterval6 = 22000;
const unsigned long eventInterval7 = 24000;
const unsigned long eventInterval8 = 26000;*/


// I call this function in a main sketch, as I do with two other functions
// "if(button.isPressed()){ FN_redAlert}"

void FN_redAlert(unsigned long millisAtButtonPressed) 
{
    Serial.println("The button is pressed");
//    redStartLocal == millis();
    Serial.println("RED ALERT!");

  static unsigned signed long redStartLocal=0;

  if (millisAtButtonPressed-redStartLocal <= eventInterval0) {
    for (int i; i < 8; i++) {  //red alert lights on, spotlights off
      digitalWrite(dryDock[i], LOW);
      digitalWrite(redPin1, HIGH);
      digitalWrite(redPin2, HIGH);
    }  // this is all that works.

    if (millisAtButtonPressed-redStartLocal >= eventInterval1) {   // red alert finishes, first spotlight set turns on
      Serial.println("Ice Ice Baby1");  //I got this from a tutorial on millis(). It just kinda stuck
      digitalWrite(dryDock[0], HIGH);   //first light group of the sequence
      digitalWrite(redPin1, LOW);       //red lights go off
      digitalWrite(redPin2, LOW);
    }

    if (millisAtButtonPressed-redStartLocal >= eventInterval2) {  //second spotlight group turns on
      Serial.println("Ice Ice Baby2");
      digitalWrite(dryDock[1], HIGH);
    }

    if (millisAtButtonPressed-redStartLocal >= eventInterval3) {  //third spotlight group turns on
      Serial.println("Ice Ice Baby3");
      digitalWrite(dryDock[2], HIGH);
    }

    if (millisAtButtonPressed-redStartLocal >= eventInterval4) {  //fourth spotlight group turns on
      Serial.println("Ice Ice Baby4");
      digitalWrite(dryDock[3], HIGH);
    }

    if (millisAtButtonPressed-redStartLocal >= eventInterval5) {  //fifth spotlight group turns on
      Serial.println("Ice Ice Baby5");
      digitalWrite(dryDock[4], HIGH);
    }

    if (millisAtButtonPressed-redStartLocal >= eventInterval6) {  //six spotlight group turns on
      Serial.println("Ice Ice Baby6");
      digitalWrite(dryDock[5], HIGH);
    }

    if (millisAtButtonPressed-redStartLocal >= eventInterval7) {  //seventh and last spotlight group turns on
      Serial.println("Ice Ice Baby7");
      digitalWrite(dryDock[6], HIGH);
      Serial.println("end");
    }
  }
  redStartLocal=millis();
}  // end of function- waits for another button press.

it is very likely that your complete code executes this line of code

if(button.isPressed()){ FN_redAlert}

only one single time
and that you expect it to work as described here

If this really is your expectation - this is expectation is WRONG
non-blocking timing requires - the following number is NO exxageration -
.
non-blocking timing requires to repeat hundred-thousands times

  • as digits 100000 of times
    repeated
    compairing of
(millisAtButtonPressed - redStart >= intervall

as long as you do not repeat executing

FN_redAlert();

It will not work.
.
Assumed (caused through the lack of more real information)
This sentence from you

this is just a part of a bigger sketch, all of which works great. I have only included this portion that I cannot get to work because I am a dufus

Makes me assume (assumption caused through the lack of more real information)

There is a pretty high chance that your code has to be restructered.
But without seeing the rest of your code it is unpossible to say.

To finally decide what exactly has to be changed additionally varying from

  • nothing else to change
    up to
  • change quite a lot

can only be said if you post your complete sketch or a pretty detailed functional description of what your code does all in all and where there are any kind of loops and where there are no kinds of loops.

The easiest way is to post your complete sketch.

non-blocking timing based on millis() requires a most outer-side loop
Even in your case as you don't want to repeat the sequence 1..5 described above but wait for a button-press to execute your sequence 1..5 once again.

The best way to achieve a functionality like described in your sequence 1..5 is to use a state-machine.

To give you an easy to understand picture

an attachable excavator with shovel is a pretty common thing.

A car is a very common thing.

doubesided adhesive tape is a common thing

but it just does not work trying to mount the excavator with shovel onto this car by using doublesided adhesive tape.

The car needs a good amount of "re-structuring" for mounting this excavator

Same thing with your code.

Your code might be already like this

and then it will be much easier to mount the excavator
but as you haven't shown the rest of your code we can not say how much work it needs

best regards Stefan

This is once again a typical post that does not help the questioner solve the problem and may even discourage him from asking again. What is this nonsense?

interesting feedback.

Well without changing the basic code-structure to do the repeated compairing your code-suggestion compiles but will create this behaviour as the TO already stated

My intention is to make clear that non-blocking timing often requires a re-structuring of the code
In my experience newcomers do not believe that.

We haven't seen the complete code if this code does use loop() as the only loop to loop or not.
It is very likely that his code does not use void loop() for looping.
and then your code-suggestion is formal correct in its own but does not work.

Some additional comments

if "snapshot of time" means the value stored inside variable currentMillis ()
curentMillis without the parenthesis
if the value of currentMillis is never updated this value will never increase

What is increasing all the time is the value of function millis()

best regards Stefan

Before this gets too involved, let me clarify. The rest of the sketch is irrelevant right now. My question is not so much anything other than the millis issue. I thought I understood, after doing a lot of reading and tutorials, but clearly I don't. This doesn't even work if it was its own sketch. Pretty well all of the examples want me to blink an LED, which involves reassigning currentMillis.

What I gathered is that when you equate a word or term with millis() , like (currentMillis == millis() ) (let's call it A), that then becomes the starting point value for the upcoming code,.
if currentMillis >= interval 1, 'do this'.

2secs 4secs 6secs
0-----A-------A+interval1------A+interval2------A+interval3--- and so on.

"0" power up of arduino.
"A" currentMillis == millis() called (button press, red on 7LEDs off).
"A+interval1" is the first timed event, (red off and #1LED on)
"A+interval2" is the next timed event, (#2 on)
"A+interval3" is the next timed event, (#3 on)
--and so on to #7

Starting point stays the same (A), but then next reference, like interval 2, is referenced against A again, but this time the A value is bigger.

All I'm asking is this, really: what am I doing wrong in this sketch- why isn't it working- not keeping track and doing stuff at a specified interval?

What am I not understanding and missing about this? I am just adding time to the button press millis to do stuff. Aren't I?

Jim Smagata
647-890-4397
Freelance Tech Theatre Services

| StefanL38
March 12 |

  • | - |

paulpaulson:

This is once again a typical post that does not help the questioner solve the problem and may even discourage him from asking again. What is this nonsense?

interesting feedback.

Well without changing the basic code-structure to do the repeated compairing your code-suggestion compiles but will create this behaviour as the TO already stated

smacks999:

when the button is pressed, only the first thing happens (7 off, 2 on). and then it sits.

My intention is to make clear that non-blocking timing often requires a re-structuring of the code
In my experience newcomers do not believe that.

We haven't seen the complete code if this code does use loop() as the only loop to loop or not.
It is very likely that his code does not use void loop() for looping.
and then your code-suggestion is formal correct in its own but does not work.

Some additional comments

smacks999:

The currentMillis() is never updated, so the original 'snapshot' of the time recorded should just increase, right?

if "snapshot of time" means the value stored inside variable currentMillis ()
curentMillis without the parenthesis
if the value of currentMillis is never updated this value will never increase

What is increasing all the time is the value of function millis()

best regards Stefan

post this sketch
I mean post this reduced sketch that you called

and I will explain it

What I write here might sound arrogant to you. But IMHO it isn't arrogant it is based on experience:

You have written that you do not yet fully understand how timing based on millis() works
Yes this is true. I can conclude this from your description.
You should really believe me that I do have understood two things

  1. non-blocking timing based on millis()
  2. having understood what the most common difficulty for newcomers is about understanding how non-blocking timing works

And to get you over this hurdle of really understanding how non-blocking timing works,
becomes easier if I explain the fundamental difference based on your code .

The reduced code that you mentioned here

best regards Stefan

No. You have to do something additional:

coding in a way that your function FN_redAlert(); is called repeatedly over and over again.

If this sentence does not yet make sense to you.
This is the point you are missing and this is the point you are not yet understanding.

If this sentence does not yet make sense to you.
post your reduced but compiling sketch

best regards Stefan

@paulpaulson

can you please post a compiling and tested sketch with your modifications.

I claim that there is minimum one bug inside your code

Respectfully, it is actually a standard request to post the entire sketch, not a snippet. It's a standard and justified request, and echoes the forum posting guidelines document. The only problem I see with it, is that it is very long winded. Perhaps it was felt that the request had to be explained. Sometimes that takes multiple posts. If only members would follow the guidelines... then such suggestions and explanations wouldn't be necessary.

Anyone who has followed similar threads will have noticed, that in most cases where a snippet was posted, the problem was elsewhere.

I understand that the whole sketch should be posted, and I can do that. The sketch has four tabs in total. The main section, that the sketch is named after, is based on the code by Ostrich Longneck in his electronics for Starships series on YouTube. I felt it was just the millis I was misunderstanding

In order to post the whole thing, how should I translate it? They share the same pre-"void setup" parameters and void setup section from the main sketch. Do I copy the other tab functions and place them after the main section? Four separate posts? ( the tabs consist of a torpedo sketch, a phaser sketch and the red alert sketch, but only the void function ( like void FN_phasers() ). It is, as stated, probably pretty long-winded and sloppy. However, because you folk are being kind in spending your valuable time, which I appreciate immensely, on my silly problem, I will combine them all with the sections separated by ///////. If desired, I can also provide a short video of the prototype in action.

Jim Smagata
647-890-4397
Freelance Tech Theatre Services

I don't agree. I think you could write a small sketch that fully illustrates your predicament.

It seems like you have tried deploying the idiomatic millis() / if / currentMillis pattern, and have missed a detail or two.

There's a reason all those tutoriaks want you to blink an LED… they want to show the essence of the idea free from as much other clutter and detail as possible.

In other words, not in the context of four tabs and several hundred lines of code.

Post a small sketch where you, for examlpe, use the "blink without delay" idea and get two LEDs blinking, at unrelated rates, and so they don't conflict one with the other.

Or where you try to do and fail.

a7

Okay, so here is the red alert code all by itself. The button turns the reds on, but nithing else happens after that.


#include <Button.h>
Button button1(21);  // Connect your button between pin 2 and GND


//DRYDOCK STUFF
// Set up Arrays & Variables used for the Floodlights in the Drydock Startup Sequence
const int dryDock[] = { 40, 22, 24, 26, 28, 30, 32, 34 };  // Output pin numbers used in drydock startup sequence; 40 is RCS

//RED ALERT STUFF
int redPin1 = 4;
int redPin2 = 3;
int redSwitch = 21;
unsigned long redStart = 0;  // Time when Red Alert started
const unsigned long eventInterval0 = 8000;
const unsigned long eventInterval1 = 11000;
const unsigned long eventInterval2 = 13000;
const unsigned long eventInterval3 = 15000;
const unsigned long eventInterval4 = 18000;
const unsigned long eventInterval5 = 20000;
const unsigned long eventInterval6 = 22000;
const unsigned long eventInterval7 = 24000;
const unsigned long eventInterval8 = 26000;

void setup() {
  Serial.begin(9600);
  button1.begin();
  pinMode(redPin1, OUTPUT);
  pinMode(redPin2, OUTPUT);
  pinMode(redSwitch, INPUT);
}


  void loop()  // The main program
  {
    if (button1.pressed()) {
      FN_redAlert();
      Serial.println("Button 1 pressed");
    }
  }


  void FN_redAlert() {

    redStart == millis();
    Serial.println("RED ALERT!");


    if (redStart <= eventInterval0) {
      for (int i; i < 8; i++) {          //red alert lights on, spotlights off
        digitalWrite(dryDock[i], LOW);
        digitalWrite(redPin1, HIGH);
        digitalWrite(redPin2, HIGH);
      }                                   // this is all that works.

      if (redStart >= eventInterval1) {   // red alert finishes, first spotlight set turns on
        Serial.println("Ice Ice Baby1");  //I got this from a tutorial on millis(). It just kinda stuck
        digitalWrite(dryDock[0], HIGH);   //first light group of the sequence
        digitalWrite(redPin1, LOW);       //red lights go off
        digitalWrite(redPin2, LOW);
      }

      if (redStart >= eventInterval2) {  //second spotlight group turns on
        Serial.println("Ice Ice Baby2");
        digitalWrite(dryDock[1], HIGH);
      }

      if (redStart >= eventInterval3) {  //third spotlight group turns on
        Serial.println("Ice Ice Baby3");
        digitalWrite(dryDock[2], HIGH);
      }

      if (redStart >= eventInterval4) {  //fourth spotlight group turns on
        Serial.println("Ice Ice Baby4");
        digitalWrite(dryDock[3], HIGH);
      }

      if (redStart >= eventInterval5) {  //fifth spotlight group turns on
        Serial.println("Ice Ice Baby5");
        digitalWrite(dryDock[4], HIGH);
      }

      if (redStart >= eventInterval6) {  //six spotlight group turns on
        Serial.println("Ice Ice Baby6");
        digitalWrite(dryDock[5], HIGH);
      }

      if (redStart >= eventInterval7) {  //seventh and last spotlight group turns on
        Serial.println("Ice Ice Baby7");
        digitalWrite(dryDock[6], HIGH);
        Serial.println("end");
      }
    }
  }  // end of function- waits for another button press.

Does this line look like the comparison of the current time, with a past time stamp? I think not, you never computed the difference. That would be like:

    if (redStart - eventInterval0 >= someInterval) {

You just aren't following the standard millis() design pattern. That is why people keep pointing you to the basic example - it's all in there.

By the way, this

if (redStart <= eventInterval0) {
      for (int i; i < 8; i++) {          //red alert lights on, spotlights off
        digitalWrite(dryDock[i], LOW);
        digitalWrite(redPin1, HIGH);
        digitalWrite(redPin2, HIGH);
      }    

should really just be

if (redStart <= eventInterval0) {
      digitalWrite(redPin1, HIGH);
      digitalWrite(redPin2, HIGH);
      for (int i; i < 8; i++) {          //red alert lights on, spotlights off
        digitalWrite(dryDock[i], LOW);
      }    

Also when using the 'if' test, the loop has to be running continuously so that millis() value can be periodically tested. By capturing it once at the beginning of your function, you are preventing any future test of the time stamp that you have created.

I strongly suggest that you just back away from this program, and spend some time mastering the technique - then it will be crystal clear obvious to you what to do, when you approach it again.

Unfortunately, there is no practical way to "just repair" your 'FN_redAlert()' function because the full context is missing. But in general, if a function uses millis() timing, it should examine time stamps not intervals, and it should return without taking any actions if it does not detect any time stamp expiry.

I felt it was just the millis I was misunderstanding

I can confirm that, at least, you don't understand millis(). The key fundamental is the concept of millis() as a free running timer, that you can capture in time stamps that you later compare with the current timer value. There isn't more substance to it than that, only some caveats, like using the right data types.

This is exactly the bug I was expecting.

you are calling function FN_redAlert(); one single time
when the button gets pressed.
and then never again

So all the if-conditions inside function FN_redAlert(); were never checked again

for non-blocking timing repeated execution of all the if-conditions like

if (millisAtButtonPressed - redStart >= eventInterval1)

is a must !

How should your code ever detect "oh now it is time to switch on green LED1"
If the checking if the right amount of time has passed by is not done???

imagine you are saying to the pizza-delivery-man at 10 o' clock : deliver pizza in two hours
and the pizza-delivery-man writes down a note deliver in 2 hours and then
just doesn't care anymore about your order throws the paper with the note away
closing his baking-shop going on vacation with never ever compairing is it 12 o' clock
and it would be time to deliver your pizza?

Thank you. I am learning, and I see that now.
Thanks to you all.