1

I've been learning how to encapsulate my code within functions, and one of the examples I worked on is a simple INPUT_PULLUP button. When I upload the sketch from the arduino website everything works, so I know it's not a hardware issue. However, with the code below the button will just not go LOW.

I just don't see what the issue is, and I'm feeling really hopeless that I can't even get the simple thing done. I would be grateful for any advice.

int button_pin = 2;
int button_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button_pin, INPUT_PULLUP);
}

void loop() {
  Button();
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state = LOW) {
    Serial.println(button_state);
  };
};
2
  • 3
    You have an error in the if statement. For checking equality, you need to use == (double equal sign). A single = is an assignment. So you are actually assigning the value LOW to button_state. And an assignment will return the value, that you assigned, in this case LOW, aka 0, aka false. Thus the if statement will never be entered – chrisl Feb 17 at 9:46
  • Thanks Chris, I will try this and report. I don't know what I would do without you people. I wasted several hours on this yesterday trying everything I could think of with no success. – Zhelyazko Grudov Feb 17 at 9:50
1
#define button_pin 2  //defining button pin as pin 2
bool button_state = 0; //button state is either 0/1 so using bool
void Button();
void setup()
{
    Serial.begin(9600);
    pinMode(button_pin, INPUT_PULLUP); //Setting input as input pullup
}

void loop()
{
    Button();
}

void Button()
{
    
    button_state = digitalRead(button_pin); //Read button state
    if (button_state == LOW)
    {
        Serial.println(button_state); //print button state when it is low
    }
}

In your code, you have used = operator in place of == in the if loop. Just if you change it, it will start working also you can use my above code it is same as yours just I have made some minor changes such as using bool in place of int and use of #define in place of pin declaration where you used int

2
  • Thank you very much for taking the time to answer. It's really helpful and I appreciate it. – Zhelyazko Grudov Feb 17 at 11:48
  • 1
    @ZhelyazkoGrudov I am glad it helped you out. Good luck :) – Maaz Sk Feb 17 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.