Skip to content

Soldering Station

Status: Almost complete and being used

I built it on August of 2018. As of now (April of 2020) still using it for my soldering works since then, though it misses two features I originally planned.

TODO

  • Post photos
  • Schematic
  • Microcontroller (Arduino) program
  • Document features, working and things left to implement.

Schematic

Please click on these images to see them enlarged. You may zoom them as much you want as they are vector (SVG) images.

Power Supply Required

Main Power Supply

We need 24VDC power supply of at least 55 watts. Soldering Iron will consume about 50 watts. I used 24V 120 watts SMPS power supply.

Power Supply for Arduino and Control Circuits

We need an additional buck converter to convert the 24V supply down to 6.5V to power the Arduino. I used LM2596 based buck converter board brought from AliExpress. Please note it needs to be connected to RAW power input pin of Arduino. Connecting 6.5V supply to Arduino's 5V will damage it.

Some Explanations for the Circuit

I organized the whole circuit into multiple sub divisions for easy handling. I will explain them separate for easy understanding.

Microcontroller Unit (MCU)

I used Arduino Pro Mini running with 16MHz clock. It has MF58 NTC to measure room temperature, which is require to measure correct temperature of soldering iron. Resistor NR1 is used to form a voltage divider with NTC. The resistor of same value of NTC, 10K, is used. The NTC resistance will be changed depending on room temperature, the voltage drop is calculated with analog input put A0. Please refer readRoomTemperature() function in the program for the logic I used to convert the voltage drop to temperature.

It also has a buzzer with NPN transistor to drive it. However, it did not work well and I did not try much on it either.

Power Saving

Please note that it has provision for input marked with "REED SWITCH". It was designated to help detect placing of soldering iron on stand. The information is planned to use to save power by reducing or by cutting supply to iron depending on duration of iron in stand.

I already included the feature in program. However, I could not implement it hardware level. It requires me to have soldering iron stand having some sort of sensor to detect presence of iron in stand.

I think Infra-Red LED with detector would most suitable for this.

My initial idea was to use Reed switch with a magnet attached on stand, but I found Reed switches are not that reliable from my tests. Also it required me to modify soldering iron unit to incorporate Reed switch. There are two problems with that. First, I need to place Reed switch near to heating element, which of course will fail eventually because of the heat. Second, I need to incorporate an extra wire for Reed switch signal. Standard Hakko 9000M style soldering iron has 5 wires and all already used. So, I would be require to change the cable to incorporate extra wire and I cannot directly use standard soldering irons in that case.

I hope, one day I will include this feature in my station. Probably with IR LED as mentioned above.

Input De-bouncing

This part is used to interface with the buttons and rotary encoder. This is not really necessary to have this part. But it helps to improve microcontroller performance by handling imperfections of contacts within buttons and rotary encoder. Otherwise microcontroller would get interrupted multiple times in each button press.

74HC14 IC is used here, which is Schmitt-Trigger Inverter.

MOSFET Driver

This part is used to provide PWM signal to gate of MOSFET. This part is also not necessary to have as default PWM frequency of Arduino is under 1KHz (490 Hz and 980 Hz depending on pins in Arduino Uno/Mini/Nano). We can just use 330Ω or 470Ω resistors to replace it. However I wanted to try a MOSFET driver. I chose circuit design from Figure 4 in Tahmid'd blog post "Low-Side MOSFET Drive Circuits and Techniques - 7 Practical Circuits".

Thermocouple Amplifier

Thermocouple within the soldering iron produce certain amounts of voltage in milli volt range depending on its temperature. That is too little and cannot be read by Arduino directly. This thermocouple amplifier amplifies the signals from thermocouple to suitable level for the Arduino to read.

It has two stages, both configured in non-inverting way. Gain of first stage is:

Similarly, gain of second stage is:

Thus total gain will be:

There are reasons for me to set the gain as 161. I planned to drive soldering iron up to 600°C. A K Type Thermocouple will produce 24.905mV at 600°C. Multiplied by the gain, it will become 4V. Supply voltage for op-amp will be 5V. Amplifying signal near to supply voltage is not good idea unless it is rail-rail op-amp.

Two Zener diodes ZD1 and ZD2 are to protect op-amps and microcontroller, in case if thermocouple wire touch 24V supply line to the heating element.

Resistor TCR1 and capacitor TCC1 together forms low pass filter. Without them, thermocouple reading will jump frequently.

Op-Amp Selection

We should choose op-amps suitable for reading very small signals. Those usually marked as "Instrumentation Amplifiers". They allow to set gain from 1 to 10,000 with single resistor and will have very low input offset voltage. Popular choices in that category are INA128 from Texas Instruments and AD620 from Analog Devices. However, they are expensive, usually has cost 10 times as much as normal op-amps. I had tried purchasing INA128 once, but seller did not deliver it as it went out of stock.

After further research on Internet, I chose OP07C for the job. It has low input voltage offset, with maximum of 60μV.

Program

The program developed for Arduino is given below. Please note it was originally written to support multiple soldering irons. So, you may encounter some constructs indicating iron number. I did not remove them.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
#include <PinChangeInterrupt.h>
#include <PinChangeInterruptBoards.h>
#include <PinChangeInterruptPins.h>
#include <PinChangeInterruptSettings.h>

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>

