weatherstation/firmware/sensor_wind.ino
2023-04-04 10:00:11 +02:00

112 lines
2.5 KiB
C++

#include "config_user.h"
#include "config.h"
#define WIND_DEFAULT_MEAS_INIT 255
volatile unsigned int anemometerRotations = 0;
volatile uint32_t start_meas_wind_time = 0;
int interruptNumber;
#ifndef SENSOR_WIND_NO_ISR
void ICACHE_RAM_ATTR _anemometerInterrupt()
{
if ((start_meas_wind_time + (WIND_SENSOR_MEAS_TIME_S * 1000)) <= millis())
{
// measurement already done, prevent read of further rotations
return;
}
anemometerRotations++;
#ifdef DEBUG
Serial.print("*");
debug("*");
#endif
}
#endif // end of if not defined SENSOR_WIND_NO_ISR
float wind_speed()
{
start_measure_wind();
do {
delay(1000); // minimum delay of measurement time is 1 second
} while (check_measure_wind_done() == false);
return measure_wind_result();
}
void start_measure_wind()
{
anemometerRotations = 0;
#ifndef SENSOR_WIND_NO_ISR
start_meas_wind_time = millis();
interruptNumber = digitalPinToInterrupt(ANEMOMETER_PIN);
attachInterrupt(interruptNumber, _anemometerInterrupt, FALLING);
#endif
}
boolean check_measure_wind_done()
{
static uint8_t previous_pin_state = WIND_DEFAULT_MEAS_INIT;
static uint8_t tmp_pin_state = WIND_DEFAULT_MEAS_INIT;
static uint32_t meas_time_done = 0;
#ifndef SENSOR_WIND_NO_ISR
// interrupt routine based measurement
if ((start_meas_wind_time + (WIND_SENSOR_MEAS_TIME_S * 1000)) <= millis())
{
detachInterrupt(interruptNumber);
return true;
}
#endif
#ifdef SENSOR_WIND_NO_ISR
if (meas_time_done >= (WIND_SENSOR_MEAS_TIME_S * 1000))
{
meas_time_done = 0;
previous_pin_state = WIND_DEFAULT_MEAS_INIT;
return true;
} else {
// measure wind without ISR
uint32_t start = millis();
do {
// read pin state
previous_pin_state = tmp_pin_state;
tmp_pin_state = digitalRead(ANEMOMETER_PIN);
if (previous_pin_state != tmp_pin_state && previous_pin_state != WIND_DEFAULT_MEAS_INIT)
{
anemometerRotations++;
#ifdef DEBUG
Serial.print("*");
debug("*");
#endif
}
// wait 5 ms
delay(5);
#ifdef ENABLE_WATCHDOG
// feed the watchdog to prevent reset
WDT_FEED();
#endif
} while ((start + WIND_SPEED_MEAS_NO_ISR_TIME_MS) >= millis());
meas_time_done += WIND_SPEED_MEAS_NO_ISR_TIME_MS;
}
#endif // SENSOR_WIND_NO_ISR
return false;
}
float measure_wind_result()
{
start_meas_wind_time = 0;
#ifdef DEBUG
debug("rotations = " + String((float)anemometerRotations));
#endif
return (float)anemometerRotations * WINDSPEED_FACTOR;
}