This program counts the frequency of a single output encoder on pin D2 it can be changed to suit your encoder by changing the defines at the top and playing with the sample time.
Diff: main.cpp
- Revision:
- 0:fb3e19364d48
diff -r 000000000000 -r fb3e19364d48 main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Tue Jan 26 12:54:37 2016 +0000 @@ -0,0 +1,37 @@ +#include "mbed.h" + +#define TICKS_PER_REVOLUTION 12.0 +#define TICK_CHECK_PERIOD 0.1 + +DigitalOut myled(LED1); +Serial pc(USBTX, USBRX); // tx, rx +Ticker periodicTimer1, periodicTimer2; + +float speed_rpm, speed_rps, ticks_per_second; +volatile unsigned int tick_counter, final_count; + +InterruptIn freqInputPin(D2); + +void freqInputPin_Interrupt() { + //Triggers on the rising edge of the frequency signal + tick_counter++; +} + +void check_TickCount(){ + final_count = tick_counter; + //pc.printf("\n\rTick Count is : %d", final_count); + tick_counter = 0; +} + +void display_TickCount(){ + //pc.printf("\n\r Final Count is : %.2f", (float) final_count*(1.0/TICK_CHECK_PERIOD)); + pc.printf("\n\r Speed in RPM is : %.2f", (float)(final_count*(1.0/TICK_CHECK_PERIOD))*(60.0/TICKS_PER_REVOLUTION)); +} + +int main() { + freqInputPin.rise(&freqInputPin_Interrupt); //chain interrupt to rising edge + periodicTimer1.attach(&check_TickCount, TICK_CHECK_PERIOD); + periodicTimer2.attach(&display_TickCount, 1.0); //Display conut once a second + while(1) { + } +}