int16_t EEPROMReadInt16bit(int address) {
  int16_t lsb = EEPROM.read(address);
  int16_t msb = EEPROM.read(address+1);
  return ( (lsb << 0) & 0xFF) + ( (msb << 8) & 0xFFFF);
}

void EEPROMWriteInt16bit(int address, int16_t value) {
  uint8_t lsb = (value & 0xFF);
  uint8_t msb = ((value >> 8) & 0xFF);
  EEPROM.write(address, lsb);
  EEPROM.write(address + 1, msb);
}

/**
 * To create objects helping to execute code by a specified interval.
 */
class TimeDivision {
  /**
   * Last time the code is executed by this time division.
   */
  unsigned long last_time;

  public:
  /**
   * Initialize by passing the gap required
   */
  TimeDivision(uint16_t gap) {
    this->last_time = 0;
  }

  /*
   * Tells if this is time to execute.
   */
  bool isTimeToExecute(uint16_t time_gap) {
    return (bool)((millis() - this->last_time) >= time_gap);
  }

  /**
   * Set the gap start time to now.
   */
  void set() {
    this->last_time = millis();
  }
};

/**
 * Address to 2 byte storage.
 */
#define IRON_TEMPERATURE_STORAGE_ADDRESS 0

/**
 * Configurable data associate with an iron which can be saved in EEPROM
 */
struct IronData {
  int16_t temperature;
};

/**
 * Minimum PWM signal.
 */
const int MINIMUM_POWER = 0;
/**
 * Maximum PWM signal.
 */
const int MAXIMUM_POWER = 255;

/**
 * Minimum temperature allowed, so user cannot go below it.
 */
#define MINIMUM_TEMPERATURE 0.0
/**
 * Maximum temperature allowed, so user cannot go above it.
 */
#define MAXIMUM_TEMPERATURE 550.0
/**
 * Increment/decrement step to use when turning rotary encoder.
 */
#define TEMPERATURE_INCREMENT_STEP 1

/**
 * Time interval to update display
 */
#define DISPLAY_REFRESH_TIME 500

/**
 * Time interval to refresh irons.
 */
#define IRON_REFRESH_TIME 250

class PIDController {
  public:
  /** Proportional **/
  float Kp = 4;

  /** Integral **/
  float Ki = 0.2;

  /** Derivative **/
  float Kd = 1.0;

  /**
   * Previous error so it can be used in next calculation.
   */
  float last_error = 0.0;

  /**
   * Integration error.
   */
  float i_error = 0.0;

  float last_input = 0.0;

  float outputSum = 0.0;

  /**
   * Time when previous calculations are made.
   */
  unsigned long last_time = 0;

  PIDController() {
    // Ensure PID controller is in reset state.
    this->reset();
  }

  /**
   * Reset PID controller.
   */
  void reset() {
    this->last_time = millis();
    this->i_error = 0.0;
    this->last_error = 0.0;

    this->last_input = 0.0;
    this->outputSum = 0.0;
  }

  /**
   * Perform PID calculation and give the result.
   *
   * @param float current_temperature
   *  Current temperature on iron tip.
   * @param float target_temperature
   *  Temperature to be maintained at iron tip.
   */
  int getChange(float current_temperature, float target_temperature) {
    unsigned long now = millis();
    // Change in time.
    unsigned long dt = now - this->last_time;
    // Proportional
    float p_error = target_temperature - current_temperature;
    // Integral
    this->i_error += ( p_error + this->last_error ) * (float) dt;
    // Derivative
    float d_error = (p_error - this->last_error) / (float) dt;
    // PID output = Proportional gain x current error + Integral gain * past error + Derivative gain x future error
    int output = (int)(((float) this->Kp * p_error) + ((float) this->Ki * this->i_error) + ((float) this->Kd * d_error));

    // Record current error
    this->last_error = p_error;
    // Record current time
    this->last_time = now;
    return output;
  }

  /**
   * PID algorithm implementation taken from Arduino
   * PID library: https://github.com/br3ttb/Arduino-PID-Library/blob/9b4ca0e5b6d7bab9c6ac023e249d6af2446d99bb/PID_v1.cpp#L58
   */
  int compute(float current_temperature, float target_temperature) {
    float output = current_temperature;
    unsigned long now = millis();
    unsigned long timeChange = (now - this->last_time);
    // Compute all the working error variables
    double error = target_temperature - current_temperature;
    double dInput = (current_temperature - this->last_input);
    this->outputSum+= (this->Ki * error);

    // Add Proportional on Measurement.
    this->outputSum-= this->Kp * dInput;

    if(this->outputSum > MAXIMUM_POWER) {
      this->outputSum = MAXIMUM_POWER;
    }
    else if(this->outputSum < MINIMUM_POWER) {
      this->outputSum = MINIMUM_POWER;
    }

    double new_output;
    new_output = this->Kp * error;

    /*Compute Rest of PID Output*/
    new_output += this->outputSum - this->Kd * dInput;

    if(new_output > MAXIMUM_POWER) {
      new_output = MAXIMUM_POWER;
    }
    else if(new_output < MINIMUM_POWER) {
      new_output = MINIMUM_POWER;
    }

    /*Remember some variables for next time*/
    this->last_input = current_temperature;
    this->last_time = now;
    return (int) new_output;
  }
};


