/* 
    simple (3,3V) digital pulse counter with reset ESP32
Count the digital pulses fed to terminal D5. For reliability, the minimum 
pulse width is 10 microseconds.
If one of the signals has changed (from high to low), ESP32 counts 
as one pulse.  
                     Steve Barth 2021 
*/

//#include <Arduino.h>

const int input = 5;                // This is input pin.
const int enable = 4;                // This is enable pin.
int pulse = 0;                       // Variable pulses count.
int mod = 0;                         // counting mode

void setup()
{
    pinMode(input, INPUT_PULLUP);       // set input pin
    pinMode(enable, INPUT_PULLUP);      // set enable pin
    pinMode(2, OUTPUT);
    Serial.begin(9600);                    // set serial monitor connect
    Serial.println("program start");          // Message
}

void loop()
{
    if (digitalRead(enable) != 0)
    {
        if (digitalRead(input) != mod)
        {
            
            pulse++;
            mod = 1;
            Serial.print("Pulse: ");// message
            Serial.print(pulse);
            /* Put an "s" if the amount of pulses is greater than 1.
            if (pulse > 1)
            {
            Serial.print(F("s"));
            }*/
            Serial.println("");
        }
    

        if (digitalRead(input) == 0)
        {
            mod = 0;
        }

        delayMicroseconds(1);                // Delay for stability.

    if (digitalRead(enable) == 0)
    {
        digitalWrite(2, HIGH);
        delayMicroseconds(1);
        digitalWrite(2, LOW);
        pulse = 0;
    } 
  
    }
}