Web enabled thermostat project


59 posts   Page 1 of 3   1, 2, 3
by onepoint21 » Wed Nov 28, 2012 5:03 pm
Hi everyone. I've only recently started learning python so I could build some ideas I've had for home automation and monitoring. The first thing I wanted to tackle was a web enabled thermostat. I went with just learning how to turn my relay board on and off using the GPIO. It was relatively easy and I've been putting in some time to get my thermostat up and running. So far the results are really promising. I have today started piecing together a really simple php page that will let me set a desired temperature using forms. So it's nothing fancy yet, however it is working really well. I thought I might share a quick video of my setup so far.

For those of you having difficulty getting things started I would really recommend a book called "Head First Programming - A Learner's Guide to Programming Using Python". It helped get my head wrapped around this stuff pretty quickly.

http://youtu.be/o3QJbWkMZFE

Any suggestions, comments or questions are welcomed.
Everything will be open sourced with instructions once I get things looking nicer.

David
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by TRG » Fri Nov 30, 2012 5:08 pm
This is a great project, exactly what I am looking to do myself.

I will be following this closely! :)
Posts: 1
Joined: Fri Nov 30, 2012 5:05 pm
by onepoint21 » Sat Dec 01, 2012 1:42 pm
Here is an update. It's got an official name. I've called it HotPi. I've decided to use nginx with PHP for the web server. I've been imaging my SD card every time I make major changes. This way I can replicate Pi's very quickly and roll back easily.
I've included a new video showing a little bit of the mobile web interface. It's just a simple dropdown to select the desired themperature, however I do plan on making a scheduling interface. Just a couple bits of hardware left to arrive in the mail before it goes live. Until then I plan on improving the interface a bit and cleaning up some code.
Please excuse my voice in the video. I've been fighting off a cold for the past week. :D
http://youtu.be/yWE45rAoZ88

Image
Next on my list is to add a sump pump sensor so I can be alerted if our sump pump ever fails.

Image
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by onepoint21 » Tue Dec 04, 2012 4:30 pm
Another update. I've added a sump pump monitor to my Pi. Using a magnetic float switch and combined with tropo.com. I'm now able to get SMS and phone calls when my sump pump fails. It's a wicked combination.

Image

Image

I apologize for the video quality, however for this demo I need my phone.
http://youtu.be/7u0ac1GEGXY
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by stephenz » Wed Dec 05, 2012 5:20 pm
Hey David

This is very cool start you've made, I'll be sure to follow your progress and I wish you well on it.

Your solution seems similar to one that I am hoping to build(perhaps ultimately yours will be more advanced).

Rather than operating a furnace however, I have to operate an exhaust fan on a cupboard with some low BTU generating output computer equipment. This is for a problem caused in summer, rather than the winter heating problem you're managing.

Now to purchase myself a Raspberry Pi or two!

Cheers,
Stephen
Posts: 1
Joined: Wed Dec 05, 2012 5:12 pm
by buschlwd » Fri Dec 07, 2012 7:39 pm
David,

Thanks for posting your project. It looks very promising and it seems to have a lot of interest. Would you mind sharing what python libraries you are using and how you set up your pins to interact with the temperature probe and level switch. I realize this may be a very basic question, but I am new to python. Thanks!

Bill
Posts: 2
Joined: Fri Dec 07, 2012 7:35 pm
by onepoint21 » Fri Dec 07, 2012 9:54 pm
Hi guys,

Thanks for the replies. The question about the exhaust/blower would be really easy to do. Its something you could have set up quite quickly. I'm in fact working on a solar furnace that will be ultimately be controlled by the pi along side of my oil furnace. So I have a pretty good idea what's needed. I think we could work together to make it happen.

As for the libraries and GPIO pins etc. I'll be happy to provide it. I'm away at work until tomorrow night. But on Sunday I should have some time to sit down and type everything up. To be honest all of the basic libraries I've been using come standard on the Debian image. I really like keep my programs easy and straight foward so don't expect anything too advanced or spectacular. Only functional and reliable!

