Arduino Servocontrol with 2 buttons

Hello!

I want to control my lightswitch with an Arduino and a servo. For prototyping i build it on a breadboard with two buttons for now. Later I will use Bluetooth(HC-05).

My problem is that the servo just goes to 135° then to 120° all the time although my buttons are being pulled down to 0V.

Thanks!

#include <LiquidCrystal.h>
#include <Servo.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo myservo;  

int AnPin = 6;
int AusPin = 7;
int An;
int Aus;
void setup()
{
  myservo.attach(9);  
lcd.begin(8,2);
}

void loop() 
{ 
  checkPins();

  if  (An = 1) {
    myservo.write(135);
    delay(250);
    myservo.write(120);
      }
  if (Aus = 1) {
    myservo.write(85);
    delay(250);
    myservo.write(120);
  }
delay(10);
} 


void checkPins() {
   An = digitalRead(6);
   Aus = digitalRead(7);
}

well two errors

first one

  if  (An = 1) {

and

  if (Aus = 1) {

these are not a comparison, you are setting An and Aus to 1 and this returns true so you always execute what's after.

second issue:

  if  (An = 1) {
    myservo.write(135);
    delay(250);
    myservo.write(120);
      }

and what should happen when you release the button and An is back to zero may be there is something to do there? (same for Aus)

(assuming your button is LOW by default, really connected to ground and you get a HIGH when you press the button)

hope this helps

Thanks very much!

Will this work:

if (An > 0) {

When An or Aus is 0 nothing needs to happen :wink:

well technically yes, but it's not good programming practice as this represent a digital pin state so can have only 2 values LOW or HIGH

you should write to have readable code:

if (An == HIGH) {
   // do what's needed when button is pressed

} else {
  // button is LOW
  // do what's needed when button is not pressed

}

note that it would be good to remember the last value of the button and if there is no change, then don't send commands to the servo at all. some low quality servo will jitter a bit even if you tell them to go to the position they already are set to.

Now everything works flawlessly

:slight_smile: :slight_smile: