Frequency counter counting pulses at the input.

Dependencies:   mbed

main.cpp

Committer:
hudakz
Date:
2017-06-30
Revision:
0:a18601268a31

File content as of revision 0:a18601268a31:

#include "mbed.h"

#define GATE_TIME   0.5 // Gate time (period of time to count pulses within) in seconds

Serial              pc(USBTX, USBRX);
InterruptIn         input(p9);  // input line
Timeout             timeout;
volatile bool       measuringEnabled = false;
volatile uint32_t   counter;

//ISR to count pulses
void onPulse(void) {
    if (measuringEnabled)
        counter++;
}

// ISR to stop counting
void stopMeasuring(void) {
    measuringEnabled = false;
}

// Initializes counting
void startMeasuring(void) {
    counter = 0;
    timeout.attach(callback(&stopMeasuring), GATE_TIME);
    measuringEnabled = true;
}

int main(void) {
    input.rise(callback(&onPulse)); // assign an ISR to count pulses
    while (1) {
        startMeasuring();
        while (measuringEnabled);   // wait until the measurement has completed
        if(GATE_TIME < 1)
            wait(1 - GATE_TIME);    // wait at least one second before printing
        pc.printf("counter   = %d\r\n", counter);
        pc.printf("frequency = %f\r\n", (double)counter / GATE_TIME);
    }
}