#define DEBUG           // show messages like "fan on, mid", "fan off"
 #define TEMP_DEBUG      // in addition to DEBUG show temp raw value every second


// minor feature. Week influence as I think. Can be 0 or 1
// 1 is better I feel
#define TEMP_CONTROL_TYPE     1

// inputs/outputs
#define INPUT_EN        6        // enable input
#define INPUT_TEMP      A3       // temp sensing input. Should be some A pin
#define OUTPUT_PWM      10       // pwm output, DONT CHANGE THIS PIN, connected to specified

#define PWM_DUTY_MIN       65        // minimal pwm %
#define PWM_DUTY_MAX       85        // maximal pwm %( dont set 100, 95 is great for max)
#define STARTUP_DELAY      2         // period for pumping up motor with constant ON output without pwm for better starting, seconds. 

#define TEMP_THRESHOLD     620
#define PWM_FREQ           770       // pwm frequency. It is just some value to get desired frequency. 720 is about 22kHz
#define PWM_STEP           7        // when temp is high and rising system increase pwm duty step by step by this value. Higher value - faster it ramp and slow down. 7 is ~1% duty per second.

enum {OFF = 0, RUNNING = 1, STARTUP = 2};

volatile bool _wdtFlag = 0;

byte enButtonTmp = 0;
byte mode = OFF;
byte tempTmp = 0;
byte tempTmp2 = 0;

uint16_t curTemp, prevTemp = 0, tmpTemp;
uint16_t dutyTmp;

byte startUpFlag = 0;

uint16_t dutyMin = PWM_FREQ / (100 / (float)PWM_DUTY_MIN);
uint16_t dutyMax = PWM_FREQ / (100 / (float)PWM_DUTY_MAX);
uint32_t time = 0;

void setup(){
  delay(500);

#ifdef DEBUG
  Serial.begin(9600);
#endif

  digitalWrite(OUTPUT_PWM, LOW);
  pinMode(OUTPUT_PWM, OUTPUT);


  // 1s timer using WDT
  //  WDTCSR = (1<<WDCE) | (1<<WDE);
  //  WDTCSR = (1<<WDCE) | (1<<WDIE) | (1<<WDP2) | (1<<WDP1);     // 1s

#ifdef DEBUG
  Serial.println("begin...");
  Serial.print("Temp control type: ");
  Serial.println(TEMP_CONTROL_TYPE, DEC);
  Serial.println();
  Serial.println();
#endif


  stopPwm();

  OCR1A = PWM_FREQ;
  OCR1B = dutyMin;
  TCNT1 = 0;
  TCCR1A = (1 << WGM11) | (1 << WGM10) | (1 << COM1B1);
  TCCR1B = (1 << WGM13) | (1 << WGM12);

  //OCR1A = PWM_FREQ;
  //OCR1B = dutyMin;

  delay(100);
}



void loop()
{
  enableHandler();

  if (millis() - time >= 1000) // 1 sec
  {
    time = millis();

    startUpHandler();

    tempHandler();
  }
}