Check back Sunday and I should have the information you are looking for.
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by onepoint21 » Sun Dec 09, 2012 3:49 pm
buschlwd wrote:David,

Thanks for posting your project. It looks very promising and it seems to have a lot of interest. Would you mind sharing what python libraries you are using and how you set up your pins to interact with the temperature probe and level switch. I realize this may be a very basic question, but I am new to python. Thanks!

Bill


This should get you started: BTW the code is losing its indentation when I paste it. Not sure how to correct that!

As an FYI, I am doing this current project on a Rev 1 Raspberry Pi. I do believe some of the pins on Rev 2 may have changed.
For the float switch I am using GPIO0(Pin 3) and Ground(Pin 9). I used GPIO0 because it apparently has an onboard resistor. So instead of adding one to the float switch I can rely on the board. Any switch should work for testing. The float switch I am using is normally closed.
The code below is very basic. It will get your float switch to print to your screen.

import RPi.GPIO as GPIO
import time

def main():

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(0, GPIO.IN, pull_up_down=GPIO.PUD_OFF)

infloop = 1
switch_down = 0

def switch_pos():
if GPIO.input(switch_down) == 0:
print("Normal")
time.sleep(10)
else
print("Failed. Call in progress")
time.sleep(10)
#This constructs an infinite loop
while infloop == 1:
switch_pos()
if __name__ == '__main__':
main()


-----------------------------------------------------------
I used a tutorial from here: http://www.cl.cam.ac.uk/freshers/raspbe ... mperature/
Using a DS18B20 temperature sensor with a 4.7K ohm resistor tied between pin 2 and 3 on the sensor. The wires are then connected as follows.
Sensor pin 1 goes to Ground, Pin 2 is data and goes to GPIO4(Pin 7), Pin 3 goes to 3Volt(Pin 1)
For the relay board, you connect from the raspberry pi 5Volt (pin2) to Vcc on the relay. Ground on the Pi(Pin 6) to GND on the relay. Then GPIO18(Pin 12) to IN1 on the relay. The following is a portion of the thermostat code to get the IO working and to print the state to the screen.
-----------------------------------------------------------

import RPi.GPIO as GPIO
import time
import math

def main():

GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)

# This reads the temperature from the DS18B20 and rounds the value to the nearest decimal.
def currtemp():
tfile = open("/sys/bus/w1/devices/28-0000044ac28e/w1_slave")
text = tfile.read()
tfile.close()
secondline = text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temperature = float(temperaturedata[2:])
temperature = temperature / 1000
temperature = round(temperature, 1)
return float(temperature)

#Set desired temperature by reading /var/bin/thermostat file
def settemp():
readtemp = open("/var/bin/thermostat", "r")
settemp = readtemp.readline(4)
readtemp.close()
return float(settemp)

# Hold the temperature at the settemp
def holdtemp():
if currtemp() >= settemp():
GPIO.output(18, GPIO.HIGH)
print "State 1",settemp(),"Furnace is off.",currtemp()
time.sleep(10)
else:
if currtemp() + 0.5 <= settemp():
GPIO.output(18, GPIO.LOW)
print "State 2",settemp(),"Furnace is on.",currtemp()
time.sleep(60)
else:
GPIO.output(18, GPIO.HIGH)
print "State 3",settemp(),"Furnace is off.",currtemp()
time.sleep(10)

# This constructs an infinite loop to monitor the temperature
infloop = 1
while infloop == 1 :
holdtemp()

if __name__ == '__main__':
main()


If you have any questions I'll do my best to answer. :D
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by buschlwd » Wed Dec 12, 2012 12:37 pm
Thanks a lot this is really great. I am excited to get started.
Posts: 2
Joined: Fri Dec 07, 2012 7:35 pm
by Paul Versteeg » Thu Dec 13, 2012 8:59 pm
Hi David,
I'm doing something very simular from what you are doing.

