Need Help With If-Else Statement

Im a beginner and this is my first post so if i write something wrong please forgive me.Im writing a code that turns a servo with a potentiometer.That part works fine but i also want to add a button that turns the servo to 90 degree but when i press the button it doesn't turn.Only the potentiometer works.Im sure that arduino detects the button press because it prints it on the serial port.And here is the code:

#include <Servo.h>

Servo myservo;


  int set = 1;


void setup() {

  

  pinMode(2, INPUT);
  pinMode(4, OUTPUT);

  Serial.begin(9600);
  myservo.attach(3);
}

void loop() {


  

int Val = analogRead(0);                        

int mappedVal = map(Val, 0, 455, 0, 180);      

      if (digitalRead(2) == HIGH) {
    
           int set = 0; 
           Serial.println("PRESSED");
           myservo.write(90);

      } 
      
      else {
      
      int set = 1;
      Serial.println("NOT PRESSED");
      
      }

      if (set = 1) {

      myservo.write(mappedVal);
      delay(15);
      
      }
}

If something is wrong with the code or missing please help me.Thank you for any advice.

Now this generates a different variable called the same name (set) as you have elsewhere.

Only have the int in front of set once, like you have at the beginning. Do not have it with int in front of it anywhere else.

Here you need == instead of =.

So your button is using a pulldown resistor? Can you show your circuit?

I will try it.Thank you for advice

Yes.I put a 10k resistor between GND and Digital pin 2.The other side of the button connected to 5v.Here is a picture of connections:

1 Like

Does it matter if i use "==" or "="?What does it change when i use two symbols?

Now it works perfectly!Thank you guys so much.Have a nice day :slight_smile:

Yes it matters especially if you want an if statement to work.

= is an assignment operator which means make the variable on the left hand side contain the value of the expression on the right hand side.

== is a logical comparison, it returns a true variable if the expression on the left hand size is the same as the expression on the right hand side.

No, you will do it along with all the other stuff that has been pointed out to you.
This is because:-

And you don't know how to program.

Thank you.Also i write the code all by myself.Im trying to improve my coding.Thank you again for helping me with the code.

2 Likes

Full credit for writing your own. :slightly_smiling_face:

See this for many more operators and useful information:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.