Switch is not working

The switch is not working, it seems that the servo motor works itself before i open the switch, any help will be appreciated. Thanks. The code is as below:

int buttonPin = 8;
#include <Servo.h>
int servoPin = 9;
Servo servo;
int angle = 0; // servo position in degrees
int state=1;
int button =LOW;
boolean lastButton = LOW;
boolean currentButton = LOW;
long currentTime;
long previousTime;

void setup() 
{
pinMode(buttonPin, INPUT);
servo.attach(servoPin);
}

boolean debounce (boolean last)
{
  boolean current = digitalRead(buttonPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(buttonPin);
  }
  return current;
}

void loop() {
 button = digitalRead(buttonPin); //normally open switch
 currentTime = millis();
 currentButton = debounce(lastButton);
if (lastButton ==LOW && currentButton == HIGH)
 {
 switch(state)
 {
 case 1 :
 if (button == HIGH)
 {
  previousTime=currentTime;
  state=2;
 }
 break;
 case 2 :
 if (currentTime - previousTime > 2000)
 {
   Liftup();
   state=3;
 }
 break;
 default:
 break;
 }
 }
   lastButton = currentButton;
}

  void Liftup()
  {
    servo.write(-90);
  }

How is the switch wired ?
Do you have a pulldown resistor on buttonPin or is it floating at an unknown voltage ?

pinMode(buttonPin, INPUT);

So you use a external pull up / pull down?

UKHeliBob was first :stuck_out_tongue:

Yes there is a external pull up resistor on buttonPin.

You say open the switch. Do you mean you press it while starting the Arduino? Because the button is normaly open and pulled up. (So HIGH in rest)

Because if you don't when you start if (lastButton ==LOW && currentButton == HIGH) will become true because you initialize lastButton to LOW and currentButton will be high (because of the pull UP).

And, because you attach the servo but don't write a position you want the library uses the mid position (90 degree (or does it use 0, don't remember..)) The Arduino can not read the current position of the servo. It can only send a new position. So the servo moves to that position on start up. If it needs to start somewhere else you need to set it.

And some notes:

  • You code indentation is terrible!

  • Why use button inside the switch instead of the "debounced"version?

  • Debounce with delay can work but delays are evil. Why noT use a debounce library?

  • servo.write(-90); is wrong. servo.write() works on the range 0 to 180. If outside this range it is set to the min of max. So -90 will become 0 in the library. And so will -89, -70 etc...

  • In case 3 you set state to 3. 3 does not exist so it will run the default. Default is empty so the program will be stuck there....

Hi,

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Tom..... :slight_smile:

You say open the switch.

"Open the switch" means "turn on" in some countries and "turn off" in others. Beware.