Problem of not reccognizing push button

Attached is part of a larger program. The issue is it does not respond to a button push.

  if (CMDID == 5)
   {
    digitalWrite(Lft, LOW);
    while ((RbuttonPushCounter < 2))
     {
      RbuttonState = digitalRead(RbuttonPin);
      digitalWrite(Rgt, HIGH);
      delay(1000);
      digitalWrite(Rgt, LOW);
      delay(1000);

      Serial.print("now ");
      Serial.println(RbuttonState);
      Serial.print("last ");
      Serial.println(RlastButtonState);

      if (RbuttonState != RlastButtonState) 
      {
        RbuttonPushCounter++;
        (RlastButtonState = RbuttonState);
        Serial.print("CNT = ");
        Serial.println(RbuttonPushCounter);
      }

      if ((RbuttonPushCounter >= 2)) {
        RbuttonPushCounter = 0;
        digitalWrite(Rgt, LOW);
        break;
      }
    }
  }

  if (CMDID == 7) 
  {
    digitalWrite(Rgt, LOW);  // Turn Relay OFF
    digitalWrite(Lft, LOW);
    Serial.println("Relay Deactivated");
  }

Does the push button work with a simple test program?

In which program you set the pin mode for the input?

Post a complete sketch that doesn't see the button press.

Say how you wired the button!

a7

Without the surrounding code, we just have to assume that this condition will be true at some point:

However, regarding this next one:

we don't know how that counter is being set and incremented. Without debounce, that count could easily become exceeded. However, without reference to the remaining code its impossible be certain of anything and therefore make a meaningful comment.

here's the whole code and it does work on a simple sketch to turn a relay on/off with the same wiring

#include "DFRobot_DF2301Q.h"
#include <esp_now.h>
#include <WiFi.h>
uint8_t broadcastAddress[] = { 0x14, 0x08, 0x08, 0xa5, 0xd7, 0x68 };
DFRobot_DF2301Q_UART DF2301Q(/*hardSerial =*/&Serial1, /*rx =*/D7, /*tx =*/D6);
#define Rgt D0
#define Lft D1

int RbuttonPin = D2;
int RbuttonPushCounter = 0;  // counter for the number of button presses
int RbuttonState = 0;        // current state of the button
int RlastButtonState = 0;

int LbuttonPin = 29;
int LbuttonPushCounter = 0;  // counter for the number of button presses
int LbuttonState = 0;        // current state of the button
int LlastButtonState = 0;

typedef struct struct_message
{
  int b;
}
 struct_message;
struct_message myData;
esp_now_peer_info_t peerInfo;
DFRobot_DF2301Q_I2C asr;

void OnDataSent(const esp_now_send_info_t *tx_info, esp_now_send_status_t status) 
{
  if (status == ESP_NOW_SEND_SUCCESS) 
  {
    Serial.println("Send Success");
  } else {
    Serial.println("Send Fail");
  }
}

