Simple button counter issue

mostlymat
Posts: 1
Joined: Thu Oct 27, 2022 2:24 am

Simple button counter issue

Postby mostlymat » Thu Oct 27, 2022 3:20 am

I am working on a simple button push counter program and I seem to be missing something. My goal is to make the counter go up with every button press and store the variable. The program compiles and prints "0" to the serial monitor but does not respond to the button being pushed. I'm using the ESP32-WROOM-32 Dev board and I have tried a few different ones with the same result. I found most of this code here https://esp32io.com/tutorials/esp32-button and modified it but I recognize this may not be the best way to go about this. Any advice is appreciated. Cheers.

Code: Select all

#define BUTTON_PIN 21 // GIOP21 pin connected to button


// Counter variable
int counter = 0;

// Variables will change:
int lastState = HIGH; // the previous state from the input pin
int currentState;     // the current reading from the input pin

void setup() {
  Serial.begin(115200);
  // initialize the pushbutton pin as an pull-up input
  pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  // read the state of the switch/button:
  currentState = digitalRead(BUTTON_PIN);
  
  // compare last state to the new one
  if(lastState == LOW && currentState == HIGH)
    counter = counter ++;
    Serial.println(counter);
  

  // save the last state
  lastState = currentState;


  delay (50);
}

chegewara
Posts: 2364
Joined: Wed Jun 14, 2017 9:00 pm

Re: Simple button counter issue

Postby chegewara » Sat Oct 29, 2022 1:49 am

mostlymat wrote:if(lastState == LOW && currentState == HIGH)
You should check why this code is never true.
Tip: what are the initial values.

boarchuz
Posts: 605
Joined: Tue Aug 21, 2018 5:28 am

Re: Simple button counter issue

Postby boarchuz » Sat Oct 29, 2022 2:49 pm

mostlymat wrote:
Thu Oct 27, 2022 3:20 am

Code: Select all

    counter = counter ++;
This is undefined behaviour (https://stackoverflow.com/questions/949 ... d-behavior).

Who is online

Users browsing this forum: No registered users and 99 guests