#include <TinyDebug.h>
#define TempInputPin PB3
#define FanCtlPin PB1
//Need to test but calculated temp to voltage
//Temp = Volt = ADC Reading @ 2.5V Ref
//20C = 0.45V = 186
//30C= 0.58V = 238
//40C= 0.83V - 341
//50C= 1.16V = 476
//60C= 1.56V = 636
const uint16_t OnThreshold=425;
const uint16_t OffThreshold=275;
uint16_t CheckThreshold = OnThreshold;
uint16_t temp;
uint32_t FanSwitchTime;
const uint32_t FanOnOverLoad = 5000; //45min x 60000ms/min
const uint16_t checktime=1000;//how often to check temp
uint32_t lastcheck=0;
bool FanOn = false;
void setup() {
Debug.begin();
//analogReference(INTERNAL2V5);
pinMode(TempInputPin,INPUT);
pinMode(FanCtlPin,OUTPUT);digitalWrite(FanCtlPin,FanOn);
}
void loop() {
uint32_t ms=millis();
if (ms-lastcheck > checktime){ // only check temp once per checktime (default 1 sec)
temp=analogRead(TempInputPin);//number goes up as temp goes up;
//Debug.println(temp);
//Debug.println(CheckThreshold);
if ((FanOn) ? (temp < CheckThreshold) : (temp > CheckThreshold)){
ToggleFan(ms);//Toggle Fan On/Off once threshold reached
}
lastcheck = ms;
}
if (FanOn && (ms - FanSwitchTime > FanOnOverLoad)){//check if fan on for more than X minutes and turn Off if so
ToggleFan(ms);//Toggle Fan Off
}
}
void ToggleFan(uint32_t _ms){
FanOn=!FanOn; //Toggle Fan On/Off once threshold reached
digitalWrite(FanCtlPin, FanOn);
FanSwitchTime = _ms;
CheckThreshold = (CheckThreshold == OnThreshold ? OffThreshold : OnThreshold);//toggle CheckThreshold
}