void setup() 
{
  Serial.begin(115200);
  myData.b = 0;
  WiFi.mode(WIFI_STA);

  if (esp_now_init() != ESP_OK)
   {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  esp_now_register_send_cb(OnDataSent);
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;
  if (esp_now_add_peer(&peerInfo) != ESP_OK) 
  {
    Serial.println("Failed to add peer");
    return;
  }
  pinMode(Rgt, OUTPUT);
  pinMode(Lft, OUTPUT);

  while (!(asr.begin()))
   {
    Serial.println("Communication with device failed, please check connection");
    delay(3000);
  }

  Serial.println("Begin ok!");
  asr.setVolume(7);
  asr.setMuteMode(0);
  asr.setWakeTime(255);

  uint8_t wakeTime = 0;
  wakeTime = asr.getWakeTime();
  Serial.print("wakeTime 4= ");
  Serial.println(wakeTime);

  /**
     @brief Play the corresponding reply audio according to the ID
     @param CMDID - command word ID
  */

  pinMode(RbuttonPin, INPUT_PULLUP);
  pinMode(LbuttonPin, INPUT);
  RbuttonPin = HIGH;
  LbuttonPin = HIGH;
}

void loop()
{
  uint8_t CMDID = 0;
  CMDID = DF2301Q.getCMDID();
  Serial.print("CMDID = ");
  Serial.println(CMDID);
  if (CMDID == 5)
   {
    digitalWrite(Lft, LOW);
    while ((RbuttonPushCounter < 2))
     {
      RbuttonState = digitalRead(RbuttonPin);
      digitalWrite(Rgt, HIGH);
      delay(1000);
      digitalWrite(Rgt, LOW);
      delay(1000);

      Serial.print("now ");
      Serial.println(RbuttonState);
      Serial.print("last ");
      Serial.println(RlastButtonState);

      if (RbuttonState != RlastButtonState) 
      {
        RbuttonPushCounter++;
        (RlastButtonState = RbuttonState);
        Serial.print("CNT = ");
        Serial.println(RbuttonPushCounter);
      }

      if ((RbuttonPushCounter >= 2)) {
        RbuttonPushCounter = 0;
        digitalWrite(Rgt, LOW);
        break;
      }
    }
  }

  if (CMDID == 7) 
  {
    digitalWrite(Rgt, LOW);  // Turn Relay OFF
    digitalWrite(Lft, LOW);
    Serial.println("Relay Deactivated");
  }

  delay(500);
  //GREEN = 8, WHITE = 9, RED = 10, CRUISE ON = 11, CRUISE SET = 12, ADAPT ON = 13, NEAR = 14, FAR = 15
  if (CMDID == 0 || CMDID == 8 || CMDID == 9 || CMDID == 10 || CMDID == 11 || CMDID == 12 || CMDID == 13 || CMDID == 14 || CMDID == 15 || CMDID == 16)
  {
    (myData.b = CMDID);
    (CMDID == 0);
    Serial.println(myData.b);
    uint8_t data[sizeof(myData)];
    memcpy(data, &myData, sizeof(myData));
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&myData, sizeof(myData));
    if (result == ESP_OK) {
      Serial.println("Sent with success");
    } else {
      Serial.println("Error sending the data");
    }
  }
  delay(1000);
}

Ok, but help us help you. At what point in your program development did it stop working?

here you set the pin # to a valid value

int RbuttonPin = D2;

and configure the pin

    pinMode (RbuttonPin, INPUT_PULLUP);

but then you set the pin # to HIGH? did you intend to set the RbuttonState?

    RbuttonPin = HIGH;

i never got t to work from the state and been trying different logic for a week. If I delete RbuttonPin it starts off as pushed once and if set it to LOW button doesn't get recognized

using the code below, i got the following with multiple iterations thru loop just pressing and releasing the button one time because it doesn't handle bounce

loop
CNT = 1
CNT = 2
loop
CNT = 1
CNT = 2
loop
CNT = 1
CNT = 2
loop
CNT = 1
CNT = 2
loop
CNT = 1
CNT = 2
loop
int RbuttonPin = A2;
int RbuttonPushCounter = 0;  // counter for the number of button presses
int RbuttonState = 0;        // current state of the button
int RlastButtonState = 0;

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (115200);

    pinMode (RbuttonPin, INPUT_PULLUP);
    RlastButtonState = RbuttonState = digitalRead (RbuttonPin);
}


// -----------------------------------------------------------------------------
void loop ()
{
    Serial.println ("loop");

    while ((RbuttonPushCounter < 2)) {
        RbuttonState = digitalRead (RbuttonPin);

        if (RbuttonState != RlastButtonState) {
            RbuttonPushCounter++;
            (RlastButtonState = RbuttonState);

            Serial.print ("CNT = ");
            Serial.println (RbuttonPushCounter);
        }
    }

    RbuttonPushCounter = 0;
}

i get the following when pressing the button 4 time

CNT = 1
CNT = 2
CNT = 3
CNT = 4

using this code


