Clearing state for ezbutton in arduino IDE

Hi, I am trying to run a simple automated device with a motor and a limit switch. I have most of the code working, however certain times when I am getting the state of the limit switch, it seems to read the state from when the state was previously read. Even if the button hasnt been pressed in multiple seconds and update the state using
int state = limitSwitch.getState();

here is a simple script I made that demonstrates the issue

#include <ezButton.h>


//Setup all Pin Locations
ezButton limitSwitch(7);  // create ezButton object that attach to pin 7;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  limitSwitch.setDebounceTime(50); // set debounce time to 50 milliseconds
}

void loop() {
  // put your main code here, to run repeatedly:
  while (true) {
      limitSwitch.loop();
      int state = limitSwitch.getState();
      if(state == LOW){
        Serial.println("The limit switch: TOUCHED");
        break;  // Exit loop
      } else {
        Serial.println("The limit switch: UNTOUCHED");
      }
  }

  Serial.println("next loop");
  delay(1000);
 
}

once i press the button I get 2 outputs sayings its been pressed even though I would think it should only be 1
The limit switch: UNTOUCHED

The limit switch: UNTOUCHED

The limit switch: TOUCHED

next loop

The limit switch: TOUCHED

next loop

I know its probably a simple thing but I'm not that familiar with C and i havent been able to figure it out

The function loop() is a while(true) loop, so this line is redundant.

Try configuring your button pin with an internal pullup resistor...

byte buttonPin = 7;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Hi are you referring to the limitSwitch.loop()? cause if thats a while loop what is the conditions for breaking out of it?

No. See post #2.

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