Trying to Understand Milli() Better

I am trying to replace delay() with Millis() to move Servo/Actuators Slowly from starting point to the endpoint with stops in-between.
I am Using Actuonix Mini Servo Actuators with Arduino. It works perfect with the delay but I want to use Millis() so that delay() doesn't stop me from controlling different things.

/////////////////////////////////////////////////////////////////////////////////////
if ((Push_Button3_State == LOW) && (Push_Button4_State == LOW)) // Push Button 3 and 4 both are pressed
{
ActuatorA3.writeMicroseconds(1600);
delay(8000);
ActuatorA3.writeMicroseconds(1625);
delay(8000);
ActuatorA3.writeMicroseconds(1650);
delay(8000);
ActuatorA3.writeMicroseconds(1675);
delay(8000);
ActuatorA3.writeMicroseconds(1700);
delay(8000);
ActuatorA3.writeMicroseconds(1725);
delay(8000);
ActuatorA3.writeMicroseconds(1750);
delay(8000);
ActuatorA3.writeMicroseconds(1770);
delay(8000);
}

//////////////////////////////////////////////////////////////

How can I use millis() in the above scenario to move the Actuator from one end to the other end with stops in between?

Thank you!

Using millis() is looking at the clock to see if something has to be done at that moment.
Start by reading this: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

The goal is to have the loop() run as many times per second as possible. Preferable hundreds or thousands times per second.

Staying in control and know what the sketch is doing is done with global variables.
Since every 8 seconds something happens, that is a millis-timer of 8 seconds. To run that sequence, you could make a table with the servo settings and go through that table in the millis-timer.
You need a global variable to indicate that the sequence is busy and a index in the table to know where the sequence is.

When we say to use millis() instead of delay(), then we do not mean to replace one function with another function, we mean that the whole sketch should be rewritten.

All of what @Koepel sez, natch.

A table of positions (times) would be the most fliexible, but if the 1770 was 1775, you might start with a slightly altered version of your original code, viz:

position = 1600;  // some static or global variable

if ((Push_Button3_State == LOW) && (Push_Button4_State == LOW)) // Push Button 3 and 4 both are pressed
{
  for (byte pp = 0; pp < 9; pp++) {
    ActuatorA3.writeMicroseconds(position);
    position += 25;
    delay(8000);
  }
}

and leave coding (or learning language features you haven't used yet) for an improved version. You still need to get rid of the dealy(), but now there's just one. The technique is the same, same trick or approach, whatever you call it.

a7

A couple more tutorials:
Beginner's guide to millis().
Several things at a time.

My take in this is here
http://www.thebox.myzen.co.uk/Tutorial/State_Machine.html

This question comes up at least once a day in some form or other.

And I want to add my two tutorials because I claim that they are easier to understand

explaining millis() = non-blocking timing

explaining state-machines:

best regards Stefan

No more tutorials however a simple simile.

You can consider the millis() the same as a stop watch that is started as soon as the processor is powered up (or reset).

So you want to delay something 10 seconds. You would do the following:

  1. note what the stopwatch reads at the "start" of the delay.
  2. add 10 seconds to the number recorded in step 1)
  3. watch the stopwatch until it reads the reading in step 1 + 10 seconds.

Slowing things down....

You want to run the water in you bath for 3 minutes.
you start the water, and at your stop watch, it reads 20 minutes and 15 seconds.
you mentality add 3 minutes so at 23 minutes 15 seconds you will turn off the water.

Instead of seconds, the millis() counts 1 millisecond ( 1/1000 of a second).

Understood. And you have plenty of advices for how to get further along with this, sorta been tots tossed into the deep end with this, do not fear.

If some pages long tutorials suit you, fine. otherwise ignore them. Do not be intimidated, it is not that hard to grasp.

It would be best if you decided the full function of a very small program.

Obvsly here you want an anticlockwise sweep when two buttons are down. Or clockwise - I just like any excuse to use "anticlockwise" :expressionless:

Your original code will initiate a sweep the instant it sees the two buttons down, and continue blind to input until the sweep is done.

What then? What if the buttons are still down? What will make it sweep the opposite direction?

When you use the various tricks talked about above, you will have to (be able to!) think about things differently, things like:

