/**************************************************************************************************
*
*  PulseCountAsync
*
*   Version:      1.0.0 - September 2009
*   Author:       Etienne Ribeiro    / tutorial assistant caad      /  eribeiro[at]ethz.ch
*   Supervisor:   Christoph Wartmann / chair for caad - ETH Zürich  /  wartmann[at].arch.ethz.ch
*
*   Desc:         Counts pulses on a digital pin over a given period asynchronously.
*
*   Functions:    int PulseCounstAsync (int digitalPin, int delayIntervall)
*                    The function need to be called constantly in loop and returns a value, when
*                    delayIntervall time is over.
*                    int digitalPin: pin to listen to.
*                    int delayIntervall: intervall in ms to listen.
*                    returns -1 if no new value is available or the pulse.
*
***************************************************************************************************/



// var
long modPulse_millisStart = -2;
boolean modPulse_lastState = false;
int modPulse_HzCounter = 0;




int PulseCounstAsync (int digitalPin, int delayIntervall) {

        // Pinmode (only at first call of this function)
        if (modPulse_millisStart == -2) {
                pinMode(digitalPin, INPUT);
                modPulse_millisStart = -1;
        }


        // Start
        if (modPulse_millisStart > millis ())
        modPulse_millisStart = -1;
        if (modPulse_millisStart == -1)
        modPulse_millisStart = millis ();


        // Count Hz Intervall
        int val = digitalRead (digitalPin);
        if (val == HIGH && modPulse_lastState == false) {
                modPulse_lastState = true;
                modPulse_HzCounter += 1;
        }
        if (val == LOW && modPulse_lastState == true)
        modPulse_lastState = false;


        // Return ?
        if (modPulse_millisStart + delayIntervall < millis()) {

                // Reset Values
                int tmpmodPulse_HzCounter = modPulse_HzCounter;
                modPulse_HzCounter = 0;
                modPulse_millisStart = -1;


                // Calculate Hz
                int Hz = tmpmodPulse_HzCounter * (1000 / delayIntervall);


                // ret
                return Hz;

        } else
        return -1;

}

This website has been archived and is no longer maintained.