Had a small mistake in the posted code. ![]()
Here is version 2.
Points if you can tell what was wrong with the sketch in post #7.
//Version two
#include <Servo.h>
Servo servo;
bool servoMoving = false;
const byte sensor_pin = 7; //+5V---[Sensor]---GND
const byte servo_pin = 2; //servo pin
byte moveTo = 0;
byte currentLocation = 0;
byte servoSpeed = 10; //10ms between increments
int val; //sensor
int incDec = 1;
unsigned long servoMillis;
//*******************************************************************
void setup()
{
pinMode (sensor_pin, INPUT_PULLUP); //sensor
servo.attach(servo_pin);
} //END of setup()
//*******************************************************************
void loop()
{
val = digitalRead(sensor_pin);
//*********************
if (servoMoving == false && val == 0)
{
moveTo = 0;
if (currentLocation >= moveTo)
{
incDec = -1;
}
else
{
incDec = 1;
}
//the servo is now going to move
servoMoving = true;
//start the TIMER
servoMillis = millis();
}
//*********************
if (servoMoving == false && val == HIGH)
{
moveTo = 90;
if (currentLocation >= moveTo)
{
incDec = -1;
}
else
{
incDec = 1;
}
//the servo is now going to move
servoMoving = true;
//start the TIMER
servoMillis = millis();
}
//*********************
//if enabled, is it time to move the servo ?
if (servoMoving == true && millis() - servoMillis > servoSpeed)
{
//restart the TIMER
servoMillis = millis();
moveServo();
}
} //END of loop()
//*******************************************************************
void moveServo()
{
if (currentLocation == moveTo)
{
//we have arrived
servoMoving = false;
return;
}
currentLocation = currentLocation + incDec;
servo.write(currentLocation);
} //END of moveServo()