/**
 * Iron is not in use and not powered.
 */
#define IRON_STATE_STOPPED 0
/**
 * Iron is in low temperature mode.
 */
#define IRON_STATE_STANDBY 1
/**
 * User has put iron on holder after use.
 */
#define IRON_STATE_ON_HOLDER 2
/**
 * Iron is being actively used.
 */
#define IRON_STATE_ACTIVE 3

/**
 * Maximum time in milliseconds an iron can be in standby mode.
 * On expire, iron will be powered off.
 */
#define MAXIMUM_STANDBY_TIME 10000
/**
 * Maximum time in milliseconds an iron can be in on holder with its set temperature..
 * On expire, iron will be put in stand by mode.
 */
#define MAXIMUM_ON_HOLDER_TIME 10000

///*** IRON 1 CONNECTED PINS ***/////
/**
 * Arduino pin connected to iron stop button.
 */
#define IRON0_STOP_BUTTON 2

/**
 * Arduino pin connected to iron start button.
 */
#define IRON0_START_BUTTON 3

/**
 * Arduino pin connected to iron reed switch.
 */
#define IRON0_REED_SWITCH_PIN 4

/**
 * Arduino pin connected to iron heating element control.
 */
#define IRON0_HEATER_CONTROL_PIN 5

/**
 * Arduino pin connected to iron thermocouple amplified output.
 */
#define IRON0_THERMOCOUPLE_READING_PIN A6


// Pin connected to NTC thermistor.
#define NTC_THERMISTOR_PIN A0


/**
 * Data tables for computing temperature from thermocouple voltage readings.
 * @see https://srdata.nist.gov/its90/download/type_k.tab
 */
float thermocouple_k_tab1[] = {
    0.0000000E+00,
    2.5173462E+01,
    -1.1662878E+00,
    -1.0833638E+00,
    -8.9773540E-01,
    -3.7342377E-01,
    -8.6632643E-02,
    -1.0450598E-02,
    -5.1920577E-04,
    0.0000000E+00,
};
float thermocouple_k_tab2[] = {
    0.000000E+00,
    2.508355E+01,
    7.860106E-02,
    -2.503131E-01,
    8.315270E-02,
    -1.228034E-02,
    9.804036E-04,
    -4.413030E-05,
    1.057734E-06,
    -1.052755E-08,
};
float thermocouple_k_tab3[] = {
    -1.318058E+02,
    4.830222E+01,
    -1.646031E+00,
    5.464731E-02,
    -9.650715E-04,
    8.802193E-06,
    -3.110810E-08,
    0.000000E+00,
    0.000000E+00,
    0.000000E+00,
};

/**
 * Get room temperature.
 * @return float
 */
float readRoomTemperature() {
  // See http://www.circuitbasics.com/arduino-thermistor-temperature-sensor-tutorial/
  int adc = analogRead(NTC_THERMISTOR_PIN);
  // TODO: Ensure resistance is 10K for both resistor and thermistor.
  float ntc_resistance = 10000.0 * (1024.0 / (float)adc - 1.0);

  // Calculate temperature with B parameter equation:
  // https://en.wikipedia.org/wiki/Thermistor#B_or_%CE%B2_parameter_equation
  // T = 1 / ( 1/ T0 + 1/B log(R/R0)
  // Need to deduct 273.15 since equation calculation is in Kelvin.
  return 1 / ( (1/298.15) + (1/3950.0) * log(ntc_resistance/ 10000.0)) - 273.15;
}

/**
 * Class representing soldering iron.
 */
class Iron {
  public:
    /**
     * Iron index.
     */
    uint8_t iron_number;

    /**
     * Pin to which PWM signal for heater element to be applied.
     */
    uint8_t heater_control_pin;

    /**
     * Analog input pin in which we will read amplified signal from thermocouple.
     */
    uint8_t thermoucouple_reading_pin;

    /**
     * Digital input pin in which reed switch is connected.
     */
    uint8_t reed_input_pin;

    /**
     * Digital input pin where start button for the iron is connected.
     */
    uint8_t start_button_pin;

    /**
     * Digital input pin where start button for the iron is connected.
     */
    uint8_t stop_button_pin;

    /**
     * Current temperature to be maintained on tip.
     */
    float target_temperature;

    /**
     * Temperature to be maintained on tip while iron is in active state.
     */
    float set_temperature;

    /**
     * Indicates whether set_temperature value is changes since it is stored in storage.
     */
    bool set_temperature_changed = false;

    /**
     * Timestamp when set_temperature changed.
     */
    unsigned long set_temperature_changed_time = 0;

    /**
     * Iron's current state.
     * Initially all irons will be in stopped state.
     */
    uint8_t state = IRON_STATE_STOPPED;

    /**
     * Starting time of active state.
     */
    unsigned long state_start_time = 0;

