Hi, I have padlock project. I'm using Arduino Nano and Servo. The padlock will be lock if the servo angle is 90 and will be unlock if the servo angle is 60.
So, I'm thinking about getting back the servo from 60 to 90 using a switch button. But, I don't know what's wrong with my code. Here's my code :
#include <Servo.h>
Servo slock; // create servo object to control a servo
int pos = 90; // variable to store the input servo position
int buttonLock = 2; // lock button location
int buttonState = 0; // variable for reading lock button status
void setup()
{
Serial.begin(9600); // initialize serial:
slock.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(buttonLock, INPUT); // set lock button as input
}
void loop()
{
buttonState = digitalRead(buttonLock);
if (Serial.available() > 0) // if there's any serial available, read it:
{
pos = Serial.parseInt(); // get the input variable for position
if ((pos > 59) && (pos < 91)) //ignore anything less than 90 or greater than 60
{
Serial.print(pos); //print the value to the serial monitor
slock.write(pos); // tell servo to go to position in variable 'pos'
}
delay(15); // waits 15ms for the servo to reach the position
}
{
if (buttonState == HIGH) // button pushed
{
slock.write(90); // lock the servo
}
delay(15);
}
}
When I upload the code above, whenever I send serial 60 from the serial monitor, the servo will bounce back to 90. Any ideas about where I do wrong with the code? Thank you!