forked from estechnical/reflowOvenController
/
ReflowController.ino
1525 lines (1243 loc) · 42.1 KB
/
ReflowController.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ----------------------------------------------------------------------------
// Reflow Oven Controller
// (c) 2014 Karl Pitrich <karl@pitrich.com>
// (c) 2012-2013 Ed Simmons
// ----------------------------------------------------------------------------
//#define FAKE_HW 1
//#define PIDTUNE 1 // autotune wouldn't fit in the 28k available on my arduino pro micro.
//#define WITH_BEEPER // Enables Beeper
// run a calibration loop that measures how many timer ticks occur between 2 zero corssings
// FIXME: does not work reliably at the moment, so a oscilloscope-determined value is used.
//#define WITH_CALIBRATION 1 // loop timing calibration
#define DEFAULT_LOOP_DELAY 89 // should be about 16% less for 60Hz mains
#include <avr/eeprom.h>
#include <EEPROM.h>
#include <PID_v1.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>
#include <Menu.h>
#include <TimerOne.h>
#include <ClickEncoder.h>
#include "temperature.h"
#include "helpers.h"
#ifdef FAKE_HW
#include <TimerThree.h>
#endif
#ifdef PIDTUNE
#include <PID_AutoTune_v0.h>
#endif
// ----------------------------------------------------------------------------
const char * ver = "3.1";
// ----------------------------------------------------------------------------
#define MS_PER_SINE 100 // for 50Hz mains; 100ms per sinusoid
//#define MS_PER_SINE 83.333 // for 60Hz Mains; 83,3333ms per sinusoid
// ----------------------------------------------------------------------------
// Hardware Configuration
// 1.8" TFT via SPI -> breadboard
#ifdef FAKE_HW
#define LCD_CS 10
#define LCD_DC 7
#define LCD_RST 8
#else
#define LCD_CS 10
#define LCD_DC 9
#define LCD_RST 8
#endif
// Thermocouple via SPI
#define THERMOCOUPLE1_CS 3
#define PIN_HEATER 0 // SSR for the heater
#define PIN_FAN 1 // SSR for the fan
#define PIN_BEEPER 5 // Beeper Out
#define PIN_ZX 2 // pin for zero crossing detector
#define INT_ZX 1 // interrupt for zero crossing detector
// Leonardo == Pro Micro:
// Pin: 3 2 0 1 7
// Int: 0 1 2 3 4
// ----------------------------------------------------------------------------
#define WITH_SPLASH 1
// ----------------------------------------------------------------------------
volatile uint32_t timerTicks = 0;
volatile uint32_t zeroCrossTicks = 0;
volatile uint8_t phaseCounter = 0;
char buf[20]; // generic char buffer
// ----------------------------------------------------------------------------
// data type for the values used in the reflow profile
typedef struct profileValues_s {
int16_t soakTemp;
int16_t soakDuration;
int16_t peakTemp;
int16_t peakDuration;
double rampUpRate;
double rampDownRate;
uint8_t checksum;
} Profile_t;
Profile_t activeProfile; // the one and only instance
int activeProfileId = 0;
int idleTemp = 50; // the temperature at which to consider the oven safe to leave to cool naturally
int fanAssistSpeed = 33; // default fan speed
const uint8_t maxProfiles = 30;
// EEPROM offsets
const uint16_t offsetFanSpeed = maxProfiles * sizeof(Profile_t) + 1; // one byte
const uint16_t offsetProfileNum = maxProfiles * sizeof(Profile_t) + 2; // one byte
const uint16_t offsetPidConfig = maxProfiles * sizeof(Profile_t) + 3; // sizeof(PID_t)
Thermocouple A;
// ----------------------------------------------------------------------------
uint32_t startCycleZeroCrossTicks;
uint32_t lastUpdate = 0;
uint32_t lastDisplayUpdate = 0;
// ----------------------------------------------------------------------------
// UI
// NB: Adafruit GFX ASCII-Table is bogous: https://github.com/adafruit/Adafruit-GFX-Library/issues/22
//
Adafruit_ST7735 tft = Adafruit_ST7735(LCD_CS, LCD_DC, LCD_RST);
#ifdef FAKE_HW
ClickEncoder Encoder(A0, A1, A2, 2);
#else
ClickEncoder Encoder(A1, A0, A2, 2);
#endif
Menu::Engine Engine;
int16_t encMovement;
int16_t encAbsolute;
int16_t encLastAbsolute = -1;
const uint8_t menuItemsVisible = 5;
const uint8_t menuItemHeight = 12;
bool menuUpdateRequest = true;
bool initialProcessDisplay = false;
// ----------------------------------------------------------------------------
// state machine
typedef enum {
None = 0,
Idle = 1,
Settings = 2,
Edit = 3,
UIMenuEnd = 9,
RampToSoak = 10,
Soak,
RampUp,
Peak,
RampDown,
CoolDown,
Complete = 20,
Tune = 30
} State;
State currentState = Idle;
State previousState = Idle;
bool stateChanged = false;
uint32_t stateChangedTicks = 0;
// ----------------------------------------------------------------------------
// track menu item state to improve render preformance
typedef struct {
const Menu::Item_t *mi;
uint8_t pos;
bool current;
} LastItemState_t;
LastItemState_t currentlyRenderedItems[menuItemsVisible];
void clearLastMenuItemRenderState() {
// memset(¤tlyRenderedItems, 0xff, sizeof(LastItemState_t) * menuItemsVisible);
for (uint8_t i = 0; i < menuItemsVisible; i++) {
currentlyRenderedItems[i].mi = NULL;
currentlyRenderedItems[i].pos = 0xff;
currentlyRenderedItems[i].current = false;
}
}
// ----------------------------------------------------------------------------
extern const Menu::Item_t miRampUpRate, miRampDnRate, miSoakTime,
miSoakTemp, miPeakTime, miPeakTemp,
miLoadProfile, miSaveProfile,
miPidSettingP, miPidSettingI, miPidSettingD,
miFanSettings;
// ----------------------------------------------------------------------------
// PID
uint8_t fanValue;
uint8_t heaterValue;
double Setpoint;
double Input;
double Output;
typedef struct {
double Kp;
double Ki;
double Kd;
} PID_t;
PID_t heaterPID = { 4.00, 0.05, 2.00 };
PID_t fanPID = { 1.00, 0.03, 10.00 };
PID PID(&Input, &Output, &Setpoint, heaterPID.Kp, heaterPID.Ki, heaterPID.Kd, DIRECT);
#ifdef PIDTUNE
PID_ATune PIDTune(&Input, &Output);
double aTuneStep = 50,
aTuneNoise = 1,
aTuneStartValue = 50; // is set to Output, i.e. 0-100% of Heater
unsigned int aTuneLookBack = 30;
#endif
// ----------------------------------------------------------------------------
bool menuExit(const Menu::Action_t a) {
clearLastMenuItemRenderState();
Engine.lastInvokedItem = &Menu::NullItem;
menuUpdateRequest = false;
return false;
}
// ----------------------------------------------------------------------------
bool menuDummy(const Menu::Action_t a) {
return true;
}
// ----------------------------------------------------------------------------
void printDouble(double val, uint8_t precision = 1) {
ftoa(buf, val, precision);
tft.print(buf);
}
// ----------------------------------------------------------------------------
void getItemValuePointer(const Menu::Item_t *mi, double **d, int16_t **i) {
if (mi == &miRampUpRate) *d = &activeProfile.rampUpRate;
if (mi == &miRampDnRate) *d = &activeProfile.rampDownRate;
if (mi == &miSoakTime) *i = &activeProfile.soakDuration;
if (mi == &miSoakTemp) *i = &activeProfile.soakTemp;
if (mi == &miPeakTime) *i = &activeProfile.peakDuration;
if (mi == &miPeakTemp) *i = &activeProfile.peakTemp;
if (mi == &miPidSettingP) *d = &heaterPID.Kp;
if (mi == &miPidSettingI) *d = &heaterPID.Ki;
if (mi == &miPidSettingD) *d = &heaterPID.Kd;
if (mi == &miFanSettings) *i = &fanAssistSpeed;
}
// ----------------------------------------------------------------------------
bool isPidSetting(const Menu::Item_t *mi) {
return mi == &miPidSettingP || mi == &miPidSettingI || mi == &miPidSettingD;
}
bool isRampSetting(const Menu::Item_t *mi) {
return mi == &miRampUpRate || mi == &miRampDnRate;
}
// ----------------------------------------------------------------------------
bool getItemValueLabel(const Menu::Item_t *mi, char *label) {
int16_t *iValue = NULL;
double *dValue = NULL;
char *p;
getItemValuePointer(mi, &dValue, &iValue);
if (isRampSetting(mi) || isPidSetting(mi)) {
p = label;
ftoa(p, *dValue, (isPidSetting(mi)) ? 2 : 1); // need greater precision with pid values
p = label;
if (isRampSetting(mi)) {
while(*p != '\0') p++;
*p++ = 0xf7; *p++ = 'C'; *p++ = '/'; *p++ = 's';
*p = '\0';
}
}
else {
if (mi == &miPeakTemp || mi == &miSoakTemp) {
itostr(label, *iValue, "\367C");
}
if (mi == &miPeakTime || mi == &miSoakTime) {
itostr(label, *iValue, "s");
}
if (mi == &miFanSettings) {
itostr(label, *iValue, "%");
}
}
return dValue || iValue;
}
// ----------------------------------------------------------------------------
bool editNumericalValue(const Menu::Action_t action) {
if (action == Menu::actionDisplay) {
bool initial = currentState != Edit;
currentState = Edit;
if (initial) {
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
tft.setCursor(10, 80);
tft.print("Edit & click to save.");
Encoder.setAccelerationEnabled(true);
}
for (uint8_t i = 0; i < menuItemsVisible; i++) {
if (currentlyRenderedItems[i].mi == Engine.currentItem) {
uint8_t y = currentlyRenderedItems[i].pos * menuItemHeight + 2;
if (initial) {
tft.fillRect(69, y - 1, 60, menuItemHeight - 2, ST7735_RED);
}
tft.setCursor(70, y);
break;
}
}
tft.setTextColor(ST7735_WHITE, ST7735_RED);
int16_t *iValue = NULL;
double *dValue = NULL;
getItemValuePointer(Engine.currentItem, &dValue, &iValue);
if (isRampSetting(Engine.currentItem) || isPidSetting(Engine.currentItem)) {
double tmp;
double factor = (isPidSetting(Engine.currentItem)) ? 100 : 10;
if (initial) {
tmp = *dValue;
tmp *= factor;
encAbsolute = (int16_t)tmp;
}
else {
tmp = encAbsolute;
tmp /= factor;
*dValue = tmp;
}
}
else {
if (initial) encAbsolute = *iValue;
else *iValue = encAbsolute;
}
getItemValueLabel(Engine.currentItem, buf);
tft.print(buf);
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
}
if (action == Menu::actionParent || action == Menu::actionTrigger) {
clearLastMenuItemRenderState();
menuUpdateRequest = true;
Engine.lastInvokedItem = &Menu::NullItem;
if (currentState == Edit) { // leave edit mode, return to menu
if (isPidSetting(Engine.currentItem)) {
savePID();
}
else if (Engine.currentItem == &miFanSettings) {
saveFanSpeed();
}
// don't autosave profile, so that one can do "save as" without overwriting the current profile
currentState = Settings;
Encoder.setAccelerationEnabled(false);
return false;
}
return true;
}
}
// ----------------------------------------------------------------------------
bool factoryReset(const Menu::Action_t action) {
#ifndef PIDTUNE
if (action == Menu::actionDisplay) {
bool initial = currentState != Edit;
currentState = Edit;
if (initial) { // TODO: add eyecandy: colors or icons
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
tft.setCursor(10, 80);
tft.print("Click to confirm");
tft.setCursor(10, 90);
tft.print("Doubleclick to exit");
}
}
if (action == Menu::actionTrigger) { // do it
factoryReset();
tft.fillScreen(ST7735_WHITE);
Engine.navigate(Engine.getParent());
return false;
}
if (action == Menu::actionParent) {
if (currentState == Edit) { // leave edit mode only, returning to menu
currentState = Settings;
clearLastMenuItemRenderState();
return false;
}
}
#endif // PIDTUNE
}
// ----------------------------------------------------------------------------
void saveProfile(unsigned int targetProfile, bool quiet = false);
// ----------------------------------------------------------------------------
bool saveLoadProfile(const Menu::Action_t action) {
#ifndef PIDTUNE
bool isLoad = Engine.currentItem == &miLoadProfile;
if (action == Menu::actionDisplay) {
bool initial = currentState != Edit;
currentState = Edit;
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
if (initial) {
encAbsolute = activeProfileId;
tft.setCursor(10, 90);
tft.print("Doubleclick to exit");
}
if (encAbsolute > maxProfiles) encAbsolute = maxProfiles;
if (encAbsolute < 0) encAbsolute = 0;
tft.setCursor(10, 80);
tft.print("Click to ");
tft.print((isLoad) ? "load " : "save ");
tft.setTextColor(ST7735_WHITE, ST7735_RED);
tft.print(encAbsolute);
}
if (action == Menu::actionTrigger) {
(isLoad) ? loadProfile(encAbsolute) : saveProfile(encAbsolute);
tft.fillScreen(ST7735_WHITE);
Engine.navigate(Engine.getParent());
return false;
}
if (action == Menu::actionParent) {
if (currentState == Edit) { // leave edit mode only, returning to menu
currentState = Settings;
clearLastMenuItemRenderState();
return false;
}
}
#endif // PIDTUNE
}
// ----------------------------------------------------------------------------
void toggleAutoTune();
bool cycleStart(const Menu::Action_t action) {
if (action == Menu::actionDisplay) {
startCycleZeroCrossTicks = zeroCrossTicks;
menuExit(action);
#ifndef PIDTUNE
currentState = RampToSoak;
#else
toggleAutoTune();
#endif
initialProcessDisplay = false;
menuUpdateRequest = false;
}
return true;
}
// ----------------------------------------------------------------------------
void renderMenuItem(const Menu::Item_t *mi, uint8_t pos) {
//ScopedTimer tm(" render menuitem");
bool isCurrent = Engine.currentItem == mi;
uint8_t y = pos * menuItemHeight + 2;
if (currentlyRenderedItems[pos].mi == mi
&& currentlyRenderedItems[pos].pos == pos
&& currentlyRenderedItems[pos].current == isCurrent)
{
return; // don't render the same item in the same state twice
}
tft.setCursor(10, y);
// menu cursor bar
tft.fillRect(8, y - 2, tft.width() - 16, menuItemHeight, isCurrent ? ST7735_BLUE : ST7735_WHITE);
if (isCurrent) tft.setTextColor(ST7735_WHITE, ST7735_BLUE);
else tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
tft.print(Engine.getLabel(mi));
// show values if in-place editable items
if (getItemValueLabel(mi, buf)) {
tft.print(' '); tft.print(buf); tft.print(" ");
}
// mark items that have children
if (Engine.getChild(mi) != &Menu::NullItem) {
tft.print(" \x10 "); // 0x10 -> filled right arrow
}
currentlyRenderedItems[pos].mi = mi;
currentlyRenderedItems[pos].pos = pos;
currentlyRenderedItems[pos].current = isCurrent;
}
// ----------------------------------------------------------------------------
// Name, Label, Next, Previous, Parent, Child, Callback
MenuItem(miExit, "", Menu::NullItem, Menu::NullItem, Menu::NullItem, miCycleStart, menuExit);
#ifndef PIDTUNE
MenuItem(miCycleStart, "Start Cycle", miEditProfile, Menu::NullItem, miExit, Menu::NullItem, cycleStart);
#else
MenuItem(miCycleStart, "Start Autotune", miEditProfile, Menu::NullItem, miExit, Menu::NullItem, cycleStart);
#endif
MenuItem(miEditProfile, "Edit Profile", miLoadProfile, miCycleStart, miExit, miRampUpRate, menuDummy);
MenuItem(miRampUpRate, "Ramp up ", miSoakTemp, Menu::NullItem, miEditProfile, Menu::NullItem, editNumericalValue);
MenuItem(miSoakTemp, "Soak temp", miSoakTime, miRampUpRate, miEditProfile, Menu::NullItem, editNumericalValue);
MenuItem(miSoakTime, "Soak time", miPeakTemp, miSoakTemp, miEditProfile, Menu::NullItem, editNumericalValue);
MenuItem(miPeakTemp, "Peak temp", miPeakTime, miSoakTime, miEditProfile, Menu::NullItem, editNumericalValue);
MenuItem(miPeakTime, "Peak time", miRampDnRate, miPeakTemp, miEditProfile, Menu::NullItem, editNumericalValue);
MenuItem(miRampDnRate, "Ramp down", Menu::NullItem, miPeakTime, miEditProfile, Menu::NullItem, editNumericalValue);
MenuItem(miLoadProfile, "Load Profile", miSaveProfile, miEditProfile, miExit, Menu::NullItem, saveLoadProfile);
MenuItem(miSaveProfile, "Save Profile", miFanSettings, miLoadProfile, miExit, Menu::NullItem, saveLoadProfile);
MenuItem(miFanSettings, "Fan Speed", miPidSettings, miSaveProfile, miExit, Menu::NullItem, editNumericalValue);
MenuItem(miPidSettings, "PID Settings", miFactoryReset, miFanSettings, miExit, miPidSettingP, menuDummy);
MenuItem(miPidSettingP, "Heater Kp", miPidSettingI, Menu::NullItem, miPidSettings, Menu::NullItem, editNumericalValue);
MenuItem(miPidSettingI, "Heater Ki", miPidSettingD, miPidSettingP, miPidSettings, Menu::NullItem, editNumericalValue);
MenuItem(miPidSettingD, "Heater Kd", Menu::NullItem, miPidSettingI, miPidSettings, Menu::NullItem, editNumericalValue);
MenuItem(miFactoryReset, "Factory Reset", Menu::NullItem, miPidSettings, miExit, Menu::NullItem, factoryReset);
// ----------------------------------------------------------------------------
#define NUMREADINGS 10
typedef struct {
double temp;
uint16_t ticks;
} Temp_t;
Temp_t airTemp[NUMREADINGS];
double readingsT1[NUMREADINGS]; // the readings used to make a stable temp rolling average
double runningTotalRampRate;
double rampRate = 0;
double rateOfRise = 0; // the result that is displayed
double totalT1 = 0; // the running total
double averageT1 = 0; // the average
uint8_t index = 0; // the index of the current reading
// ----------------------------------------------------------------------------
// Ensure that Solid State Relais are off when starting
//
void setupRelayPins(void) {
DDRD |= (1 << 2) | (1 << 3); // output
//PORTD &= ~((1 << 2) | (1 << 3));
PORTD |= (1 << 2) | (1 << 3); // off
}
void killRelayPins(void) {
Timer1.stop();
detachInterrupt(INT_ZX);
PORTD |= (1 << 2) | (1 << 3);
}
// ----------------------------------------------------------------------------
// wave packet control: only turn the solid state relais on for a percentage
// of complete sinusoids (i.e. 1x 360°)
#define CHANNELS 2
#define CHANNEL_HEATER 0
#define CHANNEL_FAN 1
typedef struct Channel_s {
volatile uint8_t target; // percentage of on-time
uint8_t state; // current state counter
int32_t next; // when the next change in output shall occur
bool action; // hi/lo active
uint8_t pin; // io pin of solid state relais
} Channel_t;
Channel_t Channels[CHANNELS] = {
// heater
{ 0, 0, 0, false, 2 }, // PD2 == RX == Arduino Pin 0
// fan
{ 0, 0, 0, false, 3 } // PD3 == TX == Arduino Pin 1
};
// delay to align relay activation with the actual zero crossing
uint16_t zxLoopDelay = 0;
#ifdef WITH_CALIBRATION
// calibrate zero crossing: how many timerIsr happen within one zero crossing
#define zxCalibrationLoops 128
struct {
volatile int8_t iterations;
volatile uint8_t measure[zxCalibrationLoops];
} zxLoopCalibration = {
0, {}
};
#endif
// ----------------------------------------------------------------------------
// Zero Crossing ISR; per ZX, process one channel per interrupt only
// NB: use native port IO instead of digitalWrite for better performance
void zeroCrossingIsr(void) {
static uint8_t ch = 0;
// reset phase control timer
phaseCounter = 0;
TCNT1 = 0;
zeroCrossTicks++;
// calculate wave packet parameters
Channels[ch].state += Channels[ch].target;
if (Channels[ch].state >= 100) {
Channels[ch].state -= 100;
Channels[ch].action = false;
}
else {
Channels[ch].action = true;
}
Channels[ch].next = timerTicks + zxLoopDelay; // delay added to reach the next zx
ch = ((ch + 1) % CHANNELS); // next channel
#ifdef WITH_CALIBRATION
if (zxLoopCalibration.iterations < zxCalibrationLoops) {
zxLoopCalibration.iterations++;
}
#endif
}
// ----------------------------------------------------------------------------
// timer interrupt handling
void timerIsr(void) { // ticks with 100µS
static uint32_t lastTicks = 0;
// phase control for the fan
if (++phaseCounter > 90) {
phaseCounter = 0;
}
if (phaseCounter > Channels[CHANNEL_FAN].target) {
PORTD &= ~(1 << Channels[CHANNEL_FAN].pin);
}
else {
PORTD |= (1 << Channels[CHANNEL_FAN].pin);
}
// wave packet control for heater
if (Channels[CHANNEL_HEATER].next > lastTicks // FIXME: this looses ticks when overflowing
&& timerTicks > Channels[CHANNEL_HEATER].next)
{
if (Channels[CHANNEL_HEATER].action) PORTD |= (1 << Channels[CHANNEL_HEATER].pin);
else PORTD &= ~(1 << Channels[CHANNEL_HEATER].pin);
lastTicks = timerTicks;
}
// handle encoder + button
if (!(timerTicks % 10)) {
Encoder.service();
}
timerTicks++;
#ifdef WITH_CALIBRATION
if (zxLoopCalibration.iterations < zxCalibrationLoops) {
zxLoopCalibration.measure[zxLoopCalibration.iterations]++;
}
#endif
}
// ----------------------------------------------------------------------------
void abortWithError(int error) {
killRelayPins();
tft.setTextColor(ST7735_WHITE, ST7735_RED);
tft.fillScreen(ST7735_RED);
tft.setCursor(10, 10);
if (error < 9) {
tft.println("Thermocouple Error");
tft.setCursor(10, 30);
switch (error) {
case 0b001:
tft.println("Open Circuit");
break;
case 0b010:
tft.println("GND Short");
break;
case 0b100:
tft.println("VCC Short");
break;
}
tft.setCursor(10, 60);
tft.println("Power off,");
tft.setCursor(10, 75);
tft.println("check connections");
}
else {
tft.println("Temperature");
tft.setCursor(10, 30);
tft.println("following error");
tft.setCursor(10, 45);
tft.print("during ");
tft.println((error == 10) ? "heating" : "cooling");
}
#ifdef WITH_BEEPER
tone(PIN_BEEPER,1760,2000); //Error Beep
#endif
while (1) { // stop
;
}
}
// ----------------------------------------------------------------------------
void displayThermocoupleData(struct Thermocouple* input) {
switch (input->stat) {
case 0:
printDouble(input->temperature);
tft.print("\367C");
break;
case 1:
tft.print("---");
break;
}
}
// ----------------------------------------------------------------------------
void alignRightPrefix(uint16_t v) {
if (v < 1e2) tft.print(' ');
if (v < 1e1) tft.print(' ');
}
uint16_t pxPerS;
uint16_t pxPerC;
uint16_t xOffset; // used for wraparound on x axis
void updateProcessDisplay() {
const uint8_t h = 86;
const uint8_t w = 160;
const uint8_t yOffset = 30; // space not available for graph
uint16_t dx, dy;
uint8_t y = 2;
double tmp;
// header & initial view
tft.setTextColor(ST7735_WHITE, ST7735_BLUE);
if (!initialProcessDisplay) {
initialProcessDisplay = true;
tft.fillScreen(ST7735_WHITE);
tft.fillRect(0, 0, tft.width(), menuItemHeight, ST7735_BLUE);
tft.setCursor(2, y);
#ifndef PIDTUNE
tft.print("Profile ");
tft.print(activeProfileId);
#else
tft.print("Tuning ");
#endif
tmp = h / (activeProfile.peakTemp * 1.10) * 100.0;
pxPerC = (uint16_t)tmp;
#if 0 // pxPerS should be calculated from the selected profile, wint fit in flash right now
double estimatedTotalTime = 60 * 12;
// estimate total run time for current profile
estimatedTotalTime = activeProfile.soakDuration + activeProfile.peakDuration;
estimatedTotalTime += (activeProfile.soakTemp - 20.0) / (activeProfile.rampUpRate / 10);
estimatedTotalTime += (activeProfile.peakTemp - activeProfile.soakTemp) / (activeProfile.rampUpRate / 10);
estimatedTotalTime += (activeProfile.peakTemp - 20.0) / (activeProfile.rampDownRate / 10);
//estimatedTotalTime *= 2; // add some spare
Serial.print("total est. time: ");
Serial.println((uint16_t)estimatedTotalTime);
#endif
tmp = 60 * 8;
tmp = w / tmp * 10.0;
pxPerS = (uint16_t)tmp;
// 50°C grid
int16_t t = (uint16_t)(activeProfile.peakTemp * 1.10);
for (uint16_t tg = 0; tg < t; tg += 50) {
uint16_t l = h - (tg * pxPerC / 100) + yOffset;
tft.drawFastHLine(0, l, 160, tft.Color565(0xe0, 0xe0, 0xe0));
}
#ifdef GRAPH_VERBOSE
Serial.print("Calc pxPerC/S: ");
Serial.print(pxPerC);
Serial.print("/");
Serial.println(pxPerS);
#endif
}
// elapsed time
uint16_t elapsed = (zeroCrossTicks - startCycleZeroCrossTicks) / 100;
tft.setCursor(125, y);
alignRightPrefix(elapsed);
tft.print(elapsed);
tft.print("s");
y += menuItemHeight + 2;
tft.setCursor(2, y);
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
// temperature
tft.setTextSize(2);
alignRightPrefix((int)A.temperature);
displayThermocoupleData(&A);
tft.setTextSize(1);
#ifndef PIDTUNE
// current state
y -= 2;
tft.setCursor(95, y);
tft.setTextColor(ST7735_BLACK, ST7735_GREEN);
switch (currentState) {
#define casePrintState(state) case state: tft.print(#state); break;
casePrintState(RampToSoak);
casePrintState(Soak);
casePrintState(RampUp);
casePrintState(Peak);
casePrintState(RampDown);
casePrintState(CoolDown);
casePrintState(Complete);
default: tft.print((uint8_t)currentState); break;
}
tft.print(" "); // lazy: fill up space
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
#endif
// set point
y += 10;
tft.setCursor(95, y);
tft.print("Sp:");
alignRightPrefix((int)Setpoint);
printDouble(Setpoint);
tft.print("\367C ");
// draw temperature curves
//
if (xOffset >= elapsed) {
xOffset = 0;
}
do { // x with wrap around
dx = ((elapsed - xOffset) * pxPerS) / 10;
if (dx > w) {
xOffset = elapsed;
}
} while(dx > w);
// temperature setpoint
dy = h - ((uint16_t)Setpoint * pxPerC / 100) + yOffset;
tft.drawPixel(dx, dy, ST7735_BLUE);
// actual temperature
dy = h - ((uint16_t)A.temperature * pxPerC / 100) + yOffset;
tft.drawPixel(dx, dy, ST7735_RED);
// bottom line
y = 119;
// set values
tft.setCursor(2, y);
tft.print("\xef");
alignRightPrefix((int)heaterValue);
tft.print((int)heaterValue);
tft.print('%');
tft.print(" \x2a");
alignRightPrefix((int)fanValue);
tft.print((int)fanValue);
tft.print('%');
tft.print(" \x12 "); // alternative: \x7f
printDouble(rampRate);
tft.print("\367C/s ");
}
// ----------------------------------------------------------------------------
void setup() {
setupRelayPins();
tft.initR(INITR_BLACKTAB);
tft.setTextWrap(false);
tft.setTextSize(1);
tft.setRotation(1);
if (firstRun()) {
factoryReset();
loadParameters(0);
}
else {
loadLastUsedProfile();
}
tft.fillScreen(ST7735_WHITE);
tft.setTextColor(ST7735_BLACK, ST7735_WHITE);
Timer1.initialize(100);
Timer1.attachInterrupt(timerIsr);
#ifndef FAKE_HW
pinMode(PIN_ZX, INPUT_PULLUP);
attachInterrupt(INT_ZX, zeroCrossingIsr, RISING);
delay(100);
#else
Timer3.initialize(1000); // x10 speed
Timer3.attachInterrupt(zeroCrossingIsr);
#endif
#ifdef WITH_SPLASH
// splash screen
tft.setCursor(10, 30);
tft.setTextSize(2);
tft.print("Reflow");
tft.setCursor(24, 48);
tft.print("Controller");
tft.setTextSize(1);
tft.setCursor(52, 67);
tft.print("v"); tft.print(ver);
#ifdef FAKE_HW
tft.print("-fake");
#endif
tft.setCursor(7, 119);
tft.print("(c)2014 karl@pitrich.com");
delay(1000);
#endif
// setup /CS line for thermocouple and read initial temperature
A.chipSelect = THERMOCOUPLE1_CS;
pinMode(A.chipSelect, OUTPUT);
digitalWrite(A.chipSelect, HIGH);
#ifndef FAKE_HW
readThermocouple(&A);
#endif
if (A.stat != 0) {
abortWithError(A.stat);
}
// initialize moving average filter
runningTotalRampRate = A.temperature * NUMREADINGS;
for(int i = 0; i < NUMREADINGS; i++) {
airTemp[i].temp = A.temperature;
}
#ifdef WITH_CALIBRATION
tft.setCursor(7, 99);
tft.print("Calibrating... ");
delay(400);
// FIXME: does not work reliably
while (zxLoopDelay == 0) {
if (zxLoopCalibration.iterations == zxCalibrationLoops) { // average tick measurements, dump 1st value
for (int8_t l = 0; l < zxCalibrationLoops; l++) {
zxLoopDelay += zxLoopCalibration.measure[l];
}
zxLoopDelay /= zxCalibrationLoops;
zxLoopDelay -= 10; // compensating loop runtime
}