From 094e61a7c189d2fde0d63cc02ca051c29692b438 Mon Sep 17 00:00:00 2001 From: BlackMark Date: Mon, 30 Mar 2020 19:38:24 +0200 Subject: [PATCH] Add fan control according to temperature --- thermistor/main.cpp | 26 +++++++++++++++++++++++++- thermistor/pwm.cpp | 25 +++++++++++++++++++++++++ thermistor/pwm.hpp | 10 ++++++++++ thermistor/thermistor.cppproj | 6 ++++++ 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 thermistor/pwm.cpp create mode 100644 thermistor/pwm.hpp diff --git a/thermistor/main.cpp b/thermistor/main.cpp index 0d9dcc4..f1cd990 100644 --- a/thermistor/main.cpp +++ b/thermistor/main.cpp @@ -12,11 +12,28 @@ #define UART0_INT_VECTORS #include "uart/hardware0.hpp" +#include "pwm.hpp" #include "thermistor.hpp" +template +T clamp(double value, T lower, T upper) +{ + if (value < lower) + return lower; + if (value > upper) + return upper; + return static_cast(value); +} + +uint8_t temperatureCurve(double temperature) +{ + double fanSpeed = (10 * temperature - 200) / 3; + return clamp(fanSpeed, 0, 100); +} + int main() { - uart::Uart0<> serial; + uart::Uart0> serial; serial.init(); serial << F("Thermistor reader\r\n"); @@ -28,10 +45,14 @@ int main() Thermistor temp; + pwm::init(); + pwm::setDuty(100); + while (true) { const auto adcSample = temp.sampleAdc(adcPin, 1000); const auto thermistorResistance = temp.getResistance(adcSample); const auto temperature = temp.getTemperature(thermistorResistance); + const auto fanSpeed = temperatureCurve(temperature); char floatBuffer[16]; @@ -41,6 +62,9 @@ int main() serial << F("Resistance: ") << floatBuffer << F("\r\n"); sprintf(floatBuffer, "%.2f", temperature); serial << F("Temperature: ") << floatBuffer << F(" C \r\n"); + serial << F("Fan speed: ") << fanSpeed << F("%\r\n"); + + pwm::setDuty(fanSpeed); _delay_ms(1000); } diff --git a/thermistor/pwm.cpp b/thermistor/pwm.cpp new file mode 100644 index 0000000..57d1233 --- /dev/null +++ b/thermistor/pwm.cpp @@ -0,0 +1,25 @@ +#include "pwm.hpp" + +#include "io/io.hpp" + +namespace pwm { + +static constexpr uint8_t PWM_TOP = 40; + +void init() +{ + io::Pin pwmPin; + pwmPin.dir(io::Dir::OUT); + pwmPin = false; + + TCCR0A = (1 << COM0B1) | (1 << WGM00); + TCCR0B = (1 << WGM02) | (1 << CS01); + OCR0A = PWM_TOP; +} + +void setDuty(uint8_t percent) +{ + OCR0B = (percent * PWM_TOP) / 100; +} + +} // namespace pwm diff --git a/thermistor/pwm.hpp b/thermistor/pwm.hpp new file mode 100644 index 0000000..964ebb1 --- /dev/null +++ b/thermistor/pwm.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace pwm { + +void init(); +void setDuty(uint8_t percent); + +} // namespace pwm diff --git a/thermistor/thermistor.cppproj b/thermistor/thermistor.cppproj index ebaf5c9..bce292a 100644 --- a/thermistor/thermistor.cppproj +++ b/thermistor/thermistor.cppproj @@ -212,6 +212,12 @@ compile + + compile + + + compile + compile