Go Down

### Topic: Frequency / period counter (Read 14465 times)previous topic - next topic

#### avandalen

##### Nov 25, 2011, 03:26 pmLast Edit: Jan 19, 2012, 04:45 pm by avandalen Reason: 1
Arduino frequency counter facts
Here is a frequency counter for the Arduino which measure the period and pulse width, it was needed for a pedelec legalisation device and a scale interface. Look for the latest version here:
http://www.avdweb.nl/arduino/frequency-period-counter.html

• The period is measured instead of the frequency; this is done to save program space. The frequency can be calculated with 1/period; however this will include the float library which takes a lot of memory. Thus the frequency calculation is left out of the library code.

• These values are available: frequency, period, pulseWidth, pulseWidthLow, elapsedTime and level.

• The frequency counter can be used in two ways:
With an interrupt triggered by the input signal.
Polled regularly with the poll() instruction in a loop.

• Take a debounce time of about 10ms if the frequency comes from a mechanically switch.

• The measurement can be done in milli seconds or micro seconds.

Frequency counter example
Code: [Select]
`#include <Streaming.h>#include <FreqPeriodCounter.h>const byte freqPin = 3;#define debounceTime_ms 10FreqPeriodCounter freqPeriodCounter(freqPin, millis, debounceTime_ms);void setup(void) { Serial.begin(9600); }void loop(void) { freqPeriodCounter.poll();  Serial << freqPeriodCounter.period << endl;}`

Frequency counter library
Code: [Select]
`/* FreqPeriodCounter * Version 25-11-2011 * Copyright (C) 2011  Albert van Dalen http://www.avdweb.nl * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses.               <------------- period ------------>                  pulseWidth                 _____________                      ______________                                   ||             ||                  ||              ||                 ||             ||  pulseWidthLow   ||              || ______________||             ||__________________||              ||______________           periodCount   0                                  1 transientTime ^              ^                   ^               ^ level                1                 0                  1                0       debounceTime  <-->           <-->                <-->            <-->                                                                  <- elapsedTime ->*/          #include "FreqPeriodCounter.h"// debounceTime in msec if msec_usecNot=1 else in usec FreqPeriodCounter::FreqPeriodCounter(byte pin, bool msec_usecNot, unsigned debounceTime):time(0), transientTime(0), elapsedTime(0), pulseWidth(0), pulseWidthLow(0), period(0), periodCount(0), level(0), lastLevel(0), pin(pin), msec_usecNot(msec_usecNot), debounceTime (debounceTime){ }bool FreqPeriodCounter::poll(){ if(msec_usecNot) time = millis();  else time = micros();  elapsedTime = time - transientTime;  level = digitalRead(pin);  if((level != lastLevel) & (elapsedTime > debounceTime))  { lastLevel = level;    transientTime = time;    if(level == HIGH)    { pulseWidthLow = elapsedTime;      period = pulseWidth + pulseWidthLow;      if(periodCount++ > 1)      { periodCount = 0;        return true; // return true if a complete period is measured      }    }    else pulseWidth = elapsedTime;    }  return false;}unsigned int FreqPeriodCounter::hertz(){ if (timeFunctionPtr == micros) return 1000000/period;  else return 1000/period;}`
Code: [Select]
`#ifndef FREQPERIODCOUNTER_H #define FREQPERIODCOUNTER_H/* FreqPeriodCounter * Version 25-11-2011 * Copyright (C) 2011  Albert van Dalen http://www.avdweb.nl * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses. */#include <WProgram.h>class FreqPeriodCounter{    public:  FreqPeriodCounter(byte pin, bool msec_usecNot, unsigned debounceTime);  bool poll();  unsigned long period, pulseWidth, pulseWidthLow, elapsedTime;  bool level;    protected:  unsigned long time, transientTime;  unsigned debounceTime;  byte periodCount, pin;  bool lastLevel, msec_usecNot;  };#endif`

#### robtillaart

#1
##### Nov 25, 2011, 11:27 pm

Thanks for sharing,

What is the range it can measure?
What is its accuracy? (can be improved by counting multiple periods of course)
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

#### avandalen

#2
##### Dec 18, 2011, 08:04 pm
Hi
The lowest time with polling is about 40us -> 25kHz. The longest time is 50 days....

#### L8APXR

#3
##### Jan 16, 2012, 06:06 pm
why is not all of the required code included?

maybe it's just because I'm new, but I frequently find that many "included" libraries that I simply don't have.

"WProgram.h" is referenced but not included in this one, for example, and "streaming.h"

