I'm currently trying to control a servo by using a limit switch. My goal is to have the Servo act as a counter of sorts by having the servo move a little bit every time the limit switch is triggered, up to a predetermined count where it will then move back to it's original position.
Currently, the servo i'm using moves counter clockwise whenever the switch is pressed, up to a maximum of 90 degrees if i hold the switch down. The servo motor will then return to it's original position after i release the switch.After a few seconds, the motor will then twitch/vibrate before moving, as if it's moving against alot of pressure/strain.
How do i control the servo so that:
- The servo holds it's position even after the switch is released
- Make the servo move only a little every time the switch is pressed
My code thus far:
#include <Servo.h>
Servo myServo;
const int switch1 = 2;
const int servo1 = 9;
int switch1Val;
int servo1Val;
int prevServo1Val = 10;
int counter = 0;
void setup(){
Serial.begin(9600);
myServo.attach(9);
pinMode(switch1,INPUT);
pinMode(servo1,OUTPUT);
}
void loop(){
switch1Val = digitalRead(switch1);
//If the switch is pressed
if(switch1Val == HIGH){
//increase the counter by 1
counter++;
if(counter < 5){
Serial.println(counter);
servo1Val = prevServo1Val + 10;
analogWrite(servo1,servo1Val);
prevServo1Val = servo1Val;
}
else{
//Resets counter
counter = 0;
//Moves servo back to original position
analogWrite(servo1,0);
}
}/*else{
//The switch is not being pressed
analogWrite(servo1,prevServo1Val);
}*/
}
What i've tried so far
- Use a delay(1000) at the end of the code.However, when i introduce the delay(commented out in the code above), the servo does not move at all when the switch is pressed.
- Use an else(if the switch is not being pressed), HOWEVER, when the else condition is included, the servo keeps vibrating when the switch is not pressed(as if the servo is trying to move, but is unable to)
Note::
Servo Model: Hitec HS-225BB
Limit Switch: OMRON 1185RE8
Any help would be appreciated!