I want to replace my simple thermostat with a Pi, that I want to initially control via PuTTY (which is what I do now using wifi), then via a web browser.
One of my requirements is that we leave the house unattended for longer periods, and I need to know what the HVAC is doing. Currently there is only a manual switch on the current thermostat to move from heating to cooling (Texas) and I have already automated that in my Python controller software. I use a DS18B20, and do a lot of work to control the HVAC system. Later on my plan is to use more sensors (outside, attic , garage) and trend that. That program is also done, and uses RRDTOOL.

My controller program also does a lot of error checking and logs errors in a file. Because controlling a complete HVAC system can be complicated, It would be nice to compare our controller programs.

I have never done any web programming and I'm currently looking for ways on how to do that. This is how I found your post.

Any suggestions on how we can share some details before we post to a larger audience?

Cheers, Paul
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by Paul Versteeg » Fri Dec 14, 2012 1:26 pm
Hi David,

I'm impressed with what you've done so far, and I really like the YouTube videos.
I'm nowhere near that far with the web interface, but I spent a lot of time on the controller part. I looked at your thermostat program in some more detail, and here are some observations:

First, you do not really have a hysteresis in your program, other then what your rounding does.
Your program switches on and off at -0.5 degrees below your set_temp. Regardless if the temperature is moving from high to low, or from low to high.

Here are two printouts of a simulation of your code:
High to low:
State 1 20.0 Furnace is off. 20.8
State 1 20.0 Furnace is off. 20.6
State 3 20.0 Furnace is off. 20.3
State 3 20.0 Furnace is off. 20.0
State 3 20.0 Furnace is off. 19.7
State 2 20.0 Furnace is on. 19.4
State 2 20.0 Furnace is on. 19.1


Low to high:
State 2 20.0 Furnace is on. 19.2
State 2 20.0 Furnace is on. 19.5
State 3 20.0 Furnace is off. 19.8
State 3 20.0 Furnace is off. 20.1
State 3 20.0 Furnace is off. 20.4
State 1 20.0 Furnace is off. 20.6
State 1 20.0 Furnace is off. 20.8


As you see, the turning point is always at 19,5 degrees when your set_temp is 20 degrees.

I use the following function to control the furnace (I also control the cooling but separately):
Code: Select all
def heating():
    '''
    Determine if we need to switch the heater on or off
    '''
    global set_temp_h, current_temp
    if current_temp <= set_temp_h + H:
        hvac(True)
        return
    if current_temp >= set_temp_h - H:
        hvac(False)

H is the hysteresis and is set at .5 degrees in my case.
What we have is called an indeterminate non-linear control function.
I found that the standard formula for this is: S low - H < Vin < S high + H

I also noticed regular bad CRC's from the DS18B20 sensor, if the CRC is bad, the temperature is bogus. Since you keep your burner on for 60 seconds, that is quite long for a bogus reading.
I use a bit of error checking as I mentioned in an earlier post, and, because the DS is very sensitive, I also average a few readings before I pass it on to my HVAC.
Here is what I use to read a DS sensor :
Code: Select all
def get_sensor_data(ds):
    '''
    Get the temperatures from one of the DS18B20's.

    Test for a proper CRC from the DS18B20 for a YES in the result.
    Average the readings for a few times to get a stable return.
    '''
    avg_tmp = 0.0
    x = 1
    while ( x <= 5): # 5 readings should do
        tfile = open(ds)
        text = tfile.read()
        tfile.close()
        if re.search ("YES", text):
            # there is a valid crc in the recording
            # strip the rubbish to get to the temperature
            temperature_data = text.split()[-1]
            temp = float(temperature_data[2:])
            temp = (temp / 1000)
            if temp < 5 or temp > 33: # one more check
                print "\t\tTemp out of range : ", temp
                write_log ("Get_sensor_data() Temp out of range : " + str(temp ))
            else:
                avg_tmp = avg_tmp + temp
                x += 1
        else:
            write_log ("Get_sensor_data() Rcvd corrupted data from sensor\n")
        sleep(0.1)
    return round(avg_tmp/(x-1), 2) # round to 2 decimal digits

BTW, you need the following imports:

import os
import string
import re
from time import time, sleep


Here is my routine to log all problems in a file, such that when the system crashes, I can still dig it up, also while the system is running, I can look at the stuff without stopping it, otherwise, I need a lot of "prints" to stdout in the code, which I don't like. Besides, nobody will see it anyway.

