
Originally Posted by
siredward
Here is the complete code -
I am trying to substitute a millis() based function for delay()
If the delay commands were to be uncommented, and the first two lines in the function servoSweep() were to be commented out, then the servo sweeps.
However if the delays are commented out as seen below, the millis code here does not do what I intend for it to.
Any thoughts on using millis() in place of delay for servo pauses?
Thank you
Code:
//SweepwithMillis
#include <PWMServo.h>
PWMServo myservo;
int previousMillisServo = 0;
int pos = 0;
long servoInterval = 15;
unsigned long currentMillis = 0;
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
servoSweep();
}
void servoSweep() {
if (currentMillis - previousMillisServo > servoInterval) {
previousMillisServo = currentMillis;
for (pos = 0; pos <= 175; pos += 1) {
myservo.write(pos);
//delay(15);
}
for (pos = 175; pos >= 0; pos -= 1) {
myservo.write(pos);
//delay(15);
}
}
@siredward:
The very first time your program calls the servoSweep() function, using the values of currentMillis (which == 0), previousMillisServo (which == 0), & servoInterval (which == 15), your "if" comparison looks like this:
With these values, this comparison will never be true, so nothing after this in the servoSweep() function will be executed. Maybe you intended to add the following as the first line in the servoSweep() function:
Code:
currentMillis = millis();
As an alternative, you could just do away with the currentMillis variable & use the millis() call in its place as follows:
Code:
void servoSweep() {
if (millis() - previousMillisServo > servoInterval) {
previousMillisServo = millis();
for (pos = 0; pos <= 175; pos += 1) {
myservo.write(pos);
//delay(15);
}
for (pos = 175; pos >= 0; pos -= 1) {
myservo.write(pos);
//delay(15);
}
}
However, this still suffers from another problem: the original code using the delay(15) call will delay 15ms between servo steps, but your modified code will not delay at all between servo steps. Not sure if this is what you intended. Normally, if you want to use the millis() function call to allow you to delay for a fixed amount, you would use the following generic approach (using the previous 15ms delays as an example):
Code:
void servoSweep() {
for (pos = 0; pos <= 175; pos += 1) {
myservo.write(pos);
previousMillisServo = millis();
// delay for the servoInterval
while ((millis() - previousMillisServo) < servoInterval) ;
}
for (pos = 175; pos >= 0; pos -= 1) {
myservo.write(pos);
previousMillisServo = millis();
// delay for the servoInterval
while ((millis() - previousMillisServo) < servoInterval) ;
}
}
See if that's what you had in mind. Let me know if I misinterpreted you intentions and/or if you have any other questions.
Good luck & have fun !!
Mark J Culross
KD5RXT