servo help

whats wrong here?

#include <Servo.h>

Servo servo_3;

bool up = true;

void setup()
{
pinMode(2, INPUT);
servo_3.attach(3);

}

void loop()
{
if (up == up) {
if (digitalRead(2) == HIGH) {
servo_3.write(180);
up = !up;
//the servo should go 180 degrees up when i push the button on pin 2
}
}

if (up == !up) {
if (digitalRead(2) == HIGH) {
servo_3.write(0);
up = up;
// the servo should go down here again when i push the button on pin 2
}
}
}

This will never be true:

  if (up == !up)

ok, but i need "up" to be true, and switch to false like i tried in the command, can you write an example?

If you need to check if up is true then the command is "if (up == true). To change up from whatever it is to the opposite then you use "up = !up". That will change true to false or false to true depending in what it is now. So you're nearly there.

Steve

thanks for help :slight_smile:

if (up == up) {

  • if (digitalRead(2) == HIGH) {*

  • servo_3.write(180);*

  • up = !up; // you set this to !up when you pressed the button once *

  • //the servo should go 180 degrees up when i push the button on pin 2*

  • }*

  • }*

  • if (up == !up) { // now here you asked again if the up value is !up. you declared up to !up when you pressed it the first time which makes the servo go back to zero.*

  • if (digitalRead(2) == HIGH) {*

  • servo_3.write(0); // it goes back and never goes to 180. *

  • up = up;*

  • // the servo should go down here again when i push the button on pin 2*

  • }*

  • }*

// try setting two button vals old button val and new button val.
#include <Servo.h>
int oldButtonVal;
int newButtonVal;
Servo servo;
int buttonval;

void setup(){
servo.attach( your servo pin);
pinMode( button pin , INPUT);

}

void loop(){
buttonval = digitalRead( button pin);
if(buttonval == 0){
oldButtonVal = 0;
newButtonVal = 0;
}

if(buttonval == 1){
oldButtonVal = 0;
newButtonVal =1;
}

if(oldButtonVal == 0 && newButtonVal == 1){
servo.write(180);
oldButtonVal = 1;
newButtonVal = 0;
}

if(oldButtonVal == 1 && newButtonVal == 0){
servo.write(0);
oldButtonVal = 0;
newButtonVal = 1;
}

i havent done right spacing or anything . but you can type this into arduino ide and it will be correct. just try it.

if(buttonval == 0){
   oldButtonVal = 0;
   newButtonVal = 0;
}

if(buttonval == 1){
  oldButtonVal = 0;
  newButtonVal =1;
}

A simple “else” would suffice - no need to retest.
(Also, HIGH and LOW are defined for your convenience. Please use them)

Please remember to use code tags when posting code.