There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.

So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.

I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.



value = 0
if button is pressed:
  value = 1 - value
  • So simple! I'm almost embarrassed I didn't think of it myself.
    – Gabe Ruiz
    Feb 14 '15 at 21:39
  • Be aware that you will need to debounce the input pin, otherwise you will get erratic results due to the mechanical bounce of the contacts.
    – kiwiron
    Feb 15 '15 at 7:36
  • So that means I will need to set it back to low with digitalWrite(pin,LOW)?
    – Gabe Ruiz
    Feb 15 '15 at 20:35
  • No, that means that you will have to use the method in the Debounce example to detect button presses if your button isn't already debounced. Feb 15 '15 at 20:43
  • Would a pull down resistor have the same function?
    – Gabe Ruiz
    Feb 16 '15 at 4:54

It sounds like you are using a number as a boolean (true/false) value.

You might consider using a a boolean instead.

boolean value = false;
if button is pressed {
if value {
    // do something here.

You can set it to true or false, or change it to it's opposite (with value=!value as shown above). You can also do if value or if !value ("if not value") - these are equivalent to if value=true or if value=false.

  • Thank you for the suggestion. I was not aware of the Boolean option.
    – Gabe Ruiz
    Feb 16 '15 at 4:15
  • int buttonPin = 10; boolean value = false; void setup(){ pinMode(buttonPin, INPUT); Serial.begin (9600); } void loop(){ if (digitalRead(buttonPin) == HIGH) { value=!value; } Serial.println(value); delay(10); } I am using this code. The readout on the serial.Print still reads 0 even if I press the button. I have installed a LED to make sure the button is working and the light turns on whenever I press the button.
    – Gabe Ruiz
    Feb 21 '15 at 21:39
  • The code you gave, just looking at it quickly, should turn value on and off every 10 milliseconds while you press the button. What happens if you move the println inside the if() statement? Feb 22 '15 at 21:08

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.