Code: Select all
def write_log(err_str):
    '''
    Write errors/warnings/messages to a log file.

    So we can look at them offline and later.
    '''
    global set_temp_h, set_temp_c, current_temp
    try:
        fout = open(logfile_name, "a") #  "a" means append
    except Exception, e:
#        print "\tOutput file open error: %s" % str(e) # while debugging

    tstamp = strftime("%d-%m-%Y %H:%M:%S", gmtime())
    fout.write (tstamp + " -> " + err_str)
    fout.write (str("\n"))
    fout.close()

I like your idea of getting an SMS when the system detects a problem. When I'm away, I'm really away (in Europe), while the house is in Texas. I have found a routine from a smart person that I have modified somewhat to send me an email. I applied for a special email address for my Pi from Google mail.
Here is that routine:
Code: Select all
def mail_alarm(msg, t):
   '''
   This function emails a message from the raspberry pi to myself.

   We also send the IP address, just in case we're going to use
   more Pi's later on. This portion can be commented out.
   '''
   to = 'your email address'
   gmail_user = 'Pi_email_address@gmail.com'
   gmail_password = 'XXXXX'
   smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
   smtpserver.ehlo()
   smtpserver.starttls()
   smtpserver.ehlo
   smtpserver.login(gmail_user, gmail_password)
   today = datetime.date.today()
   arg='ip route list'
   p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
   data = p.communicate()
   split_data = data[0].split()
   ipaddr = split_data[split_data.index('src')+1]
   my_msg = 'Message from Pi at IP address %s' %  ipaddr +'\n\nWarning: '+ msg + str(t)
   msg = MIMEText(my_msg)
   msg['Subject'] = 'Msg from Pi on %s' % today.strftime('%b %d %Y')
   msg['From'] = gmail_user
   msg['To'] = to
   smtpserver.sendmail(gmail_user, [to], msg.as_string())
   smtpserver.quit()

You need to add this:

import subprocess
import smtplib
import socket
from email.mime.text import MIMEText
from time import gmtime, strftime


My controller program is too large to explain it here, but I can add more elements if there is interest by you and the other folks. When I'm really done, I need to find a way to post it. Don't know how yet.

I myself would be more than interested to get more details about your web-end of the project.

BTW, I also initially had the indentation problem, but if you declare your program pieces as "Code", by using the button above the text box when you compose your post, it takes care of everything for you.

In the meantime, keep at it,
Paul
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by onepoint21 » Fri Dec 14, 2012 4:17 pm
Paul, that is awesome! Yeah I see what you're saving about my program. It is again, very basic and I'm on a learning curve with python. :D The code you've posted will be extremely helpful in getting my bugs worked out.
I'd be happy to help with the web side of things. My past experience in the early 2000's was almost entirely active server pages, but php is my language of choice today. I decided that because the Pi wasn't going to be serving out large web page requests that I would rather not use an sql database. It's just too much for moist people to set up and demands lots of resources from the server. Instead I can just store values in text files. That way it saves on overhead and is very easy to implement on the Pi. From the web page you would have seen in the video, I'm basically just using a little javascript and php to display and store values in a file. As the thermostat python module runs through it's loop it will look at the set value in that file and use it to manage the temperature. It's been working for a couple of weeks now without any issues. Pretty simple, but effective for a project like this.
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by onepoint21 » Fri Dec 14, 2012 8:48 pm
These are the temperature sensors that I will be mounting (in some fashion) to the wall. They cost about $3 per board. Very small and easy to hide.
Image
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by onepoint21 » Sat Dec 15, 2012 2:29 am
Paul,

Here is some sample code from my thermostat web interface.
This takes the temperature from the drop down form and saves it to a thermostat file. The python module then calls for this file to check for the desired set temperature.

Code: Select all
<?php
if(isset($_POST["settemp"])) {

$settemp = $_POST["settemp"];
$fp = fopen("/var/bin/thermostat", "w+");
$savestring = $settemp;
fwrite($fp, $savestring);
fclose($fp);
}
?>


