-
Notifications
You must be signed in to change notification settings - Fork 1
/
arduino-pid-rotary-encoder.ino
428 lines (355 loc) · 10.6 KB
/
arduino-pid-rotary-encoder.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2018 Alec B. Plumb
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <max6675.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <PID_v1.h>
#include <EEPROM.h>
#define LCD_ADDR 0x27
LiquidCrystal_I2C lcd(LCD_ADDR, 16, 2);
MAX6675 thermocouple(11, 10, 9); // CLK, CS, D0
MAX6675 thermocouple2(7, 6, 5); // CLK, CS, D0
#define RELAY_PIN 12
#define DEGREE_CHAR 0
byte degreeChar[8] = {
0b01100,
0b10010,
0b10010,
0b01100,
0b00000,
0b00000,
0b00000,
0b00000
};
#define UP_CHAR 1
byte upChar[8] = {
0b00100,
0b01110,
0b10101,
0b00100,
0b00100,
0b00100,
0b00100,
0b00100
};
#define DEFAULT_SET_POINT_C 371.111 // 700°F
#define MIN_SET_POINT_C 0.0 // °C
#define MAX_SET_POINT_C 537.222 // 999°F
#define BANG_ON_C 27.77777 // 50°F Turn relay fully on if PV is more than this below the setpoint
#define BANG_OFF_C 13.88888 // 25°F Turn relay fully off if PV is more than this above the setpoint
//////////////////////////////
// PID
//////////////////////////////
double inputTempC; // °C
double input2TempC; // °C
double setPointTempC = -1.0; // °C
double pidOutput;
// These tunings are almost entirely arbitrary, and should be tuned.
#define KP 850
#define KI .5
#define KD .1
//Specify the links and initial tuning parameters
PID myPID(&inputTempC, &pidOutput, &setPointTempC, KP, KI, KD, P_ON_E, DIRECT);
char degreesBuff[5];
int tempReadInterval = 500;
int lastTempReadTime = 0;
//////////////////////////////
// Relay Window
//////////////////////////////
int WindowSize = 5000;
unsigned long windowStartTime;
bool oldRelayEnabled = true; // we will initialize to false in setup, triggering a change
//////////////////////////////
// Settings
//////////////////////////////
struct Settings {
byte checkVal;
double setPointC;
boolean displayCelsius;
};
#define SETTINGS_WRITE_INTERVAL 10000
#define CHECK_VAL 0x69
Settings settings;
boolean displayCelsius = false;
long lastSettingsWrite;
//////////////////////////////
// Rotary Encoder
//////////////////////////////
#define ENCODER_A_PIN 2
#define ENCODER_B_PIN 3
#define ENCODER_READ_INTERVAL 250
volatile int encoderPos = 0;
int oldEncoderPos = 0;
long lastEncoderRead;
boolean encoderWasFast = false;
//////////////////////////////
// Toggle Button
//////////////////////////////
#define TOGGLE_BUTTON_PIN 4
#define TOGGLE_DEBOUNCE 200
// Note that the toggle is wired backwards, so the toggle logic is inverted
bool toggleState = false;
int togglePrevious = HIGH;
long lastToggleTime = 0;
void setup() {
// Setup Serial output
Serial.begin(9600);
setupSettings();
setupEncoder();
setupToggle();
// Setup Relay
pinMode(RELAY_PIN, OUTPUT);
setRelay(false);
// Setup PID
windowStartTime = millis();
//tell the PID to range between 0 and the full window size
myPID.SetOutputLimits(0, WindowSize);
//turn the PID on
myPID.SetMode(AUTOMATIC);
// Setup LCD
lcd.init();
lcd.backlight();
lcd.createChar(DEGREE_CHAR, degreeChar);
lcd.createChar(UP_CHAR, upChar);
lcd.setCursor(0, 0);
lcd.print("S:");
lcd.setCursor(8, 0);
lcd.print("P:");
lcd.setCursor(7, 1);
lcd.print("P2:");
}
void loop() {
readEncoder();
updateToggleState();
updateSettings();
// Show setpoint temp
lcd.setCursor(2, 0);
printDegrees(setPointTempC);
updateTemp();
lcd.setCursor(10, 0); // probe 1 temp
printDegrees(inputTempC);
lcd.setCursor(10, 1); // probe 2 temp
printDegrees(input2TempC);
if ( isnan(inputTempC) ) {
// No probe is connected, there is nothing to do.
myPID.SetMode(MANUAL);
pidOutput = 0;
} else {
// Show current temp
lcd.setCursor(10, 0);
printDegrees(inputTempC);
// if we are more than BANG_ON degrees below the setpoint, then always turn on the relay.
if ( inputTempC + BANG_ON_C < setPointTempC ) {
myPID.SetMode(MANUAL);
pidOutput = WindowSize;
}
// if we are more than BANG_OFF degrees above the setpoint, then always turn off
else if ( inputTempC - BANG_OFF_C > setPointTempC ) {
myPID.SetMode(MANUAL);
pidOutput = 0;
}
else {
myPID.SetMode(AUTOMATIC);
}
}
myPID.Compute();
// Show Output
lcd.setCursor(0, 1);
sprintf(degreesBuff, "%4d", (int)pidOutput);
lcd.print(degreesBuff);
// if we are inside the BANG range, turn on the relay for a portion of the Relay Window
// based on the pidOutput
unsigned long now = millis();
if (now - windowStartTime > WindowSize) { //time to shift the Relay Window
windowStartTime += WindowSize;
}
setRelay(pidOutput > now - windowStartTime);
}
////////////////////////////////
// Rotary Encoder
////////////////////////////////
void setupEncoder() {
pinMode(ENCODER_A_PIN, INPUT);
pinMode(ENCODER_B_PIN, INPUT);
//digitalWrite(ENCODER_A_PIN, HIGH); // enable pull-up
//digitalWrite(ENCODER_B_PIN, HIGH);
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(digitalPinToInterrupt(ENCODER_A_PIN), doEncoderA, FALLING);
// encoder pin on interrupt 1 (pin 3)
//attachInterrupt(1, doEncoderB, CHANGE);
}
void readEncoder() {
long now = millis();
if (now - lastEncoderRead < ENCODER_READ_INTERVAL) return;
lastEncoderRead = now;
int currentPos = encoderPos;
double delta = currentPos - oldEncoderPos;
if (delta == 0) {
encoderWasFast = false;
return;
}
Serial.print("Encoder delta: ");
Serial.println(delta);
oldEncoderPos = currentPos;
double deltaAbs = fabs(delta);
double deltaSign = delta / deltaAbs;
double displaySetPoint = setPointTempC;
if (!displayCelsius) displaySetPoint = cToF(setPointTempC);
// if it was a single click, change by one
if (deltaAbs < 2) {
if (!encoderWasFast) setDisplaySetPointTemp(displaySetPoint + delta);
encoderWasFast = false;
return;
}
// otherwise, change by 5 for each additional click, and round to nearest 5
encoderWasFast = true;
delta = (deltaAbs - 1) * deltaSign * 5;
setDisplaySetPointTemp(round((displaySetPoint + delta) / 5) * 5);
}
// Interrupt on A changing state
void doEncoderA() {
// Test transition
bool encoderASet = digitalRead(ENCODER_A_PIN) == HIGH;
bool encoderBSet = digitalRead(ENCODER_B_PIN) == HIGH;
// and adjust counter + if A leads B
encoderPos += (encoderASet != encoderBSet) ? +1 : -1;
}
////////////////////////////////
// Settings
////////////////////////////////
void setupSettings() {
// Setup Settings
EEPROM.get(0, settings);
Serial.print("setupSettings ");
printSettings();
if (settings.checkVal == CHECK_VAL) {
setPointTempC = settings.setPointC;
displayCelsius = settings.displayCelsius;
} else {
setPointTempC = DEFAULT_SET_POINT_C;
displayCelsius = false;
}
toggleState = displayCelsius;
}
void setDisplaySetPointTemp(double newSetPoint) {
if (!displayCelsius) newSetPoint = fToC(newSetPoint);
if (isnan(newSetPoint)) newSetPoint = DEFAULT_SET_POINT_C;
newSetPoint = min(newSetPoint, MAX_SET_POINT_C);
newSetPoint = max(newSetPoint, MIN_SET_POINT_C);
if (newSetPoint == setPointTempC) return;
setPointTempC = newSetPoint;
Serial.print("New set point: ");
Serial.print(setPointTempC);
Serial.println("°C");
}
// Write the settings if theyhave changed. Will only write as often as SETTINGS_WRITE_INTERVAL.
// Should be called in loop.
void updateSettings() {
long now = millis();
if (now - lastSettingsWrite < SETTINGS_WRITE_INTERVAL) return;
if (settings.checkVal != CHECK_VAL
|| settings.setPointC != setPointTempC
|| settings.displayCelsius != displayCelsius) {
settings.checkVal = CHECK_VAL;
settings.setPointC = setPointTempC;
settings.displayCelsius = displayCelsius;
Serial.print("updateSettings ");
printSettings();
EEPROM.put(0, settings);
lastSettingsWrite = now;
}
}
void printSettings() {
Serial.print("checkVal: ");
Serial.print(settings.checkVal);
Serial.print(", setPointC: ");
Serial.print(settings.setPointC);
Serial.print(", displayCelsius: ");
Serial.println(settings.displayCelsius);
}
////////////////////////////////
// Relay
////////////////////////////////
void setRelay(bool enabled) {
if (enabled == oldRelayEnabled) return;
oldRelayEnabled = enabled;
// set the relay pin
digitalWrite(RELAY_PIN, enabled ? HIGH : LOW);
// set the lcd indicator
lcd.setCursor(15, 0);
if (enabled) lcd.write((byte) UP_CHAR);
else lcd.print(" ");
}
////////////////////////////////
// Temperature
////////////////////////////////
void updateTemp() {
int now = millis();
if (now - lastTempReadTime < tempReadInterval) return false;
lastTempReadTime = now;
inputTempC = thermocouple.readCelsius();
input2TempC = thermocouple2.readCelsius();
// Serial.print("Read temp 1:");
// Serial.print(inputTempC);
// Serial.print("°C");
// Serial.print(", temp2: ");
// Serial.print(input2TempC);
// Serial.println("°C");
}
void printDegrees(double tempC) {
if ( isnan(tempC) ) {
lcd.print("-----");
return;
}
double temp = tempC;
if (!displayCelsius) temp = cToF(tempC);
temp = round(temp);
sprintf(degreesBuff, "%3d", (int)temp);
lcd.print(degreesBuff);
lcd.write((byte)DEGREE_CHAR);
if (displayCelsius) lcd.print("C");
else(lcd.print("F"));
}
float cToF(float c) {
return (c * 9 / 5) + 32;
}
float fToC(float f) {
return (f - 32) * 5 / 9;
}
void setDisplayCelsius(boolean newDisplayCelsius) {
if (displayCelsius == newDisplayCelsius) return;
Serial.print("set displayCelsius: ");
Serial.println(newDisplayCelsius);
displayCelsius = newDisplayCelsius;
}
//////////////////////////////
// Toggle Button
//////////////////////////////
void setupToggle() {
pinMode(TOGGLE_BUTTON_PIN, INPUT);
lastToggleTime = millis();
toggleState = displayCelsius;
}
void updateToggleState() {
int toggleRead = digitalRead(TOGGLE_BUTTON_PIN);
// if the input just went from HIGH to LOW and we've waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
if (toggleRead == LOW && togglePrevious == HIGH && millis() - lastToggleTime > TOGGLE_DEBOUNCE) {
toggleState = !toggleState;
lastToggleTime = millis();
}
setDisplayCelsius(toggleState);
togglePrevious = toggleRead;
}