When I search for Streaming.h  I find several, but they then each include some other library that I don't have (LOG.h, or whatever...)

at some point I guess my libraries will include so much random stuff that I'll have better luck with downloaded sketches?

#### avandalen

#4
##### Jan 16, 2012, 07:15 pm
Hi
See for the libraries here:
http://www.avdweb.nl/arduino/troubleshooting.html#h0-1-1-1-frequently-used-libraries

Wprogram.h is included in Arduino by default.

#### robtillaart

#5
##### Jan 16, 2012, 08:08 pm
Quote
The period is measured instead of the frequency; this is done to save program space. The frequency can be calculated with 1/period; however this will include the float library which takes a lot of memory. Thus the frequency calculation is left out of the library code.

One can calculate the frequency also by doing integer math. If one expresses the time in micros then the frequency is:
Code: [Select]
`...period = micros() - start;long freq = 1000000L/period;Serial.print("freq: ");Serial.println(freq);...`

if one wants to add 3 decimals (1 and 2 decimal are similar)
Code: [Select]
`...period = micros() - start;long freq = 10000000000L/period;  // note the extra 000Serial.print("freq: ");Serial.print(freq/1000);Serial.print('.');Serial.print(freq%1000);...`

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

#### PaulS

#6
##### Jan 17, 2012, 12:27 am
Quote
Wprogram.h is included in Arduino by default.

With versions 0023 and earlier, that is. With 1.0, that file was renamed to Arduino.h. The conditional/unconditional inclusion is how you can tell if a library is compatible with 1.0. Conditional is; unconditional is not.

#### L8APXR

#7
##### Jan 17, 2012, 02:26 am

Hi
See for the libraries here:
http://www.avdweb.nl/arduino/troubleshooting.html#h0-1-1-1-frequently-used-libraries

Wprogram.h is included in Arduino by default.

Thanks!

I've been able to get some data logged, and something odd is emerging. with a fairly large sample size (hundreds of data) there seem to be some discrete "favorite" values. Out of 1000 or so measurements, there are only about 8 discrete values, and they reach out to 5 digits behind the decimal point. weird, huh!?

I'm measuring the frequency of the AC electricity, so the measurement is around 60Hz. I have a real time monitor set up on a Digital multimeter, and also have historical data, so I know sort of how the frequency behaves (and it's not by jumping from one discrete value to another). a favorite seems to be 60.024 (about 20% of all values are 60.024HZ , lol).

When plotted in excel it seems to have a distinct upper and lower bound (say 59.953 to 60.0421), and in between it leaps around almost at random

is there something I can adjust to make it more granular of a measurement?

#### robtillaart

#8
##### Jan 18, 2012, 07:54 pm
Quote
and something odd is emerging.

pictures?
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

#### L8APXR

#9
##### Jan 18, 2012, 09:45 pm
not sure how to post a graph...

here's a small excerpt of the data. In its repetitiveness of the smae values over and over it is very representative of the whole dataset.

 59.995260.009660.009660.02460.009660.02459.995260.02459.980860.009659.995260.02460.009659.937759.966460.052860.009659.923360.009659.995259.995259.995259.980859.995259.995260.009659.995260.02460.009660.02459.995259.995259.980859.95260.009660.009660.009660.009659.995259.980860.009659.980859.95259.980859.937759.995260.02460.009660.02460.009660.009659.966460.009659.95259.995260.009659.995260.009659.995259.995260.009659.937760.02460.009659.980859.995260.02460.02460.009659.995260.02460.02460.02460.02460.009660.009660.02459.966459.95259.980859.937760.02460.02460.02459.95259.95260.02460.009659.95259.95259.995259.995260.009660.009660.009660.02460.009660.02460.009660.009660.009659.937759.966459.966460.009659.980859.995260.009659.995259.995259.995259.937760.009659.995260.02459.980859.966459.995260.009660.009659.995259.980859.980860.009660.02460.009659.980859.966460.009660.067359.95259.95260.02460.009659.995259.995260.009660.02460.009660.009660.009660.02460.009660.02460.02460.02459.95260.02459.995259.995260.02459.995259.966459.995259.980860.009659.995260.009660.009659.995259.980860.02460.009660.009659.966459.966459.980859.937760.009660.02460.02460.038459.995259.995260.009660.009659.980860.02459.966459.995259.995260.009660.02460.02460.02459.980859.95259.966459.937760.009659.966460.02460.009659.980859.966459.966459.966459.966459.995260.009660.02460.02459.95259.995260.02460.02459.995260.02460.009659.995260.02459.980860.02459.966459.980859.95259.966459.95259.995260.009659.937759.95259.966459.937760.009660.02459.966459.95259.995260.02459.937760.02460.02460.02459.980859.95259.980859.966459.95259.966459.966459.980860.009659.995260.009659.966459.980859.995260.009659.966459.95260.009660.02459.966459.95259.995260.009659.995259.95260.038459.95259.937760.009660.009659.966460.02459.995259.995260.009660.02459.966459.95259.937759.995260.009660.02460.009659.980859.995260.009660.02459.995259.995260.009659.966459.937759.95260.009660.02459.966460.009660.009660.009659.966460.009659.966459.966459.937759.95259.95259.966459.937760.009660.02459.980859.966459.995260.02459.95259.95260.009660.009660.009660.009659.995260.009660.02460.02460.009660.024

