I use a custom board but anemometers generally work the same, though your constants may vary.
I use an external pull-up, 4.7K, to 5V. The anemometer signal connects between GND and the GPIO pin. The reason for the external pull-up is to give a stronger pull, and also adds the ability to make it swing 5V instead of 3.3V, which make the signal more noise tolerant.
In setup I attach the interrupt:
attachInterrupt(ANEMOMETER_PIN, anemometerInterrupt, FALLING);
The interrupt is handled like this:
void anemometerInterrupt() {
if (millis() - lastAnemometerTime >= DEBOUNCE_TIME_MS) {
lastAnemometerTime = millis();
anemometerCount++;
}
}
As ScruffR pointed out, sticking a delay in the ISR is not the correct solution. Instead, you should measure the time of the last pulse use that to debounce the signal. In my case, DEBOUNCE_TIME_MS, is 10.
In loop, I aggregate the wind clicks every second:
if (millis() - lastAnemometerAggregationTime >= 1000) {
lastAnemometerAggregationTime = millis();
// Process anemometer data once per second
// Anemometer (D5)
// One contact closure (falling) = 1.492 MPH (2.4 kh/h) of wind speed
//Log.info("anemometerCount=%d vaneRaw=%.1f", anemometerCount, 22.5 * (float)adcToDirectionIndex(analogRead(VANE_PIN)));
if (anemometerCount > 0) {
float speed = 1.492 * (float) anemometerCount;
anemometerCount = 0;
if (speed > windGust) {
windGust = speed;
}
windSum += speed;
windCount++;
}
}
Then I send the 1 second aggregated samples up every 6 seconds:
if (millis() - lastWeatherPublishTime >= PUBLISH_TIME_MS) {
lastWeatherPublishTime = millis();
char buf[128];
if (windCount > 0) {
snprintf(buf, sizeof(buf), "{\"weatherWind\":%.1f,\"weatherGust\":%.1f}",
(windSum / (float)windCount), windGust);
localEventQueue.publish("environment", buf);
windGust = 0.0;
windSum = 0.0;
windCount = 0;
windWasNonZero = true;
}
else
if (windWasNonZero && windCount == 0) {
// Was non-zero, but now it's zero
snprintf(buf, sizeof(buf), "{\"weatherWind\":%.1f,\"weatherGust\":%.1f}",
0.0, 0.0);
localEventQueue.publish("environment", buf);
windWasNonZero = false;
}