    /**
     * Current PWM signal being applied to iron.
     * Initially no power will be applied.
     */
    int power = 0;

    /**
     * Current state of Reed switch.
     */
    uint8_t reed_state = 0;

    /**
     * PID controller for the iron.
     */
    PIDController* pid_controller = NULL;

    /**
     * heater_control_pin - PWM pin
     * thermoucouple_reading_pin - Analog input pin
     * reed_input_pin - Digital pin
     * start_button_pin - Digital pin
     * stop_button_pin - Digital pin
     */
    Iron(uint8_t iron_number, uint8_t heater_control_pin, uint8_t thermoucouple_reading_pin, uint8_t reed_input_pin, uint8_t start_button_pin, uint8_t stop_button_pin) {
      this->iron_number = iron_number;
      this->heater_control_pin = heater_control_pin;
      this->thermoucouple_reading_pin = thermoucouple_reading_pin;
      this->reed_input_pin = reed_input_pin;
      this->start_button_pin = start_button_pin;
      this->stop_button_pin = stop_button_pin;
      this->target_temperature = 0.0;
      // It will be overwritten by saved value.
      this->set_temperature = 250;
    }

    /**
     * Initialize iron on device start.
     */
    void init() {
      pinMode(this->heater_control_pin, OUTPUT);
      pinMode(this->reed_input_pin, INPUT_PULLUP);
      pinMode(this->start_button_pin, INPUT_PULLUP);
      pinMode(this->stop_button_pin, INPUT_PULLUP);
      this->pid_controller = new PIDController();
      // Get current status of Reed switch.
      this->reed_state = digitalRead(this->reed_input_pin);
      this->readTemperatureSetting();
      // Ensure iron is stopped initially.
      this->stop();
    }

    /**
     * Get temperature stored in permanence storage.
     */
    void readTemperatureSetting () {
      int address = IRON_TEMPERATURE_STORAGE_ADDRESS + this->iron_number;
      this->set_temperature = EEPROMReadInt16bit(address);
      // Make sure read temperature is within the allowed range.
      if (this->set_temperature > MAXIMUM_TEMPERATURE) {
        this->set_temperature = MAXIMUM_TEMPERATURE;
      }
      else if (this->set_temperature < MINIMUM_TEMPERATURE) {
        this->set_temperature = MINIMUM_TEMPERATURE;
      }
    }

    /**
     * Store temperature in permanence storage.
     */
    void writeTemperatureSetting () {
      int address = IRON_TEMPERATURE_STORAGE_ADDRESS + this->iron_number;
      EEPROMWriteInt16bit(address, this->set_temperature);
    }

    /**
     * Stop iron.
     */
    void stop() {
      this->power = 0;
      // Immediately cut power to iron.
      this->applyPower();

      this->pid_controller->reset();

      this->state = IRON_STATE_STOPPED;
      this->state_start_time = millis();
    }

    /**
     * Change state of the iron.
     */
    void setState(uint8_t new_state) {
      this->state = new_state;
      this->state_start_time = millis();
    }

    /**
     * Put iron in low temperature mode.
     */
    void putInStandBy() {
      this->target_temperature = 150;
      this->setState(IRON_STATE_STANDBY);
    }

    /**
     * To be called when user puts iron on holder.
     */
    void putOnHolder() {
      this->target_temperature = this->set_temperature;
      this->setState(IRON_STATE_ON_HOLDER);
    }

    /**
     * Activate iron for soldering.
     */
    void activate() {
      this->target_temperature = this->set_temperature;
      this->setState(IRON_STATE_ACTIVE);
    }

    /**
     * Apply PWM signal to the iron.
     */
    void applyPower() {
      analogWrite(this->heater_control_pin, this->power);
    }

    /**
     * Apply correct PWM signal to the iron.
     */
    void maintainTemperature() {
      //int change = this->pid_controller->getChange(this->readTemperature(), this->target_temperature);
      // Utilize PID controller to calculate the power to be applied.
      //this->power += change;
      this->power = this->pid_controller->compute(this->readTemperature(), this->target_temperature);
      if (this->power > MAXIMUM_POWER) {
        this->power = MAXIMUM_POWER;
      }
      else if (this->power < MINIMUM_POWER) {
        this->power = MINIMUM_POWER;
      }

      this->applyPower();
    }

    /**
     * Read temperature sensor data and identify current tip  temperature.
     */
    float readTemperature() {
      // Read from ADC pin which connected to amplified signal from
      // thermocouple.
      float voltage = analogRead(this->thermoucouple_reading_pin) * (5.0 / 1023.0);
      // 161 is the gain of our OP07C based signal amplifier, ( (2000 Ohm / 100 Ohm) + 1 ) * (1000 Ohm / 150 Ohm) + 1) = 161
      return Iron::thermocouple_k_mv_to_temperature(voltage * 1000 / 161.0) + readRoomTemperature();
    }