#### avandalen

#10
##### Jan 19, 2012, 01:25 pm

Quote
The period is measured instead of the frequency; this is done to save program space. The frequency can be calculated with 1/period; however this will include the float library which takes a lot of memory. Thus the frequency calculation is left out of the library code.

One can calculate the frequency also by doing integer math. If one expresses the time in micros then the frequency is:
Code: [Select]
`...period = micros() - start;long freq = 1000000L/period;Serial.print("freq: ");Serial.println(freq);...`

if one wants to add 3 decimals (1 and 2 decimal are similar)
Code: [Select]
`...period = micros() - start;long freq = 10000000000L/period;  // note the extra 000Serial.print("freq: ");Serial.print(freq/1000);Serial.print('.');Serial.print(freq%1000);...`

Hi Rob,

I thanks! I have added a function hertz() now, see also changed the website:
http://www.avdweb.nl/arduino/hardware-interfacing/frequency-period-counter

Code: [Select]
`int FreqPeriodCounter::hertz(){ if (timeFunctionPtr == micros) return 1000000/period;  else return 1000/period;}`

#### avandalen

#11
##### Jan 19, 2012, 02:14 pmLast Edit: Jan 19, 2012, 04:38 pm by avandalen Reason: 1
Quote

I'm measuring the frequency of the AC electricity, so the measurement is around 60Hz. I have a real time monitor set up on a Digital multimeter, and also have historical data, so I know sort of how the frequency behaves (and it's not by jumping from one discrete value to another). a favorite seems to be 60.024 (about 20% of all values are 60.024HZ , lol).
When plotted in excel it seems to have a distinct upper and lower bound (say 59.953 to 60.0421), and in between it leaps around almost at random
is there something I can adjust to make it more granular of a measurement?

That's not really nice, I want the library improve further if possible.

1. Printing is not allowed during the measurement. Maybe you can store the data in an array (memory of the Arduino), and later print it out?
2. If you have used polling, try interrupt operation instead of polling.

#### robtillaart

#12
##### Jan 22, 2012, 12:22 pm
Quote
here's a small excerpt of the data. In its repetitiveness of the smae values over and over it is very representative of the whole dataset.

Repeating output values are probably caused by the fact that you are reaching the limits of the accuracy.

Test:

Copy the numbers to a speadsheet in colum A
Sort that colum from low - high
Make colum B :   "=A2-A1"  extended for the whole colum A
There will appear 2 distinct values : 0  and 0,0144 (+- 0,0001)
which means the resolution the (current) algorithm produces is 0,0144, so printing with more than 2 decimals makes no sense

If you want more decimals you need to do a numerical analysis of the algorithm (and hardware sample freq/timinig/adc precision etc)).

Hope this helps,
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

#### L8APXR

#13
##### Jan 26, 2012, 03:05 am

That's not really nice, I want the library improve further if possible.

1. Printing is not allowed during the measurement. Maybe you can store the data in an array (memory of the Arduino), and later print it out?
2. If you have used polling, try interrupt operation instead of polling.

I think something may be getting lost in between languages or something. I really did not mean to be unkind or "not nice" in any way.

I think I am simply not smart enough to use the interrupt operation. I keep getting error messages when trying to compile, but I am using an Arduino Mega 2560, so maybe it wasn't written for that platform. Or, it could just be that I am really new to all this and just haven't learned enough yet.

#### nitrolx

#14
##### Feb 05, 2012, 02:54 am
Hi,
is there any way with this library to get Hertz in a decimal?
I need accuracy up to about 850Hz, to calculate engine RPM.
Having hertz only as a whole number is reducing the accuracy.

Thanks!

Go Up

Please enter a valid email to subscribe