Push Botton Counter dejar de contar

Hola amigos,

Me estoy rompiendo la cabeza con este código que lo tomé de la librería, es muy bueno te cuenta las veces que se oprime un Push Botton.

Actualmente uso el mismco código para un sensor digital. El problema es que necesito que cuando termine de contar regrese a su estado inicial, y no lo hace sino que sigue sumando los pulsos infinitamente......para cuando no està contando y luego sigue cuando se activa el sensor, pero no empieza desde cero sino desde el último número contado. Intentaré adjuntarles el monitor serial.

El pin se agregó un comando PULLUP que es para activar una resistencia de 10kohms que entiendo el Arduino UNO trae incluida. Y eso ayudó bastante.

El segundo problema es que inicia contando desde 1, no desde 0. Esto quizás porque el sensor está en HIGH y arduino lo lee como 1, pero si cambio el valor inicial a LOW, se desconfigura el código y ya no lee nada.

Llevo unos 4 meses trabajando en este código, pero al modificarlo ya no me envía los datos al serial.

Tanto el arduino como el sensor están conectados a la misma tierra.

Se que aquí hay masters en Arduino y quiero aprender de ustedes.

Muchas gracias.

// this constant won't change:
const int  buttonPin = A2;    // the pin that the pushbutton is attached to
const int ledPin = 9;       // the pin that the LED is attached to

// Variables will change:
int Cantidad = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT_PULLUP);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}


void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      Cantidad++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(Cantidad);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(10);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;


  // turns on the LED every four button pushes by checking the modulo of the
  // button push counter. the modulo function gives you the remainder of the
  // division of two numbers:
  if (Cantidad % 4 == 0) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }

}

El problema es que esto

 // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

queda fuera del bloque

if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      Cantidad++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(Cantidad);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(10);
  }

y se ejecuta en cada ciclo loop() cuando solo deberia ejecutarse si el estado actual del boton es diferente al que habia guardado.

 if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      Cantidad++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(Cantidad);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(10);
    lastButtonState = buttonState;
  }

Otra cosa que veo,usando la entrada en pullup,el pulsador deberia estar conectado a gnd y la entrada estaria normalmente en HIGH puesto que esta conectada a 5v y cuando pulses el boton deberias leer LOW .

 if (buttonState == LOW) {

Hola
Tratare de ayudarte aunque te falta dar mas información.
1.-Que sensor es?
2.-Se comporta igual a un pulsador? es decir, cambia de estado de 0 a 1 y cuando no está trabajando siempre hay un 0? o puede quedar en cualquier estado?
3.-Tu sensor es tan lento como un pulsador o trabaja a una frecuencia alta?

El problema es que necesito que cuando termine de contar regrese a su estado inicial

cuanto tiempo es necesario para saber que el sensor se detuvo o cada cuantos pulsos quieres que regrese a 0?

Le hice unos cambios a tu código suponiendo que el sensor se comporta como un pulsador y que lo tienes correctamente conectado en pull-up (un pin a gnd y el otro al pin A2). Espera medio segundo sin recibir señal para regresar el contador a 0, si necesitas mas o menos tiempo modifica el valor de la variable retardo,
prueba lo y comenta

// this constant won't change:
const byte  buttonPin = A2;    // the pin that the pushbutton is attached to
const byte ledPin = 9;       // the pin that the LED is attached to

// Variables will change:
int Cantidad = 0;   // counter for the number of button presses
bool buttonState;         // current state of the button
bool lastButtonState;     // previous state of the button
bool flag; 
unsigned long tiempo;
unsigned long retardo=500;


void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT_PULLUP);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}


void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (!buttonState  && lastButtonState ) {  //detectas el cambio de estado del boton, no uso antirrebote porque los sensores digitales no rebotan
      Cantidad++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(Cantidad);
      tiempo=millis();
      flag=true;

      if (Cantidad % 4 == 0) 
         digitalWrite(ledPin, HIGH);
      else 
         digitalWrite(ledPin, LOW);    
    } 

      lastButtonState = buttonState;

   if (buttonState && millis() - tiempo >= retardo) {  // este retardo es para detectar que no hay actividad en el boton
          
       if(flag){   // para que solo imprima en el monitor serial una sola vez       
          Serial.println("off");
          Cantidad=0;
          flag=false;
       }
     
     }
}

Si tu sensor puede quedar en cualquier estado cuando está en reposo, cambia esta linea if (buttonState && millis() - tiempo >= retardo) por ésta if (millis() - tiempo >= retardo) así el contador regresara a 0, cuando no haya cambio de estado y pase el tiempo establecido en la variable retardo

Porque doble posteas? Tienes este hilo iniciado aqui y el mismo en el foro en inglés. Eso es una falta a las normas.
Los dos estan con respuestas y me da no se que cerrarte alguno pero si un moderador del foro en inglés se da cuenta lo hará sin contemplación.
No lo vuelvas a hacer.

Estimados, no me queda mas que agradecer sus comentarios, positivos o negativos. En verdad como dice Subrite que imagino conoce mucho pues he leído tus sugerencias, coloqué el código en inglés pues cuando lo postee no ví ninguna respuesta.

No está demás decir que en el inter tuve que investigar y estudiar todas las funciones, operadores, análisis y ejemplos, y por supuesto el método de prueba y error, y no fue hasta hoy que vi sus post, se imaginan, pero lo fácil hubiera sido copiar las respuestas y ya!. Estoy muy feliz de haber logrado este código y por norma del foro y en agradecimiento a todos ustedes aquí les posteo la versión final, recuerden que este es adaptado a mi pulsador, no puedo asegurar que servirá para cualquier tipo.

Saludos y gracias.

// this constant won't change:
const int buttonPin = A2;      // the pin that the pushbutton is attached to
const int ledPin = 9;           // the pin that the LED is attached to

// Variables will change:
int Total;            // counter for the number of button presses
bool Lectura;          // current state of the button
bool nuevoLectura;     // previous state of the button
bool flag;
unsigned long tiempo;
unsigned long retardo = 1000;


void setup() {
 pinMode(buttonPin, INPUT_PULLUP);
 pinMode(ledPin, OUTPUT);
 Serial.begin(115200);
}

void loop() {

 Lectura = digitalRead(buttonPin);

 if (Lectura != nuevoLectura) {

   if (Lectura == LOW) {
     ++Total;
     Serial.print(Total);
     Serial.println(",");
     digitalWrite(ledPin, HIGH);
     tiempo = millis();
     flag = true;
   }
   else {
     if (Lectura == HIGH);
     digitalWrite(ledPin, LOW);
   }
 }
   
   nuevoLectura = Lectura;

   if (Lectura && millis() - tiempo >= retardo) {
     if (flag) {
     Serial.println(" ");
       Total = 0;
       flag = false;
     }
   }
}

Debes editar tu mensaje y poner el codigo entre las etiquetas adecuadas.

if (Lectura == LOW) {
   ++Total;
   Serial.print(Total);
   Serial.println(",");
   digitalWrite(ledPin, HIGH);
   tiempo = millis();
   flag = true;
}else {
   // if (Lectura == HIGH);  --> Sabes que es verdad para que preguntas.
   digitalWrite(ledPin, LOW);
}

Luego para resetear tu contados debes preguntar directamente por flag no por Lectura.

if (flag && millis() - tiempo >= retardo) {
   Serial.println(" ");
   Total = 0;
   flag = false;
}