    /**
     * Increment the set temperature.
     */
    void incrementSetTemperature() {
      if (this->set_temperature == MAXIMUM_TEMPERATURE) {
        // Just return doing nothing if temperature already maximum.
        return;
      }
      else {
        this->set_temperature += TEMPERATURE_INCREMENT_STEP;
        // Not to set more than allowed.
        if (this->set_temperature > MAXIMUM_TEMPERATURE) {
          this->set_temperature = MAXIMUM_TEMPERATURE;
        }
        // Sync set temperature to target temperature
        // if iron is either active or just put on holder.
        if ( this->state == IRON_STATE_ACTIVE || this->state == IRON_STATE_ON_HOLDER ) {
          this->target_temperature = this->set_temperature;
        }
        this->set_temperature_changed = true;
        this->set_temperature_changed_time = millis();
      }
    }

     /**
     * Decrement the set temperature.
     */
    void decrementSetTemperature() {
      if (this->set_temperature == MINIMUM_TEMPERATURE) {
        // Return doing nothing if temperature is already at minimum.
        return;
      }
      else {
        this->set_temperature -= TEMPERATURE_INCREMENT_STEP;
        // Not to set lower than allowed.
        if (this->set_temperature < MINIMUM_TEMPERATURE) {
          this->set_temperature = MINIMUM_TEMPERATURE;
        }
        // Sync set temperature to target temperature if iron is being actively used.
        if ( this->state == IRON_STATE_ACTIVE || this->state == IRON_STATE_ON_HOLDER ) {
          this->target_temperature = this->set_temperature;
        }

        this->set_temperature_changed = true;
        this->set_temperature_changed_time = millis();
      }
    }

    /**
     * It will get called by ISR listening to Reed switch pin.
     */
    void reedStateChanged() {
      // TODO: Check possibility of direct port read to improve performance: https://jeelabs.org/2010/01/06/pin-io-performance/
      this->reed_state = digitalRead(this->reed_input_pin);
      if (this->reed_state && this->state == IRON_STATE_ACTIVE ) {
        // Reed switch is closed and iron is being used.
        this->putOnHolder();
      }
      else if ( (!this->reed_state) && (this->state == IRON_STATE_ON_HOLDER || this->state == IRON_STATE_STANDBY)) {
        // Reed switch is open and iron is either just put on holder or in stand-by mode.
        this->activate();
      }
    }

    /**
     * Whether the iron is on stand or not.
     */
    bool isOnHolder() {
      return this->reed_state;
    }

    /**
     * Convert thermocouple milli-voltage reading to temperature in Celsius.
     * @see https://srdata.nist.gov/its90/download/type_k.tab
     *
     * @param mv
     *   Voltage in milli-volts.
     * @return float
     *   Temperature in Celsius.
     */
    static float thermocouple_k_mv_to_temperature(float mv) {
      float *c;
      if (mv >= -5.891 && mv <= 0.0) {
        c = thermocouple_k_tab1;
      } else if (mv > 0.0 && mv <= 20.644) {
          c = thermocouple_k_tab2;
      } else if (mv > 20.644 && mv <= 54.886) {
          c = thermocouple_k_tab3;
      } else {
          return -1.0;
      }
      float t = 0.0;
      for (int p = 0; p < 10; p++) {
          t += *(c + p) * pow(mv, p);
      }
      return t;
    }
};

/**
 * Initial heating up of calibration process.
 * User needs to put the thermocouple in contact with iron tip.
 */
#define CALIBRATOR_STATE_INITIAL_HEATING_UP 1
#define CALIBRATOR_STATE_THERMOCOUPLE_SET_UP 2
#define CALIBRATOR_STATE_COOLING 3
#define CALIBRATOR_STATE_FINAL_HEATING 4

#define CALIBRATOR_HEATING_UP_TEMPERATURE 400.0

/**
 * Class holding calibrator logic.
 */
class IronCalibrator {
  public:
    Iron* iron;

    uint8_t state;

    bool user_ready;

    IronCalibrator(Iron* i) {
      this->iron = i;
      this->iron->set_temperature = CALIBRATOR_HEATING_UP_TEMPERATURE;

      this->state = CALIBRATOR_STATE_INITIAL_HEATING_UP;
      this->user_ready = false;

      this->iron->activate();
    }

    void performCalibration() {
      if (this->state == CALIBRATOR_STATE_INITIAL_HEATING_UP) {
        this->iron->maintainTemperature();
        if (this->iron->readTemperature() >= CALIBRATOR_HEATING_UP_TEMPERATURE && this->user_ready) {

        }
      }
    }
};

// Various states of application.
// Irons are being used for soldering.
#define APPLICATION_STATE_USING_IRONS 1
// One or both irons are being calibrated.
#define APPLICATION_STATE_CALIBRATING_IRON 2

// I2C address of the display device.
#define DISPLAY_I2C_ADDRESS 0x3C

// Pin connected to buzzer.
#define BUZZER_PIN 10

#define BEEP_SINGLE_DURATION 50

// Beep codes.
#define BEEP_NOTHING 0
#define BEEP_SINGLE 1
#define BEEP_SINGLE_LONG 2

/**
 * Representation of rotary encoder state.
 */
struct RotaryEncoder {
  bool a_set;
  bool b_set;
};

// Buffer to print one line on LCD.
char buffer[20];

