I tried other code to control servo sweep without delay and a led with a switch but when i click the switch the led turns on only when the servo is rotating.. any help ?
#include <Servo.h>
int buttonState = 0;
class Sweeper
{
Servo servo; // the servo
int pos; // current servo position
int increment; // increment to move for each interval
int updateInterval; // interval between updates
unsigned long lastUpdate; // last update of position
public:
Sweeper(int interval)
{
updateInterval = interval;
increment = 1;
}
void Attach(int pin)
{
servo.attach(pin);
}
void Detach()
{
servo.detach();
}
void Update()
{
if((millis() - lastUpdate) > updateInterval) // time to update
{
lastUpdate = millis();
pos += increment;
servo.write(pos);
Serial.println(pos);
if ((pos >= 180) || (pos <= 0)) // end of sweep
{
delay(5000);
// reverse direction
increment = -increment;
}
}
}
};
Sweeper sweeper1(20);
void setup()
{
Serial.begin(9600);
sweeper1.Attach(9);
pinMode(7, INPUT_PULLUP);
pinMode(12, OUTPUT);
}
void loop()
{
sweeper1.Update();
buttonState = digitalRead(7);
if (buttonState == HIGH) {
digitalWrite(12, HIGH);
} else {
digitalWrite(12, LOW);
}
}