Next to display the current temperature I execute a simple python script that outputs the temperature from the sensor.

Code: Select all
<?php echo exec('python /var/bin/gettemp.py 2>&1'); ?>


The get temp.py simply looks like this

Code: Select all
#! /usr/bin/python

# Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
tfile = open("/sys/bus/w1/devices/28-0000044ac28e/w1_slave")
# Read all of the text in the file.
text = tfile.read()
# Close the file now that the text has been read.
tfile.close()
# Split the text with new lines (\n) and select the second line.
secondline = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temperaturedata = secondline.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temperature = float(temperaturedata[2:])
# Put the decimal point in the right place and display it.
temperature = temperature / 1000
print temperature


The form itself checks for the set temperature. Then on selecting your desired temperature it submits to be written to the thermostat file.

Code: Select all
<form name="termostat" method="post" class="label-top" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <div>
               <label for="settemp" class="inline">Temperature set at</label>
               <select name="settemp" id="settemp" onChange="this.form.submit()">
                  <option value=null SELECTED><?php $curSet = file_get_contents('/var/bin/thermostat'); echo $curSet; ?> °C </option>
                  <option value="21.5">High(21.5°C)</option>
                  <option value="20.0">20°C</option>
                  <option value="19.5">Home(19.5°C)</option>
                  <option value="19.0">19°C</option>
                  <option value="18.5">18.5°C</option>
                  <option value="15.5">15.5°C</option>
                  <option value="15.0">Away(15°C)</option>
                   <option value="14.5">14.5°C</option>
                  <option value="10.0">Low(10°C)</option>
               </select>
            </div>
            </form>


It needs to be cleaned up a little to make things more efficient. Like getting a true updated status rt he moment the temperature is set.
Anyhow, I'll keep you posted.
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by Paul Versteeg » Sat Dec 15, 2012 6:41 am
I realized while going through my code for the heater, that I left some debug pieces in, and I also extended the comments to make the hysteresis bit more clear.
Here is the correct piece:
Code: Select all
def heating():
    '''
    Determine if we need to switch the heater on or off.

    While the temperature is within the
    set_temp_h +/- hysteresis (H) range, the current system
    state stays unchanged.
    '''
    if current_temp >= set_temp_h + H:
#        print "stop furnace", current_temp, set_temp_h + H
        hvac(False)
    if current_temp <= set_temp_h - H:
#        print "start furnace", current_temp, set_temp_h - H
        hvac(True)


The cooling function is quite the same:
Code: Select all
def cooling():
    '''
    Determine if we need to turn the cooling on or off.

    While the temperature is within the
    set_temp_c +/- hysteresis (H) range, the current system
    state stays unchanged.
    '''
    if current_temp <= set_temp_c - H:
#        print "stop A/C", current_temp, set_temp_c - H
        hvac(False)
    if current_temp >= set_temp_c + H:
#        print "start A/C", current_temp, set_temp_c + H
        hvac(True)


Sorry if I caused you guys some grief. My code, although functionally complete, is still undergoing a lot of testing. You don't want to mess with your HVAC system, believe me.

Paul
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by Paul Versteeg » Sat Dec 15, 2012 6:45 am
Hey David,

Thank you very much for the web stuff. I'm a real nuby on PHP and HTML, but I will take a look at what you've done and will try to understand it and see if I can implement it as well. I'll keep you posted.

Tks,

Paul
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by Paul Versteeg » Sat Dec 15, 2012 3:06 pm
Folks, I started a separate Post in this forum for my own project.
Yes it has the same aim, but I think that I'm taking a different approach from the controller point of view.
With the two posts, and hopefully more coming, we can all learn from each other. And there is something for everybody to use.

Have a look at my post called:
Automatic Thermostat


I will be using the web stuff that David is using for his project heavily and sharing with us, so keep an eye on that too.

Tks, Paul
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by Paul Versteeg » Sun Dec 16, 2012 7:00 am
onepoint21 wrote:These are the temperature sensors that I will be mounting (in some fashion) to the wall. They cost about $3 per board. Very small and easy to hide.
Image


