// 20180120 - no FREQ output D5
// FREQ to servo tested perfect, even CHOKE inverted
// 20180125 - added LED : off when reaches 50Hz
#include <LiquidCrystal595.h>
#include <Servo.h>
Servo myservo;
const int ledPin = 13 ;
int potpin = 0; // analog pin A0 for pot, not used now
int val;
LiquidCrystal595 lcd (7, 8, 6);
long wait = 400 ;
float FREQ = 0 ;
#define MainPeriod 300 // was 1000
long previousMillis = 0 ;
volatile unsigned long duration = 0 ;
volatile unsigned int pulsecount = 0 ;
volatile unsigned long previousMicros = 0 ;
void setup() {
pinMode (ledPin, OUTPUT) ;
myservo.attach (10); // connects the servo to pin 10
lcd.begin (20, 4);
attachInterrupt (0, myinthandler, RISING) ; // input D3
}
void loop() {
val = map (FREQ, 2, 50, 180, 0); // scale it to use it with the servo (value between 0 and 180)
myservo.write (val); // sets the servo position according to the scaled value
delay (5); // waits for the servo to get there
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= MainPeriod)
{
previousMillis = currentMillis;
unsigned long Aduration = duration;
unsigned long Apulsecount = pulsecount;
duration = 0;
pulsecount = 0;
float Freq = 1e6 / float(Aduration);
Freq *= Apulsecount;
FREQ = Freq ;
if (isnan (FREQ))
FREQ = 0 ; // to remove "nan" when near 0
lcd.setCursor (2, 0) ;
lcd.print (Freq) ; // for testing only - shows "nan"
lcd.setCursor (2, 1) ;
lcd.print (FREQ) ;
lcd.setCursor (2, 2);
if (FREQ >= 50)
digitalWrite (ledPin, LOW);
else
digitalWrite (ledPin, HIGH);
}
}
void myinthandler()
{
unsigned long currentMicros = micros();
duration += currentMicros - previousMicros;
previousMicros = currentMicros;
pulsecount++;
}