Program a Servo Motor to be operated by a Pushbutton
Add a pushbutton to your circuit.
Refer to other pushbutton diagrams on the wiki.
// Control the direction of your servo motor with a pushbutton
int servoPin = 9; // Control pin for servo motor
int minPulse = 500; // Minimum servo position
int maxPulse = 2500; // Maximum servo position
int pulse = 0; // Amount to pulse the servo
long lastPulse = 0; // the time in milliseconds of the last pulse
int refreshTime = 20; // the time needed in between pulses
int counter = 0;
int inButton = 3; // choose the input pin (for a pushbutton)
int valButton = 0; // variable for reading the pin status
void setup() {
pinMode(servoPin, OUTPUT); // Set servo pin as an output pin
pinMode(inButton, INPUT);
pulse = minPulse; // Set the motor position value to the minimum
Serial.begin(9600);
}
void loop() {
valButton = digitalRead(inButton); // read input value
if (valButton == HIGH){
pulse = 500; // changing this number will change the position it will go to
}
else{
pulse = 2400; // changing this number will change the other position it will go to
}
// pulse the servo again if the refresh time (20 ms) has passed:
if (millis() - lastPulse >= refreshTime) {
digitalWrite(servoPin, HIGH); // Turn the motor on
delayMicroseconds(pulse); // Length of the pulse sets the motor position
digitalWrite(servoPin, LOW); // Turn the motor off
lastPulse = millis(); // save the time of the last pulse
}
}
Comments (0)
You don't have permission to comment on this page.