I have a sketch where Im using millis()/1000 to capture the time stamp when a for loop ends.
I set a variable "time" = (millis()/1000)
If time+30 <= (millis()/1000) then do something.
will I run into memory issues doing this? Is their a better method. My end goal is to prevent the for loop from running unless their is a 30 second gap.
Im running this on an Arduino Uno \
thanks
Dave
CODE** #include <VarSpeedServo.h>
VarSpeedServo servo1;
int pos = 0;
int ServoMax = 100; //Max Servo angle
int ServoMin = 50; //Mix Servo angle
int ServoCen = 75; //Servo center
int ServoSpeed = 50; //Speed at which servo rotates
int Val = 0; //Dynamic PIR state
int x = 0;
int i = 0;
int time = 0;
void setup() {
servo1.attach(9); //Servo PIN
pinMode(2,INPUT); //PIR Pin
Serial.begin(9600);
Serial.println ("Calibrating PRI");
for (x=0;x<20;x++){ //delay in seconds to allow PIR to fully boot up
Serial.print (".");
delay (1000);
}
Serial.println();
Serial.println("Calibration Complete");
}
void loop() {
Val=digitalRead(2);
if (Val==HIGH && time+30<=(millis()/1000)) //check for motion and minimum time interval (30 seconds)
{
Serial.print("Motion Detected at ");Serial.println(millis()/1000);
time=(millis()/1000);
int i = random (1,5); //count of servo movements
for (x=0;x<i;x++){
Serial.print("Servo Movement: ");Serial.print(x+1);Serial.print(" of ");Serial.println(i);
int position = random(ServoMin,ServoMax);
servo1.slowmove(position,ServoSpeed);
delay(random(1000,3000)); } // delay between movements
Jurs - Sorry guess I didnt mean memory more of general will this sketch crash. From what you said basically yes it will. if I were to change time from int to unsigned long would this help my problem, or would the more simple solution is to create a new for statement?
Im more or less a noob so any advice will be appreciated.
Basically you need a long unsigned int, but you need to use the relitave time not the absolute time. That is always treat the millis as giving you the current start time and then use millis minus the start time > time interval in milliseconds.
See the blink without delay in the example section of the IDE.
The demo Several Things at a Time is an extended example of BWoD and illustrates the use of millis() to manage timing. It may help with understanding the technique.
Always use subtraction when checking the elapsed time.