JChristensen / JC_Button

Arduino library to debounce button switches, detect presses, releases, and long presses
GNU General Public License v3.0
425 stars 102 forks source link

Setup Inputs breaks the code #29

Closed Sastas closed 3 years ago

Sastas commented 3 years ago

I found that if I use in the setup area to set up my inputs also, not just my outputs, the code start to act weird, first it is put my led on, then sometimes its start blinking or just dont do anything. Just modified one of the examples to visualize:


#include <JC_Button.h>          // https://github.com/JChristensen/JC_Button

// pin assignments
const byte
    BUTTON1_PIN(10),            // connect a button switch from this pin to ground
    LED1_PIN(12);                // connect an LED to ground, through an appropriate current limiting resistor

ToggleButton                    // define the buttons
    btn1(BUTTON1_PIN);         // this button's initial state is off

void setup()
{
    // initialize the button objects
    btn1.begin();

    // set the LED pins as outputs
    pinMode(LED1_PIN, OUTPUT);

    //This is breaking the code
    pinMode(BUTTON1_PIN, INPUT);

    // show the initial states
    digitalWrite(LED1_PIN, btn1.toggleState());
}

void loop()
{
    // read the buttons
    btn1.read();

    // if button state changed, update the LEDs
    if (btn1.changed()) digitalWrite(LED1_PIN, btn1.toggleState());

}
JChristensen commented 3 years ago

A pullup resistor for the button is required. Without it, the pin picks up stray fields which create spurious input. Change pinMode(BUTTON1_PIN, INPUT) to pinMode(BUTTON1_PIN, INPUT_PULLUP) and the problem goes away. However, calling pinMode() for a Button object is redundant as the call to Button::begin() sets the proper pin mode, so I do not recommend it.