FREQUENCY METER

Hi all

I want to do a frequency meter .

The basis of frequency meter is counting pulses in a time frame , so
frequency is equal number of pulses/time frame (herts)

The result will be sent serially to a regular LCD display with serial input .

How do I count pulses in a time frame with arduino ?
I need the C code skeleton, no need to go to C level commands .

Thanks
Elico

Count a bunch of pulses using an interrupt and see how long that took. You then have pulses and time. The more pulses, the better your average. Also use micros() for time.

I wrote a program for one guy here just last week but he decided to stick with a library.

Here it is, just happened to have a copy in my sketchbook. You can change what you want.

volatile unsigned long pulseCount = 0UL;
unsigned long startT, endT, freq, pC;

void counter()
{ 
  pulseCount++;
}

void setup()
{
  Serial.begin(38400);
  Serial.println( "Frequency counter" );
  attachInterrupt(0, counter, RISING);
}

void loop()
{
  noInterrupts();
  pC = pulseCount;
  interrupts();
  
  if ( pC == 1UL )
  {
    startT = micros(); // start time very close to on a pulse edge
    // getting end time should have the same lag within a few cycles
  }

  // if pulses are 5/second, 10 seconds will take 50 pulses --- check the 5/sec!
  if ( pC >= 51UL ) // 50 pulses -after- pulse 1
  {
    endT = micros();

    endT -= startT; // end now holds elapsed micros

    // frequency = pulses/second, we have pulses and microseconds, 1000000 usecs/sec
    // Hz = pulses x 1000000 / microseconds   

    freq = pC * 1000000UL / endT;

    Serial.print( "\n count " );
    Serial.println( pC );
    Serial.print( " micros " );
    Serial.println( endT );
    Serial.print( " freq " );
    Serial.println(freq);

    noInterrupts();
    pulseCount = 0UL;
    interrupts();
  }
}

You will find many examples if you search for: arduino frequency counter

For example this one, http://interface.khm.de/index.php/lab/experiments/arduino-frequency-counter-library/

Many thanks
Elico

elico:
I need the C code skeleton, no need to go to C level commands .

Absolutely.