I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.
The problem is that my code is fine on startup, but when i press the button the servo continues to spin.
How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// CONSTANTS
// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR
// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise
// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off
void setup()
{
myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
pinMode (crServo, OUTPUT);
pinMode (buttonPinCW, INPUT); // sets button as input
pinMode (buttonPinCC, INPUT); // sets button as input
myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}
void loop()
{
crServo = digitalRead(crSpeedDefault);
buttonStateCW = digitalRead(buttonPinCW);
buttonStateCC = digitalRead(buttonPinCC);
// clockwise rotation
if (buttonStateCW == HIGH) {
myservo.write(crSpeedCW);
// counterclockwise rotation
}
if (buttonStateCC == HIGH) {
myservo.write(crSpeedCC);
}
}
crServo = digitalRead(crSpeedDefault);there? Withconst int crServo = 12the variable cannot be changed. It doesn't make sense to re-write the servo pin to 0 or 1 using the result ofdigitalRead, which reads from pin 0 which is the Serial TX of the Arduino.