Digital temperature sensor

For this exercise, you need a ds18b20 digital temperature sensor and a 4.7k ohm resistor.

First you need to add this line to /boot/config.txt:

dtoverlay=w1-gpio

Reboot and connect it up:

  • 4.7k resistor connects between pi pin 1 and pi pin 7
  • ds18b20 pin 1 to pi pin 6
  • ds18b20 pin 2 to pi pin 7
  • ds18b20 pin 3 to pi pin 1

Notice you can add multiple temperature sensors. read_temp takes as its parameter the index of the temperature to check, indexed from 0.


In [1]:
from IPython.display import HTML

import os
import glob
import time

base_dir = '/sys/bus/w1/devices/'
device_folders = sorted(glob.glob(base_dir + '28*'))

def read_temp_raw(id):
    device_file = device_folders[id] + '/w1_slave'
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp(id):
    lines = read_temp_raw(id)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_f #, temp_f

    
HTML("""
<script type="text/javascript" src="js/smoothie.js"></script>
<script type="text/Javascript">
    var running = false;
    var sc = new SmoothieChart({ 
        interpolation: 'linear', millisPerPixel: 75,
        grid: { strokeStyle:'rgb(125, 0, 0)', fillStyle:'rgb(60, 0, 0)',
            lineWidth: 1, millisPerLine: 250, verticalSections: 6 },
        labels: { fillStyle:'rgb(255, 255, 255)' } });
    var line1 = new TimeSeries();
    sc.addTimeSeries(line1,
        { strokeStyle:'rgb(0, 255, 0)', fillStyle:'rgba(0, 255, 0, 0.4)', lineWidth:3 });
  
    sc.streamTo(document.getElementById("graphcanvas1"));
    
    function append_value(out) {
        if(out.msg_type == 'error') {
            running = false;
        } else {
            var value = out.content.data["text/plain"];
            line1.append(new Date().getTime(), value);
        }
    }
    
    function watch_input() {
        if(running) {
            Jupyter.notebook.kernel.execute("read_temp(0)", 
                {iopub: {output: append_value}}, {silent: false}); 
            setTimeout(watch_input, 1500);
        }
    }
    setTimeout(function() { running = true; watch_input(); }, 3000);
</script>
<canvas id="graphcanvas1" width="700" height="200"/>
""")


Out[1]:

In [ ]: