I am placing a 180 degree servo inside a wooden box, and the lid of the box is hinged. The servo has two pushbuttons, one to open, and one to close.
The close function, on pin 4, works perfectly. It will cut off the open function and close the box, if pressed while opening, which is what I want.
The open function, on pin 2, is delayed. After closing the box, and trying to open it again, the servo will wait around five seconds to execute the command.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
int openButton = 2; //names pin 2 as the openButton pin
int closeButton = 4; //names pin 4 as the closeButton pin
int openbuttonState = LOW;
int closebuttonState = LOW;
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 200; // the debounce time; increase if the output flickers
void setup() {
pinMode(openButton, INPUT); // sets pin 2 as an input
pinMode(closeButton, INPUT); //sets pin 4 as an input
myservo.attach(9); //Gives the servo power
}
void loop() {
// put your main code here, to run repeatedly:
openbuttonState = digitalRead(openButton);
closebuttonState = digitalRead(closeButton);
if ( (millis() - lastDebounceTime) > debounceDelay) {
if (openbuttonState == HIGH) {
myservo.write(0); //use the servo to open the box
lastDebounceTime = millis(); //set the current time
}
if (closebuttonState == HIGH) {
myservo.write(90); //use the servo to close the box
lastDebounceTime = millis(); //set the current time
}
}
}
I am using a 9V battery and a 5V regulator to power the servo, while my Nano is powered through USB(I know 9V batteries aren't enough for sustained projects, it's just for testing purposes.)
The pushbuttons are run off of the Nano's 5V output.
What is causing this delay? I'm going crazy trying to find it...