diff options
Diffstat (limited to 'table-fan/fan.c')
-rw-r--r-- | table-fan/fan.c | 45 |
1 files changed, 29 insertions, 16 deletions
diff --git a/table-fan/fan.c b/table-fan/fan.c index daa33f4..a843924 100644 --- a/table-fan/fan.c +++ b/table-fan/fan.c @@ -54,6 +54,35 @@ void fan_init(void) TCCR4B = (1<<CS41); // start timer } +#define TACHO_DATA_LEN 8 +static uint16_t tacho_data[TACHO_DATA_LEN]; +static uint8_t tacho_data_idx = 0; +static uint16_t tacho_last_ts = 0; + +ISR(TIMER1_CAPT_vect) +{ + uint16_t current = ICR1; + if(current > tacho_last_ts) { + tacho_data[tacho_data_idx] = current - tacho_last_ts; + } else { + tacho_data[tacho_data_idx] = (UINT16_MAX - tacho_last_ts) + current; + } + tacho_last_ts = current; + tacho_data_idx = (tacho_data_idx >= (TACHO_DATA_LEN-1)) ? 0 : tacho_data_idx+1; +} + +uint16_t fan_get_rpm(void) +{ + uint32_t sum = 0; + cli(); + for(uint8_t i = 0; i < TACHO_DATA_LEN; i++) { + sum += tacho_data[i]; + } + sei(); + + return (1875000 / (sum / TACHO_DATA_LEN)); +} + void fan_speed_set(uint8_t val) { OCR4B = (val > PWM_VAL_MAX) ? PWM_VAL_MAX : val; @@ -75,19 +104,3 @@ void fan_speed_dec(void) if(OCR4B > 0) OCR4B--; } - -ISR(TIMER1_CAPT_vect) -{ - static uint16_t tacho_last_ts = 0; - uint16_t current = ICR1; - uint16_t diff = 0; - if(current > tacho_last_ts) { - diff = current - tacho_last_ts; - } else { - diff = (UINT16_MAX - tacho_last_ts) + current; - } - tacho_last_ts = current; - - uint16_t rpm = 1875000 / diff; - printf("\rspeed: %6d rpm", rpm); -} |