int PinBut    = A2;
int butState;
int cnt;

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (115200);

    pinMode (PinBut, INPUT_PULLUP);
    butState = digitalRead (PinBut);
}


// -----------------------------------------------------------------------------
void loop ()
{
    byte but = digitalRead (PinBut);

    if (butState != but)  {             // but state change
        butState  = but;
        delay (50);                     // debounce
        
        if (LOW == but)  {              // pressed
            cnt++;
            Serial.print ("CNT = ");
            Serial.println (cnt);
        }
    }
}

i got that but buttonpushcounter doesnt change

the variables checked in the while loop that needs to be < 2 for the loop to run?

the code sets RbuttonPushCounter to zero when it exits the loop so that the loop can run again

please study the last code i posted

you may find it better to have a sub-function to report if a button is pressed for multiple buttons managed as an array

const byte PinButs [] = { A1, A2, A3 };
const int  Nbut       = sizeof(PinButs);

int butState [Nbut];

// -----------------------------------------------------------------------------
bool
isButPressed (
    int  n )
{
    byte but = digitalRead (PinButs [n]);

    if (butState [n] != but)  {         // but state change
        butState [n] = but;
        delay (50);                     // debounce
        
        if (LOW == but)
            return true;
    }

    return false;
}

// -----------------------------------------------------------------------------
void loop ()
{

    for (int n = 0; n < Nbut; n++)  {
        if (isButPressed (n))  {
            Serial.print   ("  but ");
            Serial.print   (n); 
            Serial.println (" pressed");
        }
    }
}

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin   (115200);
    Serial.println ("rdy");

    for (int n = 0; n < Nbut; n++)  {
        pinMode (PinButs [n], INPUT_PULLUP);
        butState [n] = digitalRead (PinButs [n]);
    }
}
    RbuttonPin = HIGH;
    LbuttonPin = HIGH;

What will be the value of RbuttonPin and LbuttonPin after these 2 lines of code are executed ?

Then in this line of code

            RbuttonState = digitalRead(RbuttonPin);

Which button will be read ?

OK..This has to be the most frustrating sketch I've ever tried. I tried the suggestions from above and tried numerous iterations. I get the the relay cycling but using the button to stop it is the issue. Now when I called CMDID 5, now and last start out at 1 and button pushes are ignored.

#include "DFRobot_DF2301Q.h"
#include <esp_now.h>
#include <WiFi.h>
uint8_t broadcastAddress[] = { 0x14, 0x08, 0x08, 0xa5, 0xd7, 0x68 };
DFRobot_DF2301Q_UART DF2301Q(/*hardSerial =*/&Serial1, /*rx =*/D7, /*tx =*/D6);
#define Rgt D0
#define Lft D1

int RbuttonPin = D2;
int RbuttonPushCounter = 0;  // counter for the number of button presses
int RbuttonState = 0;        // current state of the button
int RlastButtonState = 0;

int LbuttonPin = 29;
int LbuttonPushCounter = 0;  // counter for the number of button presses
int LbuttonState = 0;        // current state of the button
int LlastButtonState = 0;

typedef struct struct_message {
  int b;
} struct_message;
struct_message myData;
esp_now_peer_info_t peerInfo;
DFRobot_DF2301Q_I2C asr;

void OnDataSent(const esp_now_send_info_t *tx_info, esp_now_send_status_t status) {
  if (status == ESP_NOW_SEND_SUCCESS) {
    Serial.println("Send Success");
  } else {
    Serial.println("Send Fail");
  }
}

