Inconsistent Delay function in loop?

Hello Everyone!
I am trying to create an autofeeder (nema) motor that dispense every 4 hours. However, the results in very inconsistent, i.e the autofeeder will dispense 8 hours or 9 hours while sometimes it is dispensing every 4 hours.

Refer video as attached (https://youtu.be/Q8V4OghVcqQ) timelapse of dispensing for 24 hours with a timer.

The A0 pin is connected to a potentiometer, what we want to adjust the amount of feed dispenses each time with the potentiometer, while the dispensing interval remains constant (every 4 hours). So far the accuracy of the dispensing is good, just the timing is a bit inconsistent.

int driverPUL = 7;    // PUL- pin
int driverDIR = 6;    // DIR- pin
int spd = A0;     // Potentiometer
boolean setdir = LOW; 
int pd =9371; //needs to be calculated from the automation box.xls file 
int minutes = (10); // how many minutes you need to dispense the feed, maybe can conside to map the analog function to the time.
unsigned long loops = (minutes * 3200);
unsigned long stopfeed = (14400000); //stop the feeder for 4 hours minutes (4*60*60*1000)

void setup() { //system will start and initialize to dispense x2 feed, with 10 sec interval. before going into the main feed 
  pinMode (driverPUL, OUTPUT);
  pinMode (driverDIR, OUTPUT);
  minutes = map((analogRead(spd)),0,1023,0,10);
  loops = (minutes * 3200);
  for (int i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(10000); //stop for 10 seconds and repeat
    for (int i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(10000); //stop for 10 seconds and repeat
}

void loop() {
  // put your main code here, to run repeatedly:
  minutes = map((analogRead(spd)),0,1023,0,10);
  loops = (minutes * 3200);
  for (int i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(stopfeed);
}

Is there any issues with the code? or I am better to stick with an DS1302 with a clock?

This arithmetic is done in integers, so it rolls over at 32767. Try forcing it to be long/unsigned long:

  loops = (minutes * 3200UL);

Also the int i in these should be expanded to handle numbers larger than int's 32767:

Welcome to the forum

Using an RTC would be better

The problem is almost certainly caused by the fact that your calculated variables, such as loops and minutes do not have the values that you think they have. Try printing them and see

You really need to look into state machines and millis timing.
An RTC certainly could be helpful with the very long intervals, but delay() isn’t your friend in a project like this,

Yes, I think and RTC would be a better option in the long run

How does this look?

int driverPUL = 7;    // PUL- pin
int driverDIR = 6;    // DIR- pin
int spd = A0;     // Potentiometer
boolean setdir = LOW; 
int pd =9371; //needs to be calculated from the automation box.xls file 
int minutes = (10); // how many minutes you need to dispense the feed, maybe can conside to map the analog function to the time.
unsigned long loops = (minutes * 3200);
unsigned long stopfeed = (14400000); //stop the feeder for 4 hours minutes (4*60*60*1000)
unsigned long currentTime = 0; //starting point for current time 

void setup() { //system will start and initialize to dispense x2 feed, with 10 sec interval. before going into the main feed 
  pinMode (driverPUL, OUTPUT);
  pinMode (driverDIR, OUTPUT);
  minutes = map((analogRead(spd)),0,1023,0,10);
  loops = (minutes * 3200);
  for (unsigned long i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(10000); //stop for 10 seconds and repeat
    for (unsigned long i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(10000); //stop for 10 seconds and repeat
}

void loop() {
  // put your main code here, to run repeatedly:
    if ((millis()- currentTime) > stopfeed) {
    minutes = map((analogRead(spd)),0,1023,0,10);
    loops = (minutes * 3200);
      for (unsigned long i=0; i<loops; i++) {
        digitalWrite(driverDIR,setdir);
        digitalWrite(driverPUL,HIGH);
        delayMicroseconds(pd);
        digitalWrite(driverPUL,LOW);
        delayMicroseconds(pd);
      }
    }
}

why do you think this will fix your problem?

currentTime needs to be set to the value of millis() each time the condition is met

like a mixture between non-blocking timing calculating time-differences and blocking timing using delay()

The variablenames that you use sound a little bit odd to me

how many step-pulses does your stepper-motor need to make one revolution?

Some explanations to make your code shorter
this part of your code

    for (unsigned long i = 0; i < loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }

is written multiple times. Whenever code is written multiple times this part of the code can be put into its own function
let's call this part of the code "rotateStepperMotor"

void rotateStepperMotor(unsigned long p_loops) {
  digitalWrite(driverDIR, setdir); // it is enough to set direction once

  for (unsigned long i = 0; i < p_loops; i++) {
    digitalWrite(driverPUL, HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL, LOW);
    delayMicroseconds(pd);
  }
}

with this modification your code looks like this

int driverPUL = 7;    // PUL- pin
int driverDIR = 6;    // DIR- pin
int spd = A0;     // Potentiometer
byte setdir = LOW;
int pd = 9371; //needs to be calculated from the automation box.xls file
int minutes = 10; // how many minutes you need to dispense the feed, maybe can conside to map the analog function to the time.
unsigned long loops = minutes * 3200;
unsigned long stopfeed = 14400000; //stop the feeder for 4 hours minutes (4*60*60*1000)
unsigned long currentTime = 0; //starting point for current time


void setup() { //system will start and initialize to dispense x2 feed, with 10 sec interval. before going into the main feed
  pinMode (driverPUL, OUTPUT);
  pinMode (driverDIR, OUTPUT);
  minutes = map((analogRead(spd)), 0, 1023, 0, 10);
  loops = minutes * 3200;
  
  for (byte i = 0; i < 2; i++) {
    rotateStepperMotor(loops);
    delay(10000); //stop for 10 seconds and repeat
  }
}


void loop() {
  // put your main code here, to run repeatedly:
  if ( (millis() - currentTime) > stopfeed ) {
    currentTime = millis(); // must be updated each time the condition is met
    minutes = map((analogRead(spd)), 0, 1023, 0, 10);
    loops = minutes * 3200;
    rotateStepperMotor(loops);
  }
}


void rotateStepperMotor(unsigned long p_loops) {
  digitalWrite(driverDIR, setdir); // it is enough to set direction once

  for (unsigned long i = 0; i < p_loops; i++) {
    digitalWrite(driverPUL, HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL, LOW);
    delayMicroseconds(pd);
  }
}
int driverPUL = 7;    // PUL- pin
int driverDIR = 6;    // DIR- pin
int spd = A0;     // Potentiometer
boolean setdir = LOW; 
int pd =9371; //needs to be calculated from the automation box.xls file 
int minutes = (10); // how many minutes you need to dispense the feed, maybe can conside to map the analog function to the time.
unsigned long loops = (minutes * 3200);
const unsigned long stopfeed = (1200000); //stop the feeder for 4 hours minutes (4*60*60*1000)
unsigned long currentTime = 0; //starting point for current time 

void setup() { //system will start and initialize to dispense x2 feed, with 10 sec interval. before going into the main feed 
  pinMode (driverPUL, OUTPUT);
  pinMode (driverDIR, OUTPUT);
  currentTime = millis();
  minutes = map((analogRead(spd)),0,1023,0,10);
  loops = (minutes * 3200);
  for (unsigned long i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(10000); //stop for 10 seconds and repeat
    for (unsigned long i=0; i<loops; i++) {
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);
  }
  delay(10000); //stop for 10 seconds and repeat
}

void loop() {
  // put your main code here, to run repeatedly:
    if ((millis()- currentTime) > stopfeed) {
      minutes = map((analogRead(spd)),0,1023,0,10);
      loops = (minutes * 3200);
        for (unsigned long i=0; i<loops; i++) {
          digitalWrite(driverDIR,setdir);
          digitalWrite(driverPUL,HIGH);
          delayMicroseconds(pd);
          digitalWrite(driverPUL,LOW);
          delayMicroseconds(pd);
        }
      currentTime = millis ();
    }
}

This code doesnt work, inconsistent results after a few dispense
timelapse of the 24 hours dispense window

Question
sorry stupid question, is it okay if we declared "rotateStepperMotor at the bottom while it might be executed on top?

the motor needs 3200 pulses to make 1 rev

You can answer this question yourself by testing.
Run the code-version with function rotateStepperMotor

  • below loop()
  • above loop()
  • etc.

what exactly happens? You should unload extra work from your helpers
describe with precisision what can be seen in the video.
good to have the video but you should summarise what can be seen in the video

Another method is to use a serial terminal software that can write the received characters into a textfile. Me personal I prefer to use Bray's terminal because it is very intuitive to use and still has a lot of options

like

  • preparing request / responses
  • defining macros
  • even scripting is possible

If you add serial printing to your code and let brays terminal log all the printing into a textfile you can analyse what is going on.

Make sure to activate the timestamp
Brays-Terminal.zip (320.6 KB)

I have written some debug-macros that reduce the effort to write additional lines of code for comfortable serial debug-output

in some cases it is only interesting if a value has really changed
in some cases it is enough to print only

  • once per second
  • once per minute

the code has a link to a tutorial that explains how the macros work

// MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START *
// a detailed explanation how these macros work is given in this tutorial
// https://forum.arduino.cc/t/comfortable-serial-debug-output-short-to-write-fixed-text-name-and-content-of-any-variable-code-example/888298

#define dbg(myFixedText, variableName) \
  Serial.print( F(#myFixedText " "  #variableName"=") ); \
  Serial.println(variableName);

#define dbgi(myFixedText, variableName,timeInterval) \
  { \
    static unsigned long intervalStartTime; \
    if ( millis() - intervalStartTime >= timeInterval ){ \
      intervalStartTime = millis(); \
      Serial.print( F(#myFixedText " "  #variableName"=") ); \
      Serial.println(variableName); \
    } \
  }

#define dbgc(myFixedText, variableName) \
  { \
    static long lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }

#define dbgcf(myFixedText, variableName) \
  { \
    static float lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }
// MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END *

So every 10 minutes in the video, it should dump a dose of 0-10 turns worth of food into the bucket?

So some of the variable names are confusing.

  • "minutes" seems like the number of stepper-turns.
  • "loops" seems like the number of steps per feeding
  • "pd" looks like the time between steps

And with pd= 9371 microseconds, then it steps at about:

3200*9371*2/1000000 = 59 // seconds to make a turn.
10 turns = 590sec

At a feed-every-10 minute-interval in the video, just turning the stepper looks like it could take about 10 minutes before you get into the timing between feedings.

Stefan's code looks pretty good, but I'd rename "loops" to "steps", and follow stefan's advice in:

and make the pot->steps calculation like:

steps = map(analogRead(spd),0,1023,0,3200UL*minutes);

...to avoid low resolution arithmetic confusing things.

As is, your code filters the whole 1023 steps of the potentiometer into a 0-10 position switch, with position 10 taking about 10 minutes to process.

I'm not sure what the interaction between the 0-to-10 minute long feeding would do with the 10 minute interval you have in the video.

Look at blink without delay example and adapt that. Stop using delay

thank you @StefanL38

code works, timelapse of testing it over 28 hours!

https://youtu.be/CvdjI79bJ1k

will look into this to help to troubleshoot!