Looking for guidance in frequency measurement

Here is a slight update to my example, the update determines when the frequency is null using a timeout, otherwise it keeps the last frequency count even when the signal is terminated. It also prevents the function from thinking (for a short period of time) that the signal state is one during a reset.

The below code will output a frequency of ~200hz, from pin 8 to pin 49 on an Arduino Mega. You'll need to install FreqMeasure by Paul Stoffregen in your sketch library as well.



#include <FreqMeasure.h>


double sum=0;
int count=0;
unsigned long currentTime;
unsigned long lastSerialPrintTime;
unsigned long lastFreqUpdateTime;
unsigned long pinLowTime;
unsigned long pinHighTime;
int lastFreqUpdateTimeOut = 2000;
bool engineRunning = false;
float frequency = 0;

void setup()
{
    Serial.begin(9600);
    FreqMeasure.begin();
    while (!Serial)
    {
      ; // Wait for serial to connect
    }
    Serial.println("");
    delay(2000);
   
    Serial.println("Frequency Demo");

    pinMode(8, OUTPUT);
    digitalWrite(8, LOW);
    pinHighTime = (millis() + 1);

    lastSerialPrintTime = millis();
    lastFreqUpdateTime = millis();
    frequency = 0;
}

void loop()
{
    currentTime = millis();

    int pinState = digitalRead(8);
    if ((currentTime >= pinHighTime) && (pinState == 0))
    {
        digitalWrite(8, HIGH);    
        pinLowTime = (currentTime + 4);
    }
    
    if ((currentTime >= pinLowTime) && (pinState == 1))
    {
        digitalWrite(8, LOW);
        pinHighTime = (currentTime + 1);
    }

    if (FreqMeasure.available()) 
    {
        sum = sum + FreqMeasure.read();
        count = count + 1;
        if (count > 100) 
        {
            frequency = FreqMeasure.countToFrequency(sum / count);
            //Serial.println(frequency);
            sum = 0;
            count = 0;
            //lastFreqUpdateTime = millis();
            lastFreqUpdateTime = (millis() + lastFreqUpdateTimeOut);
        }
    }

    if ((currentTime - lastSerialPrintTime) > 500)
    {
        //if (((currentTime - lastFreqUpdateTime) > lastFreqUpdateTimeOut) || (frequency < 10))
        if ((currentTime > lastFreqUpdateTime) || (frequency < 10))
        {
            Serial.println("Engine is off");
            engineRunning = false;
            frequency = 0;
        }
        else
        {
            Serial.print("Engine is running, hz is: "); Serial.println(frequency);
            engineRunning = true;
        }

        lastSerialPrintTime = millis();
    }
}


1 Like