it maybe looks like a dumb quistion but im still in my learning process and im really trying to look on the internet but sometimes i don't really get it to make it work. my code is as followed:
#include <Arduino.h> #include <Servo.h> Servo Myservo; int SERVO_PIN = 8; int ServoButton_S1 = 2; void setup() { Myservo.attach(SERVO_PIN); } void loop() { Myservo.write(0); delay(2000); Myservo.write(90); delay(2000); Myservo.write(180); delay(2000); }
The servo now goes from 0 degrees (wait 2 sec) and than goes to 90 degrees (wait 2 sec) and goes to 180 degrees and so it continious.
The problem is that i want a servo that moves whenever i press the button. so its like when i press the button the servo goes to 90 degrees but when i press the button again it goes to 180 degrees and when i push it again to 0 degrees and so it has to continue. so i added the button and i called it:
int servobutton_s1 = 2;
but whenever i added it in the void loop it only works 1 time.
i hope someone can help me out. Thanks
CodePudding user response:
You have to check the button state for every loop iteration.
Something like:
#include <Arduino.h>
#include <Servo.h>
Servo Myservo;
int SERVO_PIN = 8;
const int ServoButton_S1 = 2;
int some_counter = 0;
void setup() {
Myservo.attach(SERVO_PIN);
}
void loop()
{
//read the state of the pushbutton value:
int buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (some_counter == 0)
{
Myservo.write(0);
delay(2000);
some_counter;
}
else if (some_counter == 1)
{
Myservo.write(90);
delay(2000);
some_counter;
}
else if (some_counter == 2)
{
Myservo.write(180);
delay(2000);
some_counter = 0;
}
}
}
You can also check the Arduino website; there are a lot of tutorial examples.
CodePudding user response:
This is just another solution.
#include <Servo.h>
#define SERVO_PIN 8
#define ANGLE_BUTTON 2
Servo Myservo;
int counter = 0;
int angles[] = {0, 90, 180};
int angleAmounts = sizeof(angles) / sizeof(angles[0]);
void setup() {
pinMode(ANGLE_BUTTON, INPUT_PULLUP);
Myservo.attach(SERVO_PIN);
}
void loop()
{
int buttonState = digitalRead(ANGLE_BUTTON);
if (buttonState == LOW) {
counter = counter % angleAmounts;
Myservo.write(angles[counter]);
delay(2000);
}
}