Sweep left while both buttons are down. STOP if either goes up during. If the either button goes down again (both?) sweep back to a resting position. Or maybe one button means continue to the other extreme, and the other means go back to home. Something could happen if one button goes up - slow down, perhaps.

As with any program, it is up to you to decide.

With all this opportunity comes the necessity of specifying what happens when and for why. Anything you do not deliberately plan for will nevertheless have some outcome in the code. The more you plan, the fewer surprises. One should never be surprised by the behaviour of the code, certainly not in a tiny program.

So write up a little description of how two buttons might want to control one servo. Do this with or without your ultimate objective in mind, but make it be something you can write, test and get help with here perfecting, independent of any larger context (the big project) you might want to insert it in directly.

Then you can use the techniques you get the hang of in isolation to write sections of wonderful non-blocking state machine orientated code for your big project.

Speaking of which, your big project may need re-working itself if it also has any blocking or other unfortunate expressions of your desires (code) that frustrates or invalidates the use of millis() in the way we aiming you at.

Which is why I repeat - get some small project, very small, working using these techniques before you come within a kilometer of using them in your real project.

a7

Give examples of other things that you want to do between successive positions of the Servo. For example: If you want to refresh a 7-segment display unit (Fig-1), you may execute the following codes:

  ActuatorA3.writeMicroseconds(1600);
  unsigned long prMillis = millis();
  while (millis() - prMillis < 8000)
  {
    sevSeg.refreshDisplay();
  }

cc4dRx
Figure-1:

You may but you will not get the results you expect.

Anyway that is no different from using a delay, it is still blocking code.

Is it not multi-tasking -- waiting and doing a side job? I think that the following codes are equivalent to a delay() function:

while (millis() - prMillis < 8000)
  {
     ;
  }

It has absolutely nothing to do with the question being asked here.

It is not multi-tasking. It only performs a display function alone, for a fixed period of time.

const unsigned ActuatorA3Positions[] = {1600, 1625, 1650, 1675, 1700, 1725, 1750, 1770};
const byte ActuatorA3PositionCount = sizeof ActuatorA3Positions / sizeof ActuatorA3Positions[0];
boolean ActuatorA3Running = false;
byte ActuatorA3Position = 0;
unsigned long ActuatorA3Timer;


/////////////////////////////////////////////////////////////////////////////////////
  if (!ActuatorA3Running && (Push_Button3_State == LOW) && (Push_Button4_State == LOW)) // Push Button 3 and 4 both are pressed
  {
    ActuatorA3Running = true;
    ActuatorA3Position = 0;
    ActuatorA3Timer = millis();
  }

  if (ActuatorA3Running)
  {
    ActuatorA3.writeMicroseconds(ActuatorA3Positions[ActuatorA3Position]);
    if (millis() - ActuatorA3Timer >= 8000)
    {
      ActuatorA3Timer = millis(); // Re-start the timer
      ActuatorA3Position++;  // next position
      if (ActuatorA3Position >= ActuatorA3PositionCount)
        ActuatorA3Running = false;  // All done
    }
  }
//////////////////////////////////////////////////////////////

Thank you very much you all. I have now a better understanding of how Millis() work after reading all the comments and tutorials. @johnwasser - helped me exactly what I wanted the Actuator to do.

Thank you very much all for your time and efforts.

Hi John,
Thank you very much for the solution. It works like a charm. I made changes to the program and it does what I wanted to do.
I will play with it for some time and see how I go. If I encounter any issues I will comment here and hope you will be able to help.

Again - Thank you very much!

Regards,
Apurva

Arduino timing lets you time by millis() or micros().

millis() returns ms since startup +/- 1ms due to how it counts.
micros() counts every 4 us, the low 2 bits are always 0 but the units are microseconds.
Those do not include cpu clock source error.

If close timing matters, use micros().

The time formula is, with unsigned integers; end time - start time = elapsed time.

Think of a 12 hour clock with only an hour hand. Every hour the hand moves one hour to the right. If it is 3 and my start time was 8, I subtract 8 from 3 by moving the hand 8 left from 3 to give 7 hours elapsed since 8.
Unsigned subtraction works in this circular fashion in that one-step, a single subtraction always works to a max elapsed time... 16 bits can time millis to 60.535 seconds in half the cpu cycles that 32 bit unsigned long timing takes.