void setup() {
  Serial.begin(115200);
  myData.b = 0;
  WiFi.mode(WIFI_STA);

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  esp_now_register_send_cb(OnDataSent);
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;
  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }
  pinMode(Rgt, OUTPUT);
  pinMode(Lft, OUTPUT);

  while (!(asr.begin())) {
    Serial.println("Communication with device failed, please check connection");
    delay(3000);
  }

  Serial.println("Begin ok!");
  asr.setVolume(7);
  asr.setMuteMode(0);
  asr.setWakeTime(255);

  uint8_t wakeTime = 0;
  wakeTime = asr.getWakeTime();
  Serial.print("wakeTime 4= ");
  Serial.println(wakeTime);

  /**
     @brief Play the corresponding reply audio according to the ID
     @param CMDID - command word ID
  */

  pinMode(RbuttonPin, INPUT_PULLUP);
  pinMode(LbuttonPin, INPUT_PULLUP);
  RlastButtonState = RbuttonState = digitalRead(RbuttonPin);
}

void loop() {
  uint8_t CMDID = 0;
  CMDID = DF2301Q.getCMDID();
  Serial.print("CMDID = ");
  Serial.println(CMDID);
  if (CMDID == 5) {
    digitalWrite(Lft, LOW);
    while ((RbuttonPushCounter < 2)) {
      RbuttonState = digitalRead(RbuttonPin);

      if (RbuttonState != RlastButtonState) {
        RbuttonPushCounter++;
        (RlastButtonState = RbuttonState);
        delay(50);
        Serial.print("CNT = ");
        Serial.println(RbuttonPushCounter);
      }

      digitalWrite(Rgt, HIGH);
      delay(1000);
      digitalWrite(Rgt, LOW);
      delay(1000);

      Serial.print("now ");
      Serial.println(RbuttonState);
      Serial.print("last ");
      Serial.println(RlastButtonState);
    }
      digitalWrite(Rgt, LOW);
      
    RbuttonPushCounter = 0;
  }


  if (CMDID == 7) {
    digitalWrite(Rgt, LOW);  // Turn Relay OFF
    digitalWrite(Lft, LOW);
    Serial.println("Relay Deactivated");
  }

  delay(500);
  //GREEN = 8, WHITE = 9, RED = 10, CRUISE ON = 11, CRUISE SET = 12, ADAPT ON = 13, NEAR = 14, FAR = 15
  if (CMDID == 0 || CMDID == 8 || CMDID == 9 || CMDID == 10 || CMDID == 11 || CMDID == 12 || CMDID == 13 || CMDID == 14 || CMDID == 15 || CMDID == 16) {
    (myData.b = CMDID);
    (CMDID == 0);
    Serial.println(myData.b);
    uint8_t data[sizeof(myData)];
    memcpy(data, &myData, sizeof(myData));
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&myData, sizeof(myData));
    if (result == ESP_OK) {
      Serial.println("Sent with success");
    } else {
      Serial.println("Error sending the data");
    }
  }
  delay(1000);
}

Could you express your thought more clearly?

Is your voice recognition seeing this as one or many calls?

This immediately runs twice (when RbuttonPushCounter equals 0 and 1). It then assigns "HIGH" to to RbuttonState, increases RbuttonPushCounter by one, and prints now 1 and last 1

When you use words like "now" and "last" and "start" in code, you need to show they are code and not just words, for example, using double quotes (as above) or tick marks (`), making the words "now" and "last" look like now and last or "bold" like now and last.

Further, you do not use now or last rather, you use RbuttonState and RlastButtonState... the less confusion of your writing versus your meaning, the better.

The buttons will always be connected to those pins, correct? At least while the code is running? So those variables will never need to change their values while the code is running, that's right, isn't it?

It's a good idea to declare them as const:

const int RbuttonPin = D2;

const int LbuttonPin = 29;

That way, if your code accidentally changes the value of those variables, you will get an error message when you try to upload the code, showing where in the code the change would happen (but should not happen).

Declaring a variable as const means that, apart from being given it's initial value, the code is not allowed to change the value: it's value sholud be "constant".

If you do this, I think you will find you get such errors, and then you will understand what @gcjr and @UKHeliBob are telling you.

There are a number of tests in your code. Try printing the values that you are testing before you test them.

Does the code reach the sections of code that you expect ?
Are the values of the variables that you are testing what you expect ?

what do you want this block of code to do? wait for a button press?