//a simple thermostat
#include <LiquidCrystal.h>
#include <OneWire.h>
#include <PID_v1.h>
OneWire ds(11);
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
//*push*buttons
const int Button_up = A3;
const int Button_dn = A2;
const int Button_prev = A1;
const int Button_nxt = A0;
const int Heat = 9;
// variables
int WindowSize = 5000;
unsigned long windowStartTime;
double Setpoint, Input, Output;
boolean Start = false;
boolean Conv_start = false;
float set_temp = 20;
float Temp_c;
int temp;
byte data[2];
byte i;
byte Busy = 0;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,200,5,3, DIRECT);
void setup(void)
{
// Start up the library
l
cd.begin(16,2);
pinMode (Button_up,INPUT);
pinMode (Button_dn,INPUT);
pinMode (Button_prev,INPUT);
pinMode (Button_nxt,INPUT);
pinMode (Heat,OUTPUT);
windowStartTime = millis();
//tell the PID to range between 0 and the full window size
myPID.SetOutputLimits(0, WindowSize);
myPID.SetMode(AUTOMATIC);
}
void loop(void)
{
Temperature();
Setpoint = set_temp*16;
Input = Temp_c * 16;
lcd.setCursor(0,0);
lcd.print("Set Temp =");
lcd.setCursor(10,0);
lcd.print(set_temp);
lcd.setCursor(0, 1);
lcd.print("Temp =");
lcd.setCursor(7,1);
lcd.print(Temp_c);
if (!(digitalRead(Button_up))&& !(Start))
{
while (digitalRead(Button_up)==0){
}
set_temp= set_temp+0.25;
}
if (!(digitalRead(Button_dn))&& !(Start))
{
while (digitalRead(Button_dn)==0){
}
set_temp= set_temp-0.25;
}
if (digitalRead(Button_prev)==0)
{
while (digitalRead(Button_prev)==0){
}
Start = true;
}
if (digitalRead(Button_nxt)==0)
{
while (digitalRead(Button_nxt)==0){
}
Start = false;
digitalWrite(Heat,LOW);
}
if (Start)
{
PID_HEAT();
}
}
void Temperature(void)
{
ds.reset();
ds.skip();
// start conversion and return
if (!(Conv_start)){
ds.write(0x44,0);
Conv_start = true;
return;
}
// check for conversion if it isn't complete return if it is then convert to decimal
if (Conv_start){
Busy = ds.read_bit();
if (Busy == 0){
return;
}
ds.reset();
ds.skip();
ds.write(0xBE);
for ( i = 0; i < 2; i++) { // we need 2 bytes
data = ds.read();
}
unsigned int raw = (data[1] << 8) + data[0];
Temp_c = (raw & 0xFFFC) * 0.0625;
Conv_start = false;
return;
}
return;
}
void PID_HEAT (void){
myPID.Compute();
/************************************************
turn the output pin on/off based on pid output
***************************************************/
unsigned long now = millis();
if(now - windowStartTime>WindowSize)
{ //time to shift the Relay Window
windowStartTime += WindowSize;
}
if(Output > now - windowStartTime) digitalWrite(Heat,HIGH);
else digitalWrite(Heat,LOW);
return;
}