Hey,
I think I have a solution for you. It utilizes the millis() function, but keeps track of current time and elapsed time only while a switch is ON. Also, when the elapsed time reaches a predetermined amount (500 milliseconds) it changes direction.
It stays in the 'while' loop and keeps spinning the motor back/forth until the switch is turned off, then it exits WHILE loop and finishes IF scope keeping track of the current elapsed motor time.
Next time the switch is flipped on, it will keep track of current elapsed time PLUS previous elapsed time, until it totals 500 milleseconds, then it will toggle direction and reset the previous elapsed time to zero - so it doesn't keep adding the lastTime into the current elapsedTime.
Anyway, I hope it makes sense. Fairly simple though. It could be refined more I'm sure. I just wrote this up because it seemed you had a valid question that I was curious about as well. Fun stuff.
int toggleSwitch = 10; // switch on digital pin 10
int motorRight = 11; // output to motor to spin clockwise - pin 11
int motorLeft = 12; // output to motor to spin counter-clockwise - pin 12
unsigned long currentTime;
unsigned long startTime;
unsigned long lastTime = 0;
unsigned long elapsedTime;
unsigned long timeToChange = 500; // .5 seconds -- doesn't need to be unsigned long, but this will let you make it really large
int motorDirection = 0; // 0 for clockwise (right) 1 for counterclockwise (left) this is the starting motor direction
void motorSpin()
{
if (motorDirection == 0)
{
motorLeft = LOW;
motorRight = HIGH;
}
if (motorDirection == 1)
{
motorRight = LOW;
motorLeft = HIGH;
}
}
void motorKill()
{
motorLeft = LOW;
motorRight = LOW;
}
void directionToggle()
{
if (motorDirection == 0)
motorDirection = 1;
if (motorDirection == 1)
motorDirection = 0;
}
void setup()
{
pinMode(motorRight, OUTPUT);
pinMode(motorLeft, OUTPUT);
pinMode(toggleSwitch, INPUT);
}
void loop()
{
if (toggleSwitch == HIGH)
{
startTime = millis(); // sets the start of the countdown - only for the first
// time the switch is flipped. After that, it only resets
// the counter when it reaches 500 milliseconds
motorSpin();
while (toggleSwitch == HIGH)
{
currentTime = millis();
elapsedTime = (currentTime - startTime + lastTime);
if (elapsedTime > timeToChange)
{
directionToggle();
startTime = millis();
lastTime = 0; // resets 'lastTime' to zero so it won't keep adding it into current elapsed time
}
}
motorKill(); // stops motors
lastTime = elapsedTime; // records current elapsed time
}
}
hope this works for you