I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// variables will change:
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable for reading the pushbutton status
int button_mode = 1; // Variable for the button's current state.
// button_mode = 1 when the button is up, and 0 when the button is pressed.
// This variable is 'static' and persists because it is declared outside a function.
void setup() {
myservo.attach(8); // attaches the servo on pin 9 to the servo object
Serial.begin(9600); // Initialize the Serial port at 9600 baud.
pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
}
void loop() {
buttonState = digitalRead(9);
if ((digitalRead(9) == LOW) && (button_mode == 1)) {
// Check Digital pin 9 to see if it's pressed.
pos = 150; //set servo position variable to 150
myservo.write(pos); //set servo postion to 'pos'
delay(1000); // wait 1 second
button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
Serial.println("Button has been pressed."); // and report that to the serial monitor.
} else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
pos = 50;
myservo.write(pos);
delay(1000);
button_mode = 1; // Button was down before, but is released now. Set the button to
Serial.println("Button has been released"); // released and report that to the serial monitor.
}
delay(100); //small delay to account for button bounce
}
2 Answers 2
The code is not well structured. Here is what I would do:
if (button_pressed()) { //test to see if button is pressed
button_state +=1; //increment button
if (button_stat & 0x01) {//if lsb set
myservo.write(SERVO_POS1); //set servo position 1
} else {
myservo.write(SERVO_POS2); //set servo position 2
}
}
You can debounce if you wish in button_pressed().
Do something like this:
int angles[2] = {0,180}
bool state = 0;
then:
if(button == PRESSED)
state = !state;
finnally, to control the servo:
Servo.write(angles[state]);
Explore related questions
See similar questions with these tags.