Here is a general technique to un-delay code with multiple delays using 1 timer.

// NoBlockUndelayDemo2 2022 by GoForSmoke @ Arduino.cc Forum
// Free for use, May 10, 2022 by GFS. Compiled on Arduino 2.1.0.5
// This sketch shows a general method to get rid of delays in code.
// You could upgrade code with delays to work with add-a-sketch.
// .. adding looped cases

#include <avr/io.h>
#include "Arduino.h"

const byte ledPin = 13;
unsigned long delayStart, delayWait;
const byte indexMax = 12;
byte index;


void setup()
{
  Serial.begin( 115200 );
  Serial.println( F( "\n\n\n  Un-Delay Example, free by GoForSmoke\n" ));
  Serial.println( F( "This sketch shows how to get rid of delays in code.\n" ));

  pinMode( ledPin, OUTPUT );
};


/* The section of the original sketch with delays:
 * 
 * digitalWrite( ledPin, HIGH );   --  0
 * delay( 500 );
 * digitalWrite( ledPin, LOW );    --  1
 * delay( 500 );
 * for ( i = 0; i < 12; i++ )
 * (
 *   digitalWrite( ledPin, HIGH );   --  2
 *   delay( 250 );
 *   digitalWrite( ledPin, LOW );    --  3
 *   delay( 250 );
 * }
 * digitalWrite( ledPin, HIGH );   --  4
 * delay( 1000 );
 * digitalWrite( ledPin, LOW );    --  5
 * delay( 1000 );
 */

byte blinkStep; // state tracking for BlinkPattern() below

void BlinkPattern()
{
  // This one-shot timer replaces every delay() removed in one spot.  
  // start of one-shot timer
  if ( delayWait > 0 ) // one-shot timer only runs when set
  {
    if ( millis() - delayStart < delayWait )
    {
      return; // instead of blocking, the undelayed function returns
    }
    else
    {
      delayWait = 0; // time's up! turn off the timer and run the blinkStep case
    }
  }
  // end of one-shot timer

  // here each case has a timed wait but cases could change Step on pin or serial events.
  switch( blinkStep )  // runs the case numbered in blinkStep
  {
    case 0 :
    digitalWrite( ledPin, HIGH );
    Serial.println( F( "Case 0 doing something unspecified here at " ));
    Serial.println( delayStart = millis()); // able to set a var to a value I pass to function
    delayWait = 500; // for the next half second, this function will return on entry.
    blinkStep = 1;   // when the switch-case runs again it will be case 1 that runs
    break; // exit switch-case

    case 1 :
    digitalWrite( ledPin, LOW );
    Serial.println( F( "Case 1 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 500;
    blinkStep = 2;
    break;

    case 2 :
    digitalWrite( ledPin, HIGH );
    Serial.println( F( "Case 2 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 250;
    blinkStep = 3;
    break;

    case 3 :
    digitalWrite( ledPin, LOW );
    Serial.println( F( "Case 3 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 250;
    // this replaces the for-loop in non-blocking code.
    if ( index++ < indexMax ) // index gets incremented after the compare
    {
      blinkStep = 2;
    }
    else
    {
      index = 0;
      blinkStep = 4;
    }  // how to for-loop in a state machine without blocking execution.
    break;

    case 4 :
    digitalWrite( ledPin, HIGH );
    Serial.println( F( "Case 4 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 1000;
    blinkStep = 5;
    break;

    case 5 :
    digitalWrite( ledPin, LOW );
    Serial.print( F( "Case 5 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 1000;
    blinkStep = 0;
    break;
  }
}


void loop()  // runs over and over, see how often
{            
  BlinkPattern();
}

Hello John,
The Code is working good. The only Problem I am facing now - Actuator is looping. Is there way to stop at 1770?
What the code is doing right now is - Actuator is going from 1600 to 1770 with 8000 delay between the steps and once it reaches 1770 it goes back to 1600 and start the process again.

My question now - Is there a way to keep the same code and stop the Actuator at 1770 when it reaches there?

Thank you!

Is it needed to mention the data type or default int-type is ok?

When the actuator reaches at the final position, then stop it inserting the while(1); instruction.