TimeDivision
  // Refresh display by 500 milli seconds.
  display_refresh_time = TimeDivision(500),
  // Process irons in each 250 milli seconds.
  iron_process_time = TimeDivision(250),
  // Time gap between beeps.
  beep_time = TimeDivision(250);



/**
 * Class representing the entire device.
 */
class Application {
  public:
    // TODO: Change once ready.
    static const int number_of_irons = 1;

    Iron* irons[Application::number_of_irons];

    /**
     * Iron currently being configured/set up.
     * First iron will be the one always active initially.
     */
    uint8_t active_iron = 0;

    /**
     * 20x4 character LCD display.
     */
    LiquidCrystal_I2C display = LiquidCrystal_I2C(0x27, 20, 4);

    /**
     * Indicates application state change. Mostly used for clearing display.
     */
    bool state_changed = false;

    /**
     * State of the application/device.
     * Whether iron is being used, calibrated, etc.
     */
    uint8_t state;

    /**
     * Current state of rotary encoder.
     */
    RotaryEncoder rotary_encoder;

    /**
     * Calibrator object.
     * It will be created only as required.
     */
    IronCalibrator* calibrator;

    /**
     * To indicate to issue beep(s).
     */
    uint8_t beep = 0;

    uint8_t beep_stage = 0;


    Application() {
      this->state = APPLICATION_STATE_USING_IRONS;
      this->calibrator = NULL;
    }

    /**
     * Perform station initialization including irons.
     */
    void init() {
      // Initialize first iron.
      this->irons[0] = new Iron(0, IRON0_HEATER_CONTROL_PIN, IRON0_THERMOCOUPLE_READING_PIN, IRON0_REED_SWITCH_PIN, IRON0_START_BUTTON, IRON0_STOP_BUTTON);
      this->irons[0]->init();

      // Make the first iron as active one.
      this->active_iron = 0;

      // Initialize LCD.
      this->display.init();
      this->display.backlight();
    }

    /**
     * Set the active iron being configured or managed.
     */
    void setActiveIron(uint8_t num) {
      this->active_iron = num % 2;
    }

    /**
     * Allow to change application state.
     */
    void setState(uint8_t new_state) {
      this->state = new_state;
      // Display needs to be cleared completely since things on
      // screen are going to change entirely.
      this->state_changed = true;
    }

    /**
     * Show normal front page.
     */
    void displayFrontPage() {
      // Show active iron.
      if (this->number_of_irons == 1) {
        // Show both current and set temperatures.
        this->display.setCursor(0, 0);
        sprintf(buffer,"%03d", round(this->irons[this->active_iron]->readTemperature()));
        this->display.print(buffer);
        sprintf(buffer,"/%03d", round(this->irons[this->active_iron]->set_temperature));
        this->display.print(buffer);
        this->display.print((char)223); // Print degree (°) symbol.
        this->display.print("C");
        if (this->irons[this->active_iron]->set_temperature_changed) {
          this->display.print("*");
        }
        else {
          this->display.print(" ");
        }

        // Show status of the iron.
        this->display.setCursor(0, 1);
        if (this->irons[this->active_iron]->state == IRON_STATE_STOPPED) {
          this->display.print("Stopped  ");
        }
        else if (this->irons[this->active_iron]->state == IRON_STATE_STANDBY) {
          this->display.print("Stand by ");
        }
        else if (this->irons[this->active_iron]->state == IRON_STATE_ON_HOLDER) {
          this->display.print("On holder");
        }
        else {
          this->display.print("Active   ");
        }

        // Show power level being applied to iron.
        this->display.setCursor(0, 2);
        // TODO: Make icon.
        sprintf(buffer,"Power %03d", this->irons[this->active_iron]->power);
        this->display.print(buffer);

        this->display.setCursor(0, 3);
        // TODO: Make icon to show this.
        this->display.print(this->irons[this->active_iron]->reed_state);

      }
    }

    /**
     * Display calibration pages.
     */
    void displayCalibrationPage() {
      if (!this->calibrator) {
        this->display.setCursor(0, 0);
        this->display.print("Ready for Calibration");
        this->display.setCursor(0, 1);
        this->display.print( (char) 126 );
      }
      else {
        if (this->calibrator->state == CALIBRATOR_STATE_INITIAL_HEATING_UP) {
          this->display.setCursor(0, 0);
          this->display.print("Heating up...");
          this->display.setCursor(0, 1);
          this->display.println("Iron tip is heating up");
//          this->display.println("Put solder on tip and");
//          this->display.println("place thermocouple in");
//          this->display.println("contact.");
//          this->display.println("Press iron start butt-");
//          this->display.println("on when ready.");
        }
      }
    }

    /**
     * Show the correct screen.
     */
    void render() {
      // Refresh screen as necessary.
      if ( display_refresh_time.isTimeToExecute(DISPLAY_REFRESH_TIME) ) {
        if (this->state_changed) {
          this->display.clear();
          this->state_changed = false;
        }
        if (this->state == APPLICATION_STATE_USING_IRONS) {
          this->displayFrontPage();
        }
        else if (this->state == APPLICATION_STATE_CALIBRATING_IRON) {
          this->displayCalibrationPage();
        }
      }
    }

