/*  Program to measure the frequenncy of a input, on digital pin 8
 *  Made by Oyvind Skaaden
 */
#include <FreqMeasure.h>  // Library for measure
#define out 4             // The pin the transistor is controlled by

float rpm = 40000;        // The limit for when to open the transistor
bool ledUnderRPM = true;  // Change this to light the LED should light when the rpm are over rpm
float freq = rpm / 60;

void setup() {
  Serial.begin(57600);
  FreqMeasure.begin();
}

double sum=0;
int count=0;

void loop() {
  if (FreqMeasure.available()) {
    // average several reading together
    sum = sum + FreqMeasure.read();
    count = count + 1;
    if (count > 30) {
      float frequency = FreqMeasure.countToFrequency(sum / count);
      Serial.print(frequency);
      if (frequency < freq) { // If the measured frequency is below the RPM do this
        digitalWrite(out, ledUnderRPM);
        Serial.println(" ON");
      }
      else{
        digitalWrite(out, !ledUnderRPM);
        Serial.println(" OFF");
      }
      sum = 0;
      count = 0;
    }
  }
}
