-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfireplace-fan-pwm.ino
89 lines (75 loc) · 2.2 KB
/
fireplace-fan-pwm.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <AutoPID.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// General Settings
#define DEBUG true
// Pinout Settings
#define TEMP_READ_DELAY 1000 // OneWire can only read every ~750ms
#define ONE_WIRE_BUS 12 // DS18B20 Pin
#define PWM_OUTPUT_PIN 14 // PWM Output Pin
// PID Controller Settings
#define DESIRED_TEMP 44
#define OUTPUT_MIN 280
#define OUTPUT_MAX 800
#define KP -60
#define KI -0.7
#define KD -0
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature temperatureSensors(&oneWire);
unsigned long lastTempUpdate;
double temperature, pwmPower, setPoint;
bool fanStarted = false;
AutoPID myPID(&temperature, &setPoint, &pwmPower, OUTPUT_MIN, OUTPUT_MAX, KP, KI, KD);
bool updateTemperature() {
if ((millis() - lastTempUpdate) > TEMP_READ_DELAY) {
temperature = temperatureSensors.getTempCByIndex(0);
lastTempUpdate = millis();
temperatureSensors.requestTemperatures();
return true;
}
return false;
}
void setup() {
pinMode(PWM_OUTPUT_PIN, OUTPUT);
setPoint = DESIRED_TEMP;
temperatureSensors.begin();
temperatureSensors.requestTemperatures();
while (!updateTemperature()) {}
myPID.setTimeStep(4000);
Serial.begin(115200);
}
void loop() {
if (updateTemperature()) {
if (DEBUG) {
Serial.print("Temperature: ");
Serial.println(temperature);
Serial.print("setPoint: ");
Serial.println(setPoint);
Serial.print("Status: ");
Serial.println(fanStarted);
}
if (fanStarted || temperature > DESIRED_TEMP) {
startFanIfNeeded();
if (DEBUG) {
Serial.print("PWM Output: ");
Serial.println(pwmPower);
}
analogWrite(PWM_OUTPUT_PIN, pwmPower);
}
// Stop the PWM if temperature is 10ºC below the setpoint value
if (temperature < DESIRED_TEMP - 10) {
analogWrite(PWM_OUTPUT_PIN, 0);
fanStarted = false;
}
}
myPID.run();
}
// Start the PWM at max power during a short period of time, avoiding damages for
// motor overheating. PWM is not the right way for regulate a motor speed. But it's cheap.
void startFanIfNeeded() {
if (!fanStarted) {
fanStarted = true;
analogWrite(PWM_OUTPUT_PIN, OUTPUT_MAX);
delay(3000);
}
}