    /**
     * This function will be called continuously while irons are being used.
     */
    void processIrons() {
      if (iron_process_time.isTimeToExecute(IRON_REFRESH_TIME)) {
        if (this->state == APPLICATION_STATE_USING_IRONS) {
          unsigned long time_now = millis();
          for (int i = 0; i < Application::number_of_irons; i++) {
            switch (this->irons[i]->state) {

              case IRON_STATE_STOPPED:
                // TODO: What to do with stopped iron?
                break;

              case IRON_STATE_STANDBY:
                if ( ( time_now - this->irons[i]->state_start_time ) >= MAXIMUM_STANDBY_TIME ) {
                  // Iron spend enough time in stand by mode.
                  // Let's turn it off to save power and for safety.
                  this->irons[i]->stop();
                }
                else {
                  this->irons[i]->maintainTemperature();
                }
                break;

              case IRON_STATE_ON_HOLDER:
                if ( ( time_now - this->irons[i]->state_start_time ) >= MAXIMUM_ON_HOLDER_TIME ) {
                  // Iron spend enough time in on holder mode.
                  // Let's put it in stand by mode with reduced heating.
                  this->irons[i]->putInStandBy();
                }
                else {
                  this->irons[i]->maintainTemperature();
                }
                break;

              case IRON_STATE_ACTIVE:
              default:
                this->irons[i]->maintainTemperature();
                break;
            }

            // Save set temperature if user changed it.
            // It is delayed saving to avoid writing continuously to EEPROM
            // which may shorten its lifetime.
            if (this->irons[i]->set_temperature_changed && ( (time_now - (this->irons[i]->set_temperature_changed_time)) > 10000)) {
              this->irons[i]->writeTemperatureSetting();
              this->irons[i]->set_temperature_changed = false;
            }
          }
        }
        else if (this->state == APPLICATION_STATE_CALIBRATING_IRON){
          if (this->calibrator) {
            this->calibrator->performCalibration();
          }
        }
      }
    }

    /**
     * Process requests to make beeps.
     */
    void makeBeep() {
      switch (this->beep) {
      case BEEP_SINGLE:
        // Handle single beep.
        if (this->beep_stage == 0) {
          digitalWrite(BUZZER_PIN, HIGH);
          this->beep_stage++;
          beep_time.set();
        }
        // Stop the beep if met the duration limit.
        else if (this->beep_stage == 1 && beep_time.isTimeToExecute(BEEP_SINGLE_DURATION)) {
          digitalWrite(BUZZER_PIN, LOW);
          this->beep_stage--;
          // Finished handling the beep so reset beep to BEEP_NOTHING
          this->beep = BEEP_NOTHING;
        }
        break;
      case BEEP_NOTHING:
      default:
        break;
      }
    }

    /**
     * It will get called when rotary encoder being turned clock wise direction.
     */
    void rotaryEncoderTurningClockwise() {
      if (this->state == APPLICATION_STATE_USING_IRONS) {
        this->irons[this->active_iron]->incrementSetTemperature();
      }
    }

    /**
     * It will get called when rotary encoder being turned anti-clock wise direction.
     */
    void rotaryEncoderTurningAntiClockwise() {
      if (this->state == APPLICATION_STATE_USING_IRONS) {
        this->irons[this->active_iron]->decrementSetTemperature();
      }
    }

    /**
     * It will get called by ISR when rotary encoder button is pressed.
     */
    void rotaryEncoderButtonPressed() {
      if ( this->state == APPLICATION_STATE_USING_IRONS ) {
        this->setState(APPLICATION_STATE_CALIBRATING_IRON);
        // TODO: Make it to render changes immediately.
      }
      else if (this->state == APPLICATION_STATE_CALIBRATING_IRON) {
        this->setState(APPLICATION_STATE_USING_IRONS);
      }
    }

    /**
     * It will get called by ISR when start button is pressed.
     */
    void ironStartButtonPressed(uint8_t iron_num) {
      if (this->state == APPLICATION_STATE_USING_IRONS) {
        // Make iron active if it is not already.
        if (this->active_iron != iron_num) {
          this->active_iron = iron_num;
        }
        else if (this->irons[iron_num]->state == IRON_STATE_STOPPED ) {
          if (this->irons[iron_num]->isOnHolder()) {
            // Iron is stopped and on stand.
            // Thus make iron as user just put on stand.
            // So it will become in stand by mode and not heated fully.
            this->irons[iron_num]->putInStandBy();
          }
          else {
            // Iron is not in stand.
            // Thus make iron ready for soldering.
            this->irons[iron_num]->activate();
          }
        }
        else if (this->irons[iron_num]->state == IRON_STATE_STANDBY ) {
          // Iron is in stand by mode and user wants to heat it for soldering.
          // Make as if iron is just put on stand.
          this->irons[iron_num]->putOnHolder();
        }
      }

      else if (this->state == APPLICATION_STATE_CALIBRATING_IRON) {
        if (!this->calibrator) {
          this->calibrator = new IronCalibrator(this->irons[iron_num]);
        }
      }
    }