David, this is an interesting board for a great price. Where did you find this?
This board also has some more components beside the DS and the resistor. I'd like to know what they are.
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by Paul Versteeg » Sun Dec 16, 2012 7:55 am
Paul Versteeg wrote:Hey David,

Thank you very much for the web stuff. I'm a real nuby on PHP and HTML, but I will take a look at what you've done and will try to understand it and see if I can implement it as well. I'll keep you posted.

Tks,

Paul


David, I got it working on my machine. I had one issue to deal with, I needed to chmod the data file before I got it working (newby!). Thanks a bunch, this will help me to get started on php and I will now try to extend your program and incorporate it in my own program. Stay tuned on developments in my post (Automatic Thermostat).

BTW This is an excellent example of collaborate working and sharing on this forum!

Paul

Paul
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by onepoint21 » Sun Dec 16, 2012 2:04 pm
Paul Versteeg wrote:
onepoint21 wrote:These are the temperature sensors that I will be mounting (in some fashion) to the wall. They cost about $3 per board. Very small and easy to hide.
Image


David, this is an interesting board for a great price. Where did you find this?
This board also has some more components beside the DS and the resistor. I'd like to know what they are.


Hi Paul, This board was purchased on ebay. (http://www.ebay.ca/itm/DS18B20-temperature-measurement-sensor-module-/140837350708?pt=LH_DefaultDomain_0&hash=item20ca8f6d34#ht_1247wt_952)

Image

There are 2 resistors and one LED(d1) soldered to the board. Resistor r1 is 10K ohm and r2 is 1K ohm. Looks like r1 is between pin 2/3 and r2 is for the LED. Although I haven't officially traced it out yet.

I plugged it in and set the new bus code yesterday and it worked perfectly.

Glad to hear you got the code working. Permissions are a pain! More often than not they are the culprit for things not executing.
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by oxfletch » Wed Dec 26, 2012 4:55 pm
Any idea what distances these temp sensors can run over? What I would love to do is install one in each room in the house, and run them back over twisted pair cable back to a central Raspberry PI
Posts: 1
Joined: Wed Dec 26, 2012 4:53 pm
by danjperron » Thu Dec 27, 2012 5:04 am
You should check the crc of the ds1820 sensor. I just finish to hook up 5 sensors on my pond heater system and I found out that sometimes sensors gives bad results. When I looked at the returned data, I found out that every time the temperature is wrong , the crc is also not ok. (data return is all ones). So I modified the read the sensor functions and implements the crc check. We just need to look for the string 'YES' at the first row.

check ReadSensor function from the code below


Code: Select all
#!/usr/bin/python
import RPi.GPIO as GPIO
import time

def ReadCpuTemperature():
  file= open("/sys/class/thermal/thermal_zone0/temp","r")
  string = file.readline()
  file.close()
  cputemp = float(string)/1000.0
  return cputemp

def ReadSensor( SensorId):
  while(1):
    fname = "/sys/bus/w1/devices/" + SensorId + "/w1_slave"
    tfile = open(fname)
    text = tfile.read()
    tfile.close()
    firstline  = text.split("\n")[0]
    crc_check = text.split("crc=")[1]
    crc_check = crc_check.split(" ")[1]
    if crc_check.find("YES")>=0:
     break

  secondline = text.split("\n")[1]
  temperaturedata = secondline.split(" ")[9]
  temperature = float(temperaturedata[2:])
  temperature = temperature / 1000.0
#    if temperature<0:
#print text
  return temperature

GPIO.setwarnings(False)
# set pin 16 et 18 output
GPIO.setmode(GPIO.BOARD)
#GPIO.setup(16,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)
#GPIO.output(16,GPIO.LOW)
#GPIO.output(18,GPIO.LOW)
target=4.0
histeresys=0.5
heater_on=True
while True:


   time_string =   time.strftime("%d%b%Y %H:%M:%S",time.localtime())

   th_cpu       = ReadCpuTemperature()
   th_main_box  = ReadSensor("28-00000457ecaa")
   th_cam_box   = ReadSensor("28-0000045d387d")
   th_outside   = ReadSensor("28-000004575419")
   th_pond1     = ReadSensor("28-000004575f0a")
   th_pond2     = ReadSensor("28-000004583355")


   if th_pond1 < th_pond2:
     th_min=th_pond1
   else:
     th_min=th_pond2

   if th_min > (target+histeresys):
     heater_on = False

   if th_min < (target-histeresys):
     heater_on = True


   if heater_on:
      GPIO.output(18,GPIO.HIGH)
   else:
      GPIO.output(18,GPIO.LOW)

   print "{0} T('C) CPU:{1:.0f} Box:{2:.1f} Cam:{3:.1f} Out:{4:.1f} Pond1:{5:.1f} Pond2:{6:.1f}  SetP:{7} Heater:{8}"  .format(time_string,th_cpu,th_main_box,th_cam_box,th_outside,th_pond1,th_pond2,target,heater_on)



The problem for me is that I'm in Canada and I just don't want my pond to freeze . My pond is not deep enough and my fish will die . it is -10 Celsius right now. So I got 5 sensors , one for each reservoir (2), one inside the computer box, one inside the webcam box and one outside. I just look at the lowest temperature from the reservoirs and toggle the 300W heater using an arduino shield relay. And for the fun of it I added a webcam which will be submerged. Now that everything has been tested and working well after fixing all the problems with the Rpi. A lot was about the power distribution and the wifi connection.

Next week it will be outside. Presently my heater is always on.

Image
Posts: 838
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada
by Paul Versteeg » Thu Dec 27, 2012 12:52 pm
oxfletch wrote:Any idea what distances these temp sensors can run over? What I would love to do is install one in each room in the house, and run them back over twisted pair cable back to a central Raspberry PI


There is quite a lot of information about w1 interfaces and the cabling required if you Google for it. The major recommendation is to use Cat-5 cable. Don't use ordinary cable, like telephone cable. The distance can be 100 meters or more, the topology should not be a "star" if possible.

Because the DS interfaces to the computer with a series of pulses, the capacitance of the wire is getting more important the longer the cable is. You should not use the parasitic option of powering the DS if you can avoid it. You can also experiment with the pull-up resistor for the DS, typically 4K7, but you can go to a much lower value. If you have a scope, you can see the results.
Posts: 10
Joined: Wed Dec 05, 2012 10:31 am
by onepoint21 » Sun Dec 30, 2012 5:03 pm
danjperron wrote:You should check the crc of the ds1820 sensor. I just finish to hook up 5 sensors on my pond heater system and I found out that sometimes sensors gives bad results. When I looked at the returned data, I found out that every time the temperature is wrong , the crc is also not ok. (data return is all ones). So I modified the read the sensor functions and implements the crc check. We just need to look for the string 'YES' at the first row.


Very very cool. I wouldn't have ever figured that out. Definitely implementing this.

Just hooked up the thermostat to my furnace for the first time today. Thought I might post a new video. Please disregard the awful wiring job. It's temporary until my pin connectors come in the mail.
Now to the video http://www.youtube.com/watch?v=XcCIHEbGAq8
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am
by onepoint21 » Sun Jan 06, 2013 12:09 am
Been up and running for for a week now and made just a few minor tweaks. I finally after a month received my dupont connector pins so I could finally wire the Pi, relay and temperature sensor using CAT5.

ImageImage

I need to figure out a solution to house my temperature sensor. I'm working on a shapeways project that hopefully will hide it cleanly on the wall.

ImageImageImage

This is the python script for the controller on pastebin. http://pastebin.com/MgFWrP9T.
I will trying to get the time to get the rest of my code posted this weekend. I have LOADS of more ideas to work on with respect to the thermostat. I'll keep things updated as I go. My wife and I have noticed a significant difference in the stability of the temperature at home. It's much more consistant than it used to be.
A HUGE thank you to everyone who has added their ideas to this project. Your help has made the outcome infinitely better than I had hoped.
Posts: 41
Joined: Thu Nov 22, 2012 12:13 am