-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathsoldering_907_lcd.ino
2125 lines (1944 loc) · 73.3 KB
/
soldering_907_lcd.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
/*
* Soldering IRON controller for hakko 907 soldering IRON using interrupts from the Timer1 to check the temperature
* The IRON heater is managed by pin D10 with FastPWM function using Timer1
* Timer1 runs with prescale 1 through 0 to 255 and back, switching the D10 pin each time
* The PWM frequency on the pin D10 is 31250 Hz
* Timer1 generates also the overflow interrupts at 31250 Hz.
* Overflow interrupts are using to check the IRON temperature
* First, the IRON is powered off and the controller waits for 32 timer interrupts (about 1 ms)
* then the current IRON temperature is checked and the controller waits for check_period Timer1 interrupts
* to restart the all procedure over again
*/
#include <LiquidCrystal.h>
#include <EEPROM.h>
// The LCD 0802 parallel interface
const byte LCD_RS_PIN = 13;
const byte LCD_E_PIN = 12;
const byte LCD_DB4_PIN = 5;
const byte LCD_DB5_PIN = 6;
const byte LCD_DB6_PIN = 7;
const byte LCD_DB7_PIN = 8;
// Rotary encoder interface
const byte R_MAIN_PIN = 2; // Rotary Encoder main pin (right)
const byte R_SECD_PIN = 4; // Rotary Encoder second pin (left)
const byte R_BUTN_PIN = 3; // Rotary Encoder push button pin
const byte probePIN = A0; // Thermometer pin from soldering iron
const byte heaterPIN = 10; // The soldering iron heater pin
const byte buzzerPIN = 11; // The simple buzzer to make a noise
const uint16_t temp_minC = 180; // Minimum temperature in degrees of celsius
const uint16_t temp_maxC = 400; // Maximum temperature in degrees of celsius
const uint16_t temp_minF = (temp_minC *9 + 32*5 + 2)/5;
const uint16_t temp_maxF = (temp_maxC *9 + 32*5 + 2)/5;
const uint16_t temp_tip[3] = {200, 300, 400};
// The variables for Timer1 operations
volatile uint16_t tmr1_count; // The count to calculate the temperature check period
volatile bool iron_off; // Whether the IRON is switched off to check the temperature
const uint32_t check_period = 100; // The IRON temperature check period, ms
//------------------------------------------ Configuration data ------------------------------------------------
/* Config record in the EEPROM has the following format:
uint32_t ID each time increment by 1
struct cfg config data, 8 bytes
byte CRC the checksum
*/
struct cfg {
uint32_t calibration; // The temperature calibration data for soldering IRON. (3 reference points: 200, 300, 400 Centegrees)
uint16_t temp; // The preset temperature of the IRON in the internal units
byte off_timeout; // The Automatic switch-off timeout in minutes [0 - 30]
bool celsius; // Temperature units: true - Celsius, false - Farenheit
};
class CONFIG {
public:
CONFIG() {
can_write = false;
buffRecords = 0;
rAddr = wAddr = 0;
eLength = 0;
nextRecID = 0;
byte rs = sizeof(struct cfg) + 5; // The total config record size
// Select appropriate record size; The record size should be power of 2, i.e. 8, 16, 32, 64, ... bytes
for (record_size = 8; record_size < rs; record_size <<= 1);
}
void init();
bool load(void);
void getConfig(struct cfg &Cfg); // Copy config structure from this class
void updateConfig(struct cfg &Cfg); // Copy updated config into this class
bool save(void); // Save current config copy to the EEPROM
bool saveConfig(struct cfg &Cfg); // write updated config into the EEPROM
void clearAll(void); // Clean all EEPROM
protected:
struct cfg Config;
private:
bool readRecord(uint16_t addr, uint32_t &recID);
bool can_write; // The flag indicates that data can be saved
byte buffRecords; // Number of the records in the outpt buffer
uint16_t rAddr; // Address of thecorrect record in EEPROM to be read
uint16_t wAddr; // Address in the EEPROM to start write new record
uint16_t eLength; // Length of the EEPROM, depends on arduino model
uint32_t nextRecID; // next record ID
byte record_size; // The size of one record in bytes
};
// Read the records until the last one, point wAddr (write address) after the last record
void CONFIG::init(void) {
eLength = EEPROM.length();
uint32_t recID;
uint32_t minRecID = 0xffffffff;
uint16_t minRecAddr = 0;
uint32_t maxRecID = 0;
uint16_t maxRecAddr = 0;
byte records = 0;
nextRecID = 0;
// read all the records in the EEPROM find min and max record ID
for (uint16_t addr = 0; addr < eLength; addr += record_size) {
if (readRecord(addr, recID)) {
++records;
if (minRecID > recID) {
minRecID = recID;
minRecAddr = addr;
}
if (maxRecID < recID) {
maxRecID = recID;
maxRecAddr = addr;
}
} else {
break;
}
}
if (records == 0) {
wAddr = rAddr = 0;
can_write = true;
return;
}
rAddr = maxRecAddr;
if (records < (eLength / record_size)) { // The EEPROM is not full
wAddr = rAddr + record_size;
if (wAddr > eLength) wAddr = 0;
} else {
wAddr = minRecAddr;
}
can_write = true;
}
void CONFIG::getConfig(struct cfg &Cfg) {
memcpy(&Cfg, &Config, sizeof(struct cfg));
}
void CONFIG::updateConfig(struct cfg &Cfg) {
memcpy(&Config, &Cfg, sizeof(struct cfg));
}
bool CONFIG::saveConfig(struct cfg &Cfg) {
updateConfig(Cfg);
return save(); // Save new data into the EEPROM
}
bool CONFIG::save(void) {
if (!can_write) return can_write;
if (nextRecID == 0) nextRecID = 1;
uint16_t startWrite = wAddr;
uint32_t nxt = nextRecID;
byte summ = 0;
for (byte i = 0; i < 4; ++i) {
EEPROM.write(startWrite++, nxt & 0xff);
summ <<=2; summ += nxt;
nxt >>= 8;
}
byte* p = (byte *)&Config;
for (byte i = 0; i < sizeof(struct cfg); ++i) {
summ <<= 2; summ += p[i];
EEPROM.write(startWrite++, p[i]);
}
summ ++; // To avoid empty records
EEPROM.write(wAddr+record_size-1, summ);
rAddr = wAddr;
wAddr += record_size;
if (wAddr > EEPROM.length()) wAddr = 0;
nextRecID ++; // Get ready to write next record
return true;
}
bool CONFIG::load(void) {
bool is_valid = readRecord(rAddr, nextRecID);
nextRecID ++;
return is_valid;
}
bool CONFIG::readRecord(uint16_t addr, uint32_t &recID) {
byte Buff[record_size];
for (byte i = 0; i < record_size; ++i)
Buff[i] = EEPROM.read(addr+i);
byte summ = 0;
for (byte i = 0; i < sizeof(struct cfg) + 4; ++i) {
summ <<= 2; summ += Buff[i];
}
summ ++; // To avoid empty fields
if (summ == Buff[record_size-1]) { // Checksumm is correct
uint32_t ts = 0;
for (char i = 3; i >= 0; --i) {
ts <<= 8;
ts |= Buff[byte(i)];
}
recID = ts;
memcpy(&Config, &Buff[4], sizeof(struct cfg));
return true;
}
return false;
}
void CONFIG::clearAll(void) {
for (uint16_t i = 0; i < eLength; ++i)
EEPROM.write(i, 0);
init();
load();
}
//------------------------------------------ class IRON CONFIG -------------------------------------------------
class IRON_CFG : public CONFIG {
public:
IRON_CFG() { current_tip = 0; t_tip[0] = t_tip[1] = t_tip[2] = 0; is_calibrated = false; }
void init(void);
bool isCelsius(void) { return Config.celsius; }
bool isCold(uint16_t temp); // Whether the IRON is temperature is low
uint16_t tempPresetHuman(void); // The preset Temperature in the human readable units
uint16_t tempPreset(void) { return Config.temp; }
uint16_t human2temp(uint16_t temp); // Translate the human readable temperature into internal value
uint16_t tempHuman(uint16_t temp); // Thanslate temperature from internal units to the human readable value (Celsius or Farenheit)
byte selectTip(byte index); // Select new tip, return selected tip index
byte getOffTimeout(void) { return Config.off_timeout; }
bool getTempUnits(void) { return Config.celsius; }
bool savePresetTempHuman(uint16_t temp);// Save preset temperature in the human readable units
bool savePresetTemp(uint16_t temp); // Save preset temperature in the internal units (convert it to the human readable units)
void saveConfig(byte off, bool cels); // Save global configuration parameters
void applyCalibrationData(uint16_t tip[3]);
void getCalibrationData(uint16_t tip[3]);
void saveCalibrationData(uint16_t tip[3]);
void setDefaults(bool Write = false); // Set default parameter values if failed to load data from EEPROM
private:
byte current_tip; // The current tip index
bool is_calibrated; // whether the tip has calibrated data
// t_tip[] - array of internal sensor readings of the current tip at reference temperatures,
// defined in temp_tip[] global array
uint16_t t_tip[3];
const uint16_t def_tip[3] = {587, 751, 916};// Default values of internal sensor readings at reference temperatures
const uint16_t def_set = 653; // Default preset temperature in internal units
const uint16_t ambient_temp = 350; // Ambient temperatire in the internal units
const uint16_t ambient_tempC = 25; // Ambient temperature in Celsius
const uint16_t max_temp = 960; // Maximum possible temperature readings in internal units
};
void IRON_CFG::init(void) {
CONFIG::init();
if (!CONFIG::load()) setDefaults(); // If failed to load the data from EEPROM, initialize the config data with default values
uint32_t cd = Config.calibration;
t_tip[0] = cd & 0x3FF; cd >>= 10; // 10 bits per calibration parameter, because the ADC readings are 10 bits
t_tip[1] = cd & 0x3FF; cd >>= 10;
t_tip[2] = cd & 0x3FF;
// Check the tip calibration is correct
if ((t_tip[0] >= t_tip[1]) || (t_tip[1] >= t_tip[2])) {
setDefaults();
for (byte i = 0; i < 3; ++i)
t_tip[i] = def_tip[i];
}
}
bool IRON_CFG::isCold(uint16_t temp) {
return (temp < t_tip[0]) && (map(temp, ambient_temp, t_tip[0], ambient_tempC, temp_tip[0]) < 32);
}
uint16_t IRON_CFG::tempPresetHuman(void) {
return tempHuman(Config.temp);
}
// Translate the temperature from human readable units (Celsius or Fahrenheit) to the internal units
uint16_t IRON_CFG::human2temp(uint16_t t) {
uint16_t t0 = temp_tip[0];
uint16_t t2 = temp_tip[2];
if (!Config.celsius) { // Translate the temperature limits to Fahrenheit
t0 = map(t0, temp_minC, temp_maxC, temp_minF, temp_maxF);
t2 = map(t2, temp_minC, temp_maxC, temp_minF, temp_maxF);
if (t < temp_minF) t = temp_minF;
if (t > temp_maxF) t = temp_maxF;
} else {
if (t < temp_minC) t = temp_minC;
if (t > temp_maxC) t = temp_maxC;
}
uint16_t left = 0;
uint16_t right = max_temp;
uint16_t temp = map(t, t0, t2, t_tip[0], t_tip[2]);
if (temp > (left+right) / 2) {
temp -= (right-left) / 4;
} else {
temp += (right-left) / 4;
}
for (uint8_t i = 0; i < 20; ++i) {
uint16_t tempH = tempHuman(temp);
if (tempH == t) {
return temp;
}
uint16_t new_temp;
if (tempH < t) {
left = temp;
new_temp = (left+right)/2;
if (new_temp == temp)
new_temp = temp + 1;
} else {
right = temp;
new_temp = (left+right)/2;
if (new_temp == temp)
new_temp = temp - 1;
}
temp = new_temp;
}
return temp;
}
// Thanslate temperature from internal units to the human readable value (Celsius or Farenheit)
uint16_t IRON_CFG::tempHuman(uint16_t temp) {
uint16_t tempH = 0;
if (temp < ambient_temp) {
tempH = ambient_tempC;
} else if (temp < t_tip[0]) {
tempH = map(temp, ambient_temp, t_tip[0], ambient_tempC, temp_tip[0]);
} else if (temp >= t_tip[1]) {
tempH = map(temp, t_tip[1], t_tip[2], temp_tip[1], temp_tip[2]);
} else {
tempH = map(temp, t_tip[0], t_tip[1], temp_tip[0], temp_tip[1]);
}
if (!Config.celsius)
tempH = map(tempH, temp_minC, temp_maxC, temp_minF, temp_maxF);
return tempH;
}
bool IRON_CFG::savePresetTempHuman(uint16_t temp) {
Config.temp = human2temp(temp);
return CONFIG::save();
}
bool IRON_CFG::savePresetTemp(uint16_t temp) {
Config.temp = temp;
return CONFIG::save();
}
void IRON_CFG::saveConfig(byte off, bool cels) {
if (off > 30) off = 0;
Config.off_timeout = off;
Config.celsius = cels;
CONFIG::save(); // Save new data into the EEPROM
}
void IRON_CFG::applyCalibrationData(uint16_t tip[3]) {
if (tip[0] < ambient_temp) {
uint16_t t = ambient_temp + tip[1];
tip[0] = t >> 1;
}
t_tip[0] = tip[0];
t_tip[1] = tip[1];
if (tip[2] > max_temp) tip[2] = max_temp;
t_tip[2] = tip[2];
}
void IRON_CFG::getCalibrationData(uint16_t tip[3]) {
tip[0] = t_tip[0];
tip[1] = t_tip[1];
tip[2] = t_tip[2];
}
void IRON_CFG::saveCalibrationData(uint16_t tip[3]) {
if (tip[2] > max_temp) tip[2] = max_temp;
uint32_t cd = tip[2] & 0x3FF; cd <<= 10; // Pack tip calibration data in one 32-bit word: 10-bits per value
cd |= tip[1] & 0x3FF; cd <<= 10;
cd |= tip[0];
Config.calibration = cd;
t_tip[0] = tip[0];
t_tip[1] = tip[1];
t_tip[2] = tip[2];
}
void IRON_CFG::setDefaults(bool Write) {
uint32_t c = def_tip[2] & 0x3FF; c <<= 10;
c |= def_tip[1] & 0x3FF; c <<= 10;
c |= def_tip[0] & 0x3FF;
Config.calibration = c;
Config.temp = def_set;
Config.off_timeout = 0; // Default autometic switch-off timeout (disabled)
Config.celsius = true; // Default use celsius
if (Write) {
CONFIG::clearAll();
CONFIG::save();
}
}
//------------------------------------------ class BUZZER ------------------------------------------------------
class BUZZER {
public:
BUZZER(byte buzzerP) { buzzer_pin = buzzerP; }
void init(void);
void shortBeep(void) { tone(buzzerPIN, 3520, 160); }
void lowBeep(void) { tone(buzzerPIN, 880, 160); }
void doubleBeep(void) { tone(buzzerPIN, 3520, 160); delay(300); tone(buzzerPIN, 3520, 160); }
void failedBeep(void) { tone(buzzerPIN, 3520, 160); delay(170);
tone(buzzerPIN, 880, 250); delay(260);
tone(buzzerPIN, 3520, 160);
}
private:
byte buzzer_pin;
};
void BUZZER::init(void) {
pinMode(buzzer_pin, OUTPUT);
noTone(buzzer_pin);
}
//------------------------------------------ class BUTTON ------------------------------------------------------
class BUTTON {
public:
BUTTON(byte ButtonPIN, unsigned int timeout_ms = 3000) {
pt = tickTime = 0;
buttonPIN = ButtonPIN;
overPress = timeout_ms;
}
void init(void) { pinMode(buttonPIN, INPUT_PULLUP); }
void setTimeout(uint16_t timeout_ms = 3000) { overPress = timeout_ms; }
byte intButtonStatus(void) { byte m = mode; mode = 0; return m; }
void cnangeINTR(void);
byte buttonCheck(void);
bool buttonTick(void);
private:
volatile byte mode; // The button mode: 0 - not pressed, 1 - pressed, 2 - long pressed
uint16_t overPress; // Maxumum time in ms the button can be pressed
volatile uint32_t pt; // Time in ms when the button was pressed (press time)
uint32_t tickTime; // The time in ms when the button Tick was set
byte buttonPIN; // The pin number connected to the button
const uint16_t tickTimeout = 200; // Period of button tick, while tha button is pressed
const uint16_t shortPress = 900; // If the button was pressed less that this timeout, we assume the short button press
};
void BUTTON::cnangeINTR(void) { // Interrupt function, called when the button status changed
bool keyUp = digitalRead(buttonPIN);
unsigned long now_t = millis();
if (!keyUp) { // The button has been pressed
if ((pt == 0) || (now_t - pt > overPress)) pt = now_t;
} else {
if (pt > 0) {
if ((now_t - pt) < shortPress) mode = 1; // short press
else mode = 2; // long press
pt = 0;
}
}
}
byte BUTTON::buttonCheck(void) { // Check the button state, called each time in the main loop
mode = 0;
bool keyUp = digitalRead(buttonPIN); // Read the current state of the button
uint32_t now_t = millis();
if (!keyUp) { // The button is pressed
if ((pt == 0) || (now_t - pt > overPress)) pt = now_t;
} else {
if (pt == 0) return 0;
if ((now_t - pt) > shortPress) // Long press
mode = 2;
else
mode = 1;
pt = 0;
}
return mode;
}
bool BUTTON::buttonTick(void) { // When the button pressed for a while, generate periodical ticks
bool keyUp = digitalRead(buttonPIN); // Read the current state of the button
uint32_t now_t = millis();
if (!keyUp && (now_t - pt > shortPress)) { // The button have been pressed for a while
if (now_t - tickTime > tickTimeout) {
tickTime = now_t;
return (pt != 0);
}
} else {
if (pt == 0) return false;
tickTime = 0;
}
return false;
}
//------------------------------------------ class ENCODER ------------------------------------------------------
class ENCODER {
public:
ENCODER(byte aPIN, byte bPIN, int16_t initPos = 0) {
pt = 0; mPIN = aPIN; sPIN = bPIN; pos = initPos;
min_pos = -32767; max_pos = 32766; channelB = false; increment = 1;
changed = 0;
is_looped = false;
}
void init(void) {
pinMode(mPIN, INPUT_PULLUP);
pinMode(sPIN, INPUT_PULLUP);
}
void set_increment(byte inc) { increment = inc; }
byte get_increment(void) { return increment; }
int16_t read(void) { return pos; }
void reset(int16_t initPos, int16_t low, int16_t upp, byte inc = 1, byte fast_inc = 0, bool looped = false);
bool write(int16_t initPos);
void cnangeINTR(void);
private:
int32_t min_pos, max_pos;
volatile uint32_t pt; // Time in ms when the encoder was rotaded
volatile uint32_t changed; // Time in ms when the value was changed
volatile bool channelB;
volatile int16_t pos; // Encoder current position
byte mPIN, sPIN; // The pin numbers connected to the main channel and to the socondary channel
bool is_looped; // Whether the encoder is looped
byte increment; // The value to add or substract for each encoder tick
byte fast_increment; // The value to change encoder when in runs quickly
const uint16_t fast_timeout = 300; // Time in ms to change encodeq quickly
const uint16_t overPress = 1000;
};
bool ENCODER::write(int16_t initPos) {
if ((initPos >= min_pos) && (initPos <= max_pos)) {
pos = initPos;
return true;
}
return false;
}
void ENCODER::reset(int16_t initPos, int16_t low, int16_t upp, byte inc, byte fast_inc, bool looped) {
min_pos = low; max_pos = upp;
if (!write(initPos)) initPos = min_pos;
increment = fast_increment = inc;
if (fast_inc > increment) fast_increment = fast_inc;
is_looped = looped;
}
void ENCODER::cnangeINTR(void) { // Interrupt function, called when the channel A of encoder changed
bool rUp = digitalRead(mPIN);
unsigned long now_t = millis();
if (!rUp) { // The channel A has been "pressed"
if ((pt == 0) || (now_t - pt > overPress)) {
pt = now_t;
channelB = digitalRead(sPIN);
}
} else {
if (pt > 0) {
byte inc = increment;
if ((now_t - pt) < overPress) {
if ((now_t - changed) < fast_timeout) inc = fast_increment;
changed = now_t;
if (channelB) pos -= inc; else pos += inc;
if (pos > max_pos) {
if (is_looped)
pos = min_pos;
else
pos = max_pos;
}
if (pos < min_pos) {
if (is_looped)
pos = max_pos;
else
pos = min_pos;
}
}
pt = 0;
}
}
}
//------------------------------------------ class lcd DSPLay for soldering iron -----------------------------
class DSPL : protected LiquidCrystal {
public:
DSPL(byte RS, byte E, byte DB4, byte DB5, byte DB6, byte DB7) : LiquidCrystal(RS, E, DB4, DB5, DB6, DB7) { }
void init(void);
void clear(void) { LiquidCrystal::clear(); }
void tSet(uint16_t t, bool celsuis); // Show the temperature set
void tCurr(uint16_t t); // Show The current temperature
void pSet(byte p); // Show the power set
void timeToOff(byte sec); // Show the time to automatic off the iron
void msgNoIron(void); // Show 'No iron' message
void msgReady(void); // Show 'Ready' message
void msgWorking(void); // Show 'Working' message
void msgOn(void); // Show 'On' message
void msgOff(void); // Show 'Off' message
void msgCold(void); // Show 'Cold' message
void msgFail(void); // Show 'Fail' message
void msgTune(void); // Show 'Tune' message
void msgCelsius(void); // Show 'Cels.' message
void msgFarneheit(void); // Show 'Faren.' message
void msgDefault(); // Show 'default' message (load default configuratuin)
void msgCancel(void); // Show 'cancel' message
void msgApply(void); // Show 'save message'
void setupMode(byte mode, byte p = 0); // Show the configureation mode [0 - 2]
void percent(byte Power); // Show the percentage
private:
bool full_second_line; // Whether the second line is full with the message
};
void DSPL::init(void) {
LiquidCrystal::begin(8, 2);
LiquidCrystal::clear();
full_second_line = false;
}
void DSPL::tSet(uint16_t t, bool celsius) {
char buff[5];
char units = 'C';
if (!celsius) units = 'F';
LiquidCrystal::setCursor(0, 0);
sprintf(buff, "%3d%c", t, units);
LiquidCrystal::print(buff);
}
void DSPL::tCurr(uint16_t t) {
char buff[4];
LiquidCrystal::setCursor(0, 1);
if (t < 1000) {
sprintf(buff, "%3d", t);
} else {
LiquidCrystal::print(F("xxx"));
return;
}
LiquidCrystal::print(buff);
if (full_second_line) {
LiquidCrystal::print(F(" "));
full_second_line = false;
}
}
void DSPL::pSet(byte p) {
char buff[6];
sprintf(buff, "P:%3d", p);
LiquidCrystal::setCursor(0, 0);
LiquidCrystal::print(buff);
}
void DSPL::timeToOff(byte sec) {
char buff[5];
sprintf(buff, " %3d", sec);
LiquidCrystal::setCursor(4, 0);
LiquidCrystal::print(buff);
}
void DSPL::msgNoIron(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F("no iron "));
full_second_line = true;
}
void DSPL::msgReady(void) {
LiquidCrystal::setCursor(4, 0);
LiquidCrystal::print(F(" rdy"));
}
void DSPL::msgWorking(void) {
LiquidCrystal::setCursor(4, 0);
LiquidCrystal::print(F(" wrk"));
}
void DSPL::msgOn(void) {
LiquidCrystal::setCursor(4, 0);
LiquidCrystal::print(F(" ON"));
}
void DSPL::msgOff(void) {
LiquidCrystal::setCursor(4, 0);
LiquidCrystal::print(F(" OFF"));
}
void DSPL::msgCold(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F(" cold "));
full_second_line = true;
}
void DSPL::msgFail(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F(" Failed "));
}
void DSPL::msgTune(void) {
LiquidCrystal::setCursor(0, 0);
LiquidCrystal::print(F("Tune"));
}
void DSPL::msgCelsius(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F("Celsius "));
}
void DSPL::msgFarneheit(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F("Faren. "));
}
void DSPL::msgDefault() {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F(" default"));
}
void DSPL::msgCancel(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F(" cancel "));
}
void DSPL::msgApply(void) {
LiquidCrystal::setCursor(0, 1);
LiquidCrystal::print(F(" save "));
}
void DSPL::setupMode(byte mode, byte p) {
char buff[5];
LiquidCrystal::clear();
LiquidCrystal::print(F("setup"));
LiquidCrystal::setCursor(1,1);
switch (mode) {
case 0:
LiquidCrystal::print(F("off:"));
if (p > 0) {
sprintf(buff, "%2dm", p);
LiquidCrystal::print(buff);
} else {
LiquidCrystal::print(" NO");
}
break;
case 1:
LiquidCrystal::print(F("units"));
LiquidCrystal::setCursor(7, 1);
if (p)
LiquidCrystal::print("C");
else
LiquidCrystal::print("F");
break;
case 2:
LiquidCrystal::print(F("calib. "));
break;
case 3:
LiquidCrystal::print(F("tune"));
break;
}
}
void DSPL::percent(byte Power) {
char buff[6];
sprintf(buff, " %3d%c", Power, '%');
LiquidCrystal::setCursor(3, 1);
LiquidCrystal::print(buff);
}
//------------------------------------------ class HISTORY ----------------------------------------------------
#define H_LENGTH 16
class HISTORY {
public:
HISTORY(void) { len = 0; }
void init(void) { len = 0; }
bool isFull(void) { return len == H_LENGTH; }
uint16_t last(void);
uint16_t top(void) { return queue[0]; }
void put(uint16_t item); // Put new entry to the history
uint16_t average(void); // calcilate the average value
float dispersion(void); // calculate the math dispersion
float gradient(void); // calculate the gradient of the history values
private:
volatile uint16_t queue[H_LENGTH];
volatile byte len; // The number of elements in the queue
volatile byte index; // The current element position, use ring buffer
};
void HISTORY::put(uint16_t item) {
if (len < H_LENGTH) {
queue[len++] = item;
} else {
queue[index ] = item;
if (++index >= H_LENGTH) index = 0; // Use ring buffer
}
}
uint16_t HISTORY::last(void) {
byte i = H_LENGTH - 1;
if (index)
i = index - 1;
return queue[i];
}
uint16_t HISTORY::average(void) {
uint32_t sum = 0;
if (len == 0) return 0;
if (len == 1) return queue[0];
for (byte i = 0; i < len; ++i) sum += queue[i];
sum += len >> 1; // round the average
sum /= len;
return uint16_t(sum);
}
float HISTORY::dispersion(void) {
if (len < 3) return 1000;
uint32_t sum = 0;
uint32_t avg = average();
for (byte i = 0; i < len; ++i) {
long q = queue[i];
q -= avg;
q *= q;
sum += q;
}
sum += len << 1;
float d = (float)sum / (float)len;
return d;
}
// approfimating the history with the line (y = ax+b) using method of minimum square. Gradient is parameter a
float HISTORY::gradient(void) {
if (len < 2) return 0;
long sx, sx_sq, sxy, sy;
sx = sx_sq = sxy = sy = 0;
for (byte i = 1; i <= len; ++i) {
sx += i;
sx_sq += i*i;
sxy += i*queue[i-1];
sy += queue[i-1];
}
long numerator = len * sxy - sx * sy;
long denominator = len * sx_sq - sx * sx;
float a = (float)numerator / (float)denominator;
return a;
}
//------------------------------------------ class PID algoritm to keep the temperature -----------------------
/* The PID algoritm
* Un = Kp*(Xs - Xn) + Ki*summ{j=0; j<=n}(Xs - Xj) + Kd(Xn - Xn-1),
* Where Xs - is the setup temperature, Xn - the temperature on n-iteration step
* In this program the interactive formulae is used:
* Un = Un-1 + Kp*(Xn-1 - Xn) + Ki*(Xs - Xn) + Kd*(Xn-2 + Xn - 2*Xn-1)
* With the first step:
* U0 = Kp*(Xs - X0) + Ki*(Xs - X0); Xn-1 = Xn;
*/
class PID {
public:
PID(void) {
Kp = 768;
Ki = 40;
Kd = 260;
}
void resetPID(int temp = -1); // reset PID algoritm history parameters
// Calculate the power to be applied
int reqPower(int temp_set, int temp_curr);
int changePID(byte p, int k);
private:
void debugPID(int t_set, int t_curr, long kp, long ki, long kd, long delta_p);
int temp_h0, temp_h1; // previously measured temperature
int temp_diff_iterate; // The temperature difference to start iterate process
bool pid_iterate; // Whether the iterative process is used
long i_summ; // Ki summary multiplied by denominator
long power; // The power iterative multiplied by denominator
long Kp, Ki, Kd; // The PID algorithm coefficients multiplied by denominator
const byte denominator_p = 9; // The common coefficeient denominator power of 2 (9 means divide by 512)
};
void PID::resetPID(int temp) {
temp_h0 = 0;
power = 0;
i_summ = 0;
pid_iterate = false;
if ((temp > 0) && (temp < 1000))
temp_h1 = temp;
else
temp_h1 = 0;
}
int PID::changePID(byte p, int k) {
switch(p) {
case 1:
if (k >= 0) Kp = k;
return Kp;
case 2:
if (k >= 0) Ki = k;
return Ki;
case 3:
if (k >= 0) Kd = k;
return Kd;
default:
break;
}
return 0;
}
int PID::reqPower(int temp_set, int temp_curr) {
if (temp_h0 == 0) {
// When the temperature is near the preset one, reset the PID and prepare iterative formulae
if ((temp_set - temp_curr) < 10) {
if (!pid_iterate) {
pid_iterate = true;
power = 0;
i_summ = 0;
}
}
i_summ += temp_set - temp_curr; // first, use the direct formulae, not the iterate process
power = Kp*(temp_set - temp_curr) + Ki*i_summ;
// If the temperature is near, prepare the PID iteration process
} else {
long kp = Kp * (temp_h1 - temp_curr);
long ki = Ki * (temp_set - temp_curr);
long kd = Kd * (temp_h0 + temp_curr - 2*temp_h1);
long delta_p = kp + ki + kd;
power += delta_p; // power keeped multiplied by denominator!
}
if (pid_iterate) temp_h0 = temp_h1;
temp_h1 = temp_curr;
long pwr = power + (1 << (denominator_p-1)); // prepare the power to delete by denominator, roud the result
pwr >>= denominator_p; // delete by the denominator
return int(pwr);
}
//------------------------- class FastPWM operations using Timer1 on pin D10 at 31250 Hz ----------------------
class FastPWM {
public:
FastPWM() { }
void init(void);
void duty(byte d) { OCR1B = d; }
};
void FastPWM::init(void) {
pinMode(10, OUTPUT); // Use D10 pin for heationg the IRON
digitalWrite(10, LOW); // Switch-off the power
tmr1_count = 0;
iron_off = false;
noInterrupts();
TCNT1 = 0;
TCCR1B = _BV(WGM13); // Set mode as phase and frequency correct pwm, stop the timer
TCCR1A = 0;
ICR1 = 256;
TCCR1B = _BV(WGM13) | _BV(CS10); // Top value = ICR1, prescale = 1; 31250 Hz
TCCR1A |= _BV(COM1B1); // XOR D10 on OC1B, detached from D09
OCR1B = 0; // Switch-off the signal on pin D10;
TIMSK1 = _BV(TOIE1); // Enable overflow interrupts @31250 Hz
interrupts();
}
//------------------------------------------ class soldering iron ---------------------------------------------
class IRON : protected PID {
public:
IRON(byte heater_pin, byte sensor_pin) {
hPIN = heater_pin;
sPIN = sensor_pin;
on = false;
fix_power = false;
no_iron = true;
}
void init(void);
void switchPower(bool On);
bool isOn(void) { return on || fix_power; }
bool noIron(void) { return no_iron; }
uint16_t getTemp(void) { return temp_set; }
uint16_t getCurrTemp(void) { return h_temp.last(); }
uint16_t tempAverage(void) { return h_temp.average(); }
uint16_t tempDispersion(void) { return h_temp.dispersion(); }
uint16_t powerDispersion(void) { return h_power.dispersion(); }
byte getMaxFixedPower(void) { return max_fixed_power; }
int changePID(byte p, int k) { return PID::changePID(p, k); }
void setTemp(uint16_t t); // Set the temperature to be keeped
byte getAvgPower(void); // Average applied power
byte appliedPower(void); // Power applied to the solder [0-100%]
byte hotPercent(void); // How hot is the iron (used in the idle state)
void checkIron(void); // Check the IRON, stop it in case of emergency
void keepTemp(void); // Keep the IRON temperature, called by Timer1 interrupt
bool fixPower(byte Power); // Set the specified power to the the soldering iron
private:
FastPWM fastPWM; // Power the IRON using fast PWM through D10 pin using Timer1
uint32_t check_ironMS; // Milliseconds when to check the IRON is connected
byte hPIN, sPIN; // The heater PIN and the sensor PIN
int power; // The soldering station power
byte actual_power; // The power supplied to the iron
bool fix_power; // Whether the soldering iron is set the fix power
uint16_t temp_set; // The temperature that should be keeped
bool iron_checked; // Whether the iron works
uint16_t temp_start; // The temperature when the solder was switched on
uint32_t elapsed_time; // The time elipsed from the start (ms)
uint16_t temp_min; // The minimum temperature (180 centegrees)
volatile bool on; // Whether the soldering iron is on
volatile bool no_iron; // Whether the iron is connected
volatile bool chill; // Whether the IRON should be cooled (preset temp is lower than current)
uint16_t temp_max; // The maximum temperature (400 centegrees)
HISTORY h_power;
HISTORY h_temp;
const uint16_t temp_no_iron = 980; // Sensor reading when the iron disconnected
const byte max_power = 180; // maximum power to the iron (220)
const byte max_fixed_power = 120; // Maximum power in fiexed power mode
const uint16_t check_time = 10000; // Time in ms to check Whether the solder is heating
const uint16_t heat_expected = 10; // The iron should change the temperature at check_time
const uint32_t check_iron_ms = 1000; // The period in ms to check Whether the IRON is conected
};
void IRON::setTemp(uint16_t t) {
if (on) resetPID();
temp_set = t;
uint16_t ta = h_temp.average();
chill = (ta > t + 5); // The IRON must be cooled
}