    /**
     * It will get called by ISR when stop button is pressed.
     */
    void ironStopButtonPressed(uint8_t iron_num) {
      if (this->state == APPLICATION_STATE_USING_IRONS) {
        if (
            this->irons[iron_num]->state == IRON_STATE_ACTIVE ||
            this->irons[iron_num]->state == IRON_STATE_STANDBY
        ) {
          // Always stop iron.
          this->irons[iron_num]->stop();
        }
      }
    }
};

/**
 * Arduino pin connected to rotary encoder pin A.
 */
#define ROTARY_ENCODER_PIN_A 7  // PORTD 7

/**
 * Arduino pin connected to rotary encoder pin B.
 */
#define ROTARY_ENCODER_PIN_B 6  // PORTD 6

/**
 * Arduino pin connected to rotary encoder button.
 */
#define ROTARY_ENCODER_BUTTON 8

// One and only application object.
Application app = Application();

///<--- Interrupt Service Routines (ISRs) --->///

/**
 * ISR for rotary encoder pin a
 */
void do_encoder_a() {
  // Low to High transition?
  // TODO: Check possibility of direct port read to improve performance: https://jeelabs.org/2010/01/06/pin-io-performance/
  //if (digitalRead(ROTARY_ENCODER_PIN_A) == HIGH) {
  if (bitRead(PIND, 7)) {
    app.rotary_encoder.a_set = true;
    if (!app.rotary_encoder.b_set) {
      // Rotating anti-clockwise.
      app.rotaryEncoderTurningAntiClockwise();
    }
  }

  // High-to-low transition?
  // TODO: Check possibility of direct port read to improve performance: https://jeelabs.org/2010/01/06/pin-io-performance/
  //if (digitalRead(ROTARY_ENCODER_PIN_A) == LOW) {
  else {
    app.rotary_encoder.a_set = false;
  }
}

/**
 * ISR for rotary encoder pin a
 */
void do_encoder_b() {
  // Low-to-high transition?
  // TODO: Check possibility of direct port read to improve performance: https://jeelabs.org/2010/01/06/pin-io-performance/
  //if (digitalRead(ROTARY_ENCODER_PIN_B) == HIGH) {
  if (bitRead(PIND, 6)) {
    app.rotary_encoder.b_set = true;
    if (!app.rotary_encoder.a_set) {
      // Rotating Clockwise.
      app.rotaryEncoderTurningClockwise();
    }
  }

  // High-to-low transition?
  // TODO: Check possibility of direct port read to improve performance: https://jeelabs.org/2010/01/06/pin-io-performance/
  //if (digitalRead(ROTARY_ENCODER_PIN_B) == LOW) {
  else {
    app.rotary_encoder.b_set = false;
  }
}

/**
 * Interrupt service routine.
 * Rotary encode button has been pressed.
 */
void rotary_encoder_button_pressed() {
  app.rotaryEncoderButtonPressed();
}

/**
 * ISR processing iron0 start button event.
 */
void iron0_start_button_pressed() {
  app.ironStartButtonPressed(0);
}

/**
 * ISR processing iron0 stop button event.
 */
void iron0_stop_button_pressed() {
  app.ironStopButtonPressed(0);
}

/**
 * ISR processing iron0 reed switch state change.
 */
void iron0_reed_switch_state_changed() {
  app.irons[0]->reedStateChanged();
}

/**
 * Set up device for operation.
 */
void setup() {
  // Digital pins for rotary encoder
  pinMode(ROTARY_ENCODER_PIN_A, INPUT);
  pinMode(ROTARY_ENCODER_PIN_B, INPUT);
  pinMode(ROTARY_ENCODER_BUTTON, INPUT);
  attachPCINT(digitalPinToPCINT(ROTARY_ENCODER_PIN_A), do_encoder_a, CHANGE);
  attachPCINT(digitalPinToPCINT(ROTARY_ENCODER_PIN_B), do_encoder_b, CHANGE);
  attachPCINT(digitalPinToPCINT(ROTARY_ENCODER_BUTTON), rotary_encoder_button_pressed, RISING);

  pinMode(IRON0_START_BUTTON, INPUT_PULLUP);
  pinMode(IRON0_STOP_BUTTON, INPUT_PULLUP);
  pinMode(IRON0_REED_SWITCH_PIN, INPUT_PULLUP);
  attachPCINT(digitalPinToPCINT(IRON0_START_BUTTON), iron0_start_button_pressed, RISING);
  attachPCINT(digitalPinToPCINT(IRON0_STOP_BUTTON), iron0_stop_button_pressed, RISING);
  attachPCINT(digitalPinToPCINT(IRON0_REED_SWITCH_PIN), iron0_reed_switch_state_changed, CHANGE);

  Serial.begin(9600);
  app.init();
}

void loop() {
  app.processIrons();
  app.render();
  app.makeBeep();
}

Calibration

I had planned to include calibration feature in this program but I did not work on it yet. It would require an external and accurate temperature sensor. However no modification would be required in soldering station circuit. So, we can implement this feature just by modifying the program.

External Dependencies

These are external libraries this program depends on. Library packages are provided in case if the libraries ever go out of Internet from their original locations!

Photos

Completed soldering station with iron connected.
Iron board containing both MOSFET driver and thermocouple amplifier.

Comments