58 lines
1.3 KiB
C
58 lines
1.3 KiB
C
#include "FanControl.h"
|
|
|
|
#include "TMP144.h"
|
|
#include "main.h"
|
|
|
|
#include "stm32f4xx_hal_def.h"
|
|
#include "stm32f4xx_hal_tim.h"
|
|
|
|
#include <stdint.h>
|
|
|
|
TIM_HandleTypeDef* timer;
|
|
uint32_t channel;
|
|
FanState fan_state;
|
|
|
|
HAL_StatusTypeDef fan_ctrl_init(TIM_HandleTypeDef* handle, uint32_t channel_) {
|
|
timer = handle;
|
|
channel = channel_;
|
|
fan_state = FANS_OFF;
|
|
|
|
return HAL_TIM_PWM_Start(timer, channel);
|
|
}
|
|
|
|
void fan_ctrl_update() {
|
|
if (fan_state == FANS_OFF && max_temperature > THRESH_FANS_ON_HALF) {
|
|
fan_state = FANS_ON;
|
|
} else if (fan_state == FANS_ON && max_temperature < THRESH_FANS_OFF) {
|
|
fan_state = FANS_OFF;
|
|
}
|
|
|
|
uint32_t power;
|
|
if (fan_state == FANS_OFF) {
|
|
power = 0;
|
|
} else {
|
|
if (max_temperature < THRESH_FANS_ON_HALF) {
|
|
power = 50;
|
|
} else if (max_temperature > THRESH_FANS_ON_FULL) {
|
|
power = 100;
|
|
} else {
|
|
power = (100 * (max_temperature - THRESH_FANS_ON_HALF)) /
|
|
(THRESH_FANS_ON_FULL - THRESH_FANS_ON_HALF);
|
|
}
|
|
}
|
|
fan_ctrl_set_power(power);
|
|
}
|
|
|
|
void fan_ctrl_set_power(uint32_t percent) {
|
|
if (percent > 100) {
|
|
percent = 100;
|
|
}
|
|
|
|
// The PWM signal switches a low side switch, so we need to invert the duty
|
|
// cycle.
|
|
percent = 100 - percent;
|
|
|
|
uint32_t counter = timer->Init.Period * percent / 100;
|
|
__HAL_TIM_SET_COMPARE(timer, channel, counter);
|
|
}
|