I’m writing an app to record data from an anemometer and am getting some strange behavior. For some reason whenever the input signal gets low enough in pulse width to generate a MPH of 0.0, the “peak” value is set to zero! this makes so sense. :-[
Code:
/*
*
* Windspeed measurement sketch using NRG 40C anemometer whose signal has been
* massaged into a TTL square wave.
*
* Coded by: Joseph Lane. 06/30/2010
*/
#include <EEPROM.h>
// takes an address and a generic type and writes to eeprom
template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
const byte* p = (const byte*)(const void*)&value;
int i;
for (i = 0; i < sizeof(value); i++)
EEPROM.write(ee++, *p++);
return i;
}
template <class T> int EEPROM_readAnything(int ee, T& value)
{
byte* p = (byte*)(void*)&value;
int i;
for (i = 0; i < sizeof(value); i++)
*p++ = EEPROM.read(ee++);
return i;
}
double sensorOne, peak = 0.0;
const int PEAKADDY = 0;
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
pinMode(2, INPUT); // digital sensor is on digital pin 2
// EEPROM_readAnything(PEAKADDY, peak); // Get stored highest
}
void loop()
{
sensorOne = pulseIn(2, LOW); // LOW because square wave signal is inverted
sensorOne = 1 / ((sensorOne / 1000000) * 2); // half period to hz
sensorOne = (sensorOne * 1.711) + 0.78; // hz to mph
if (sensorOne > peak) {
peak = sensorOne;
// EEPROM_writeAnything(PEAKADDY, peak); // write new peak to eeprom
Serial.println("NEW PEAK!");
}
// send sensor values:
Serial.print("MPH: ");
Serial.print(sensorOne);
Serial.print(" PEAK:");
Serial.println(peak);
//delay(1000); // pause 1 second
}
Output:
NEW PEAK!
MPH: 2.54 PEAK:2.54
NEW PEAK!
MPH: 2.60 PEAK:2.60
NEW PEAK!
MPH: 2.69 PEAK:2.69
NEW PEAK!
MPH: 3.00 PEAK:3.00
MPH: 2.88 PEAK:3.00
NEW PEAK!
MPH: 3.03 PEAK:3.03
NEW PEAK!
MPH: 3.42 PEAK:3.42
NEW PEAK!
MPH: 3.68 PEAK:3.68
NEW PEAK!
MPH: 4.15 PEAK:4.15
NEW PEAK!
MPH: 4.48 PEAK:4.48
NEW PEAK!
MPH: 4.87 PEAK:4.87
NEW PEAK!
MPH: 5.27 PEAK:5.27
MPH: 4.87 PEAK:5.27
MPH: 4.80 PEAK:5.27
MPH: 4.17 PEAK:5.27
MPH: 4.00 PEAK:5.27
MPH: 3.55 PEAK:5.27
MPH: 3.46 PEAK:5.27
MPH: 3.04 PEAK:5.27
MPH: 2.72 PEAK:5.27
NEW PEAK!
MPH: 0.00 PEAK:0.00
MPH: 2.09 PEAK:0.00
MPH: 0.00 PEAK:0.00
MPH: 2.38 PEAK:0.00
MPH: 2.40 PEAK:0.00
MPH: 0.00 PEAK:0.00
MPH: 2.42 PEAK:0.00