weatherstation/firmware/sensor_wind.ino

114 lines
2.5 KiB
Arduino
Raw Normal View History

#include "config_user.h"
#include "config.h"
2023-04-03 18:10:46 +02:00
#define WIND_DEFAULT_MEAS_INIT 255
2022-11-24 19:17:21 +01:00
volatile unsigned int anemometerRotations = 0;
2023-04-04 10:00:11 +02:00
volatile uint32_t start_meas_wind_time = 0;
int interruptNumber;
#ifndef SENSOR_WIND_NO_ISR
2022-11-24 19:17:21 +01:00
void ICACHE_RAM_ATTR _anemometerInterrupt()
{
2023-04-04 10:00:11 +02:00
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("*");
2022-11-24 19:17:21 +01:00
debug("*");
#endif
}
2023-04-04 10:00:11 +02:00
#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
2023-04-04 10:00:11 +02:00
start_meas_wind_time = millis();
interruptNumber = digitalPinToInterrupt(ANEMOMETER_PIN);
2022-11-24 19:17:21 +01:00
attachInterrupt(interruptNumber, _anemometerInterrupt, FALLING);
#endif
}
boolean check_measure_wind_done()
{
2023-04-03 18:10:46 +02:00
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);
2023-04-03 18:10:46 +02:00
return true;
2023-04-03 18:10:46 +02:00
}
#endif
#ifdef SENSOR_WIND_NO_ISR
2023-04-03 18:10:46 +02:00
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);
2023-04-04 12:51:24 +02:00
if (previous_pin_state != tmp_pin_state && tmp_pin_state == 0 && previous_pin_state != WIND_DEFAULT_MEAS_INIT)
{
2023-04-04 12:51:24 +02:00
// only count rotations on falling edges
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());
2023-04-03 18:10:46 +02:00
meas_time_done += WIND_SPEED_MEAS_NO_ISR_TIME_MS;
}
2023-04-03 18:10:46 +02:00
#endif // SENSOR_WIND_NO_ISR
return false;
}
float measure_wind_result()
{
start_meas_wind_time = 0;
2022-11-24 19:17:21 +01:00
#ifdef DEBUG
debug("rotations = " + String((float)anemometerRotations));
#endif
return (float)anemometerRotations * WINDSPEED_FACTOR;
}