Frequency Counter

29 Jul 2011

I’m trying to build a simple frequency counter application using ticker with InterruptIn. Every thing is working in order as long as the frequency is less than 100kHz. Am using PWM to generate the input for the counter, when the frequency goes above 100KHz, my counter will read out the half of the correct value.

I really need to measure frequencies up to 250KHz. I presume this should be easily achievable with mbed considering that it runs at 96MHz

Is there something wrong with my code? Or will be there any other method that allow me to measure frequencies up to 250KHz?

Below is my simple code

Thank you all

#include "mbed.h"
#include "TextLCD.h"
unsigned int counts;
float freq;
TextLCD lcd(p15, p16, p17, p18, p19, p20); // rs, e, d4-d7
class Counter {
    Counter(PinName pin) : _interrupt(pin) {        // create the InterruptIn on the pin specified to Counter
        _interrupt.rise(this, &Counter::increment); // attach increment function of this counter instance

    void increment() {

void clear() {
        _count = 0;

    unsigned int read() {
        return _count;

    InterruptIn _interrupt;
    volatile unsigned int _count;

Ticker out;
Counter counter(p5);
PwmOut x(p21);
void output() {
  counts =; 
  freq = counts;


int main() {
  out.attach(&output, 1);
    while(1) {
    x= 0.5;
   // x.pulsewidth_us(1) ;
        lcd.printf("freq: %f\r\n", freq);
01 Aug 2011

This thread has a good explanation from Andy on how you can work around this problem.

The issue is that the ISR installed by the InterruptIn code is relatively CPU intensive as it appears to check the rising and falling interrupt status for all 32 pins of Port0 and all 16 pins of Port2, even though you only care about one of them. Therefore it is best to replace the use of InterruptIn code with your own as Andy mentions in the linked forum post.

Maybe someone has written a replacement for the InterruptIn class?

04 Aug 2011

Thanks Adam this was very useful, Andy's code worked for me.


11 Jul 2018

This code is not running for 2MHZ to be counted at counter pin of Microcontroller. Do any one have idea how to run this code for mhz frequency?

Please log in to post a reply.