/*
 * 60W PD Powered Automatic Reflow Hoteplate
 * Author: tobychui
 * 
 * Notes: 
 * Temperature sensing is done using 1k 1% resistor and a 10k Thermistor
 * You might need to change the code if you are using other values
 * 
 * Touch Button Mappings
 * Start Btn: P1.4
 * Stop Btn: P1.7
 */
#include <TouchKey.h>

#define TEMP_PIN 11 //P1.1
#define HEATER_PIN 34 //P3.4
#define LED_PREHEAT 15 //P1.5
#define LED_REFLOW 16 //P1.6

#define HOLDSTART_TIME 100 //in cycles
#define COOLDOWN_TEMP_ADC 255 //Room temperature
//Preheat power settings
#define PREHEAT_TEMP_ADC 155 //160 degree C
#define PREHEAT_PWR_PWM 150 //160 degree C

//Reflow power settings
#define REFLOW_TEMP_ADC 123 //220 degree C
#define REFLOW_PWR_PWM 255

#define CUTOFF_TEMP_ADC 100 //240 degree C, overheat cutoff

//Func def
void updateHeaterPowerState();
void updateKeyStates();
int readTemp();


//Runtimes
bool reflowing = false;
int startCountdown = HOLDSTART_TIME; //Hold for 1000ms to start
int currentHeatplateTemp = 0; //Converted temperature in degree C (rounded)
int cycleCounter = 0; //Record cycle time up to 10 seconds
bool blinkState = false; //If blinking this will be switching between true and false
bool reflowComplete = false; //Indicate if the stopping is done because of reflow complete

int targetTempADC = 255; //Target ADC reading to reach, 255 = room temperature
int targetPwrPWM = 0; //Target PWM cycle for heater, 255 = full power, 0 = off
int offset = 1; //Allow +-offset for the ADC reading before reheating / cooling

void setup() {
  //Enable the touch buttons
  //Enable all 6 channels:TIN2(P1.4),TIN5(P1.7)
  TouchKey_begin((1 << 2) | (1 << 5));

  //Set LED pins to output
  pinMode(LED_PREHEAT, OUTPUT);
  pinMode(LED_REFLOW, OUTPUT);
  digitalWrite(LED_PREHEAT, LOW);
  digitalWrite(LED_REFLOW, LOW);

  //Set temp sense pin to input
  pinMode(TEMP_PIN, INPUT);

  //Set mosfet control pins to output and disable it
  pinMode(HEATER_PIN, OUTPUT);
  digitalWrite(HEATER_PIN, LOW);
}


void loop() {
  //Check key status
  updateKeyStates();

  //Update current temperature value
  if (reflowing){
    //Reflowing. cycle time = 100ms
    updateHeaterPowerState();
  }else{
    //Standby, cycle time = 10ms
    digitalWrite(HEATER_PIN, LOW);
    if (cycleCounter%200 == 0){
      if (reflowComplete){
        //Reflow done blink
        if (blinkState){
          digitalWrite(LED_REFLOW, HIGH);
        }else{
          digitalWrite(LED_REFLOW, LOW);
        }
      }else{
        //Standby blink
        if (blinkState){
          digitalWrite(LED_PREHEAT, HIGH);
        }else{
          digitalWrite(LED_PREHEAT, LOW);
        }
      }
      
      blinkState = !blinkState;
    }
    delay(10);
  }

  //Cycle printout
  //USBSerial_println("cycle");
  cycleCounter++;
  if (cycleCounter > 10000){
    cycleCounter = 0;
  }
}
