Connecting 1-wire temperature sensors to RPi ?


12 posts
by RazziaDK » Sat Dec 22, 2012 3:13 am
I'm thinking of using one of my Raspberry Pi's to collect temperatures and show them on a munin-style graph. I have three of these 1-wire temperature sensors based on DS18B2 gathering dust around here somewhere - I would love to be able to use them.

Can anyone tell me how I might connect them to my Rasp Pi and collect the data into a database.

Thank you in advance!

/Rasmus
Posts: 2
Joined: Sat Dec 22, 2012 2:59 am
by RazziaDK » Sat Dec 22, 2012 3:57 am
If possible I would also like to connect a HD44780 4x20 LCD and have it displaying the current temperatures. From what I can find in my search, it should be a big problem connecting the display.

But I'm starting to doubt the 1-wire sensors - if there is an easier (and fairly cheap) type of sensor that would do the job, I would love to know.
Posts: 2
Joined: Sat Dec 22, 2012 2:59 am
by fulburncams » Sat Dec 22, 2012 6:11 am
Hi there is a Dallas i2c 2482 device that converts from the raspi i2cbus to 1-wire. You will need to write some software but I seem to remember there is a one wire library on the forum somewhere.
User avatar
Posts: 70
Joined: Wed Nov 30, 2011 8:29 pm
by Maxion » Sat Dec 22, 2012 8:49 am
RazziaDK wrote:I'm thinking of using one of my Raspberry Pi's to collect temperatures and show them on a munin-style graph. I have three of these 1-wire temperature sensors based on DS18B2 gathering dust around here somewhere - I would love to be able to use them.

Can anyone tell me how I might connect them to my Rasp Pi and collect the data into a database.

Thank you in advance!

/Rasmus



Hey there! I've done just that! If you need any help, feel free to ask here or to PM me.

Here's my setup running, www.maxedin.net/madamsholmen

I've got an RPi that uses 2 DS18B20 sensors that output to a .csv file which then is uploaded to my webserver and displayed using the higstock charts library.

Here's an easy to understand guide to get the DS18B20's working: http://www.cl.cam.ac.uk/freshers/raspbe ... mperature/

If there's anything else you're wondering about, let me know! These senors as *very* easy to get to work with the Raspberry pi. I spent more time trying to get my USB memory stick to auto-mount with the correct RW permissions, haha.
Posts: 138
Joined: Mon Dec 03, 2012 2:22 pm
by hitman80 » Sat Dec 22, 2012 10:09 am
Code: Select all
I've got an RPi that uses 2 DS18B20 sensors that output to a .csv file which then is uploaded to my webserver and displayed using the higstock charts library.

@ Maxion
can you share with us your code /scripts used for your site....
I made the same , locally with the same raspberry as web server, but i 'll want to use highcharts for nicer graphs....
Posts: 18
Joined: Sun Nov 04, 2012 5:55 pm
by Maxion » Sat Dec 22, 2012 10:50 am
hitman80 wrote:
Code: Select all
I've got an RPi that uses 2 DS18B20 sensors that output to a .csv file which then is uploaded to my webserver and displayed using the higstock charts library.

@ Maxion
can you share with us your code /scripts used for your site....
I made the same , locally with the same raspberry as web server, but i 'll want to use highcharts for nicer graphs....


Sure, keep in mind that I'm by far not an expert on this subject so my code is most likely crude and there are most likely better ways to do this.

Also keep in mind that my setup is made for a remote Pi. When deciding how to do this I had the following in mind:

A) KISS on the pi. I want to do as little work as possible with as few lines of code as possible to minimize the risk of something crashing.

B) I use an external webserver to which I only have FTP access to generate the graphs

C) I'm a n00b

I use a couple of python scripts to gather the temperature data.

One script is run every minute by a cron job. This reads the temperature data and saves it to a temporary log file. It has soma fault checks in it because my sensors bug out every now and then and output the wrong values.

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

#Every minute read temperature sensor and write value to 5minlog and 30minlog files without timestamps
import time
import datetime

#Open the temperature sensor and read it and process the result
tfile = open("/sys/bus/w1/devices/28-000003ca5dc8/w1_slave")
text = tfile.read()
tfile.close()
temperature_data = text.split()[-1]
temperature = float(temperature_data[2:])
temperature = temperature / 1000

#This while function checks for the error temperatures, and tries to read the sensor again to get a proper value. After 10 tries it stops
count = 0
while temperature == -0.062 or temperature == -0.125:
         time.sleep(2)   
         count = count + 1
         tfile1 = open("/home/usbpictures/logs/temperror.log", "a")
         tfile1.write("\n" + str(datetime.datetime.now()) + " Temperature error on sensor, 28-000003ca5dc8, Inne at " + str(temperature) + ", retrying " + str(count) + " times")
         tfile = open("/sys/bus/w1/devices/28-000003ca5dc8/w1_slave")
         text = tfile.read()
         tfile.close()
         temperature_data = text.split()[-1]
         temperature = float(temperature_data[2:])
         temperature = temperature / 1000
         if count > 10:
            break
         
else:

# If the temperature is within sane values it logs the temperature to the 1min temporary log.   
   logtemp = str(temperature)
      
   with open("/home/usbpictures/logs/1minlog.log", "a") as myfile:
      myfile.write("\n" + logtemp)
   
   #templog to find error temperatures   
   #with open("//home/usbpictures/logs/tmp/1minlog_tmp.log", "a") as myfile:
   #   myfile.write("\n" + logtemp)

#The below code reads the second sensor and does the same as above
tfile = open("/sys/bus/w1/devices/28-000003ca697f/w1_slave")
text = tfile.read()
tfile.close()
temperature_data = text.split()[-1]
temperature = float(temperature_data[2:])
temperature = temperature / 1000


count = 0
while temperature == -0.062 or temperature == -0.125:
         count = count + 1
         print 'Temperature error on sensor 2, Ute, retrying'
         tfile1 = open("/home/usbpictures/logs/temperror.log", "a")
         tfile1.write("\n" + str(datetime.datetime.now()) + " Temperature error on sensor, 28-000003ca697f, Ute at " + str(temperature) + ", retrying " + str(count) + " times")
         tfile = open("/sys/bus/w1/devices/28-000003ca697f/w1_slave")
         text = tfile.read()
         tfile.close()
         temperature_data = text.split()[-1]
         temperature = float(temperature_data[2:])
         temperature = temperature / 1000
         if count > 10:
            break
         
else:

   logtemp = str(temperature)
      
   with open("/home/usbpictures/logs/1minlog_2.log", "a") as myfile:
      myfile.write("\n" + logtemp)
   #templog to find error temperatures
   #with open("/home/usbpictures/logs/tmp/1minlog2_tmp.log", "a") as myfile:
   #
      myfile.write("\n" + logtemp)


Another script runs every 5 minutes and averages the values in the temporary logs, empties it, and saves the temperature average and the current date to a master log file.

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

#Every 5 minutes average the values in the 5minlog file, save to the 24hlog with timestamp, empty 5minlog
import time
millis = int(round((time.time() + 7200) * 1000))
millis2 = str(millis)

#read the 1min log file and average the values in it
data = open ("/home/usbpictures/logs/1minlog.log").read().split()
s = sum([ float(i) for i in data])
avg = s/len(data)

avg = round(avg, 2)
logtemp = str(avg)

#print logtemp

#print millis2

#Save the averaged value with timestamp in milliseconds to the master log file
with open("/home/usbpictures/logs/5min.log", "a") as myfile:
    myfile.write("\n" + millis2 + "," + logtemp)

#Save the averaged value with timestamp to the 24hour temporary log file   
with open("/home/usbpictures/logs/24h.log", "a") as myfile:
    myfile.write("\n" + logtemp)

#Save the averaged value with timestamp to the master log file
with open("/home/usbpictures/logs/master_5min.log", "a") as myfile:
    myfile.write("\n" + millis2 + "," + logtemp)

#Empty the 1min temp log       
open('/home/usbpictures/logs/1minlog.log', 'w').close()


#Do the same for the second sensor
data = open ("/home/usbpictures/logs/1minlog_2.log").read().split()
s = sum([ float(i) for i in data])
avg = s/len(data)

avg = round(avg, 2)
logtemp = str(avg)

print logtemp

with open("/home/usbpictures/logs/5min_2.log", "a") as myfile:
    myfile.write("\n" + millis2 + "," + logtemp)
with open("/home/usbpictures/logs/24h_2.log", "a") as myfile:
   myfile.write("\n" + logtemp)
with open("/home/usbpictures/logs/master_5min_2.log", "a") as myfile:
    myfile.write("\n" + millis2 + "," + logtemp)
       
       
open('/home/usbpictures/logs/1minlog_2.log', 'w').close()


I'm currently not sure how many datapoints highcharts can display without becoming too slow. When I figure that out the master log file will still remain, but I'll create another log file which displays only as many data points as it can handle.

When I reach this point I'll also create a separate graph for daily temperature averages as well as some sort of archival graphs for the master log file.

Here's the .js file that loads the highstock charts. Follow the simple how to on the highcharts website on getting it installed an importing the correct libraries.

Code: Select all
$(document).ready(function() {
         
         var options = {
        legend: {
            enabled: true,
            align: 'center',
            borderColor: 'white',
            borderWidth: 2,
            layout: 'vertical',
            verticalAlign: 'top',
         floating: true,
            y: 25,
            shadow: true
        },
   navigator : {
        enabled : false
            },

    chart: {

      subtitle: {text: 'Klicka och dra för att zooma in. Tryck på seriens namn under grafen för att gömma serien.'},
        renderTo: 'container',
      zoomType: 'x',
      marginTop: 80,
      height: 500
       // defaultSeriesType: 'line'

    },
   rangeSelector: {
      inputEnabled: false,
      buttonTheme: { // styles for the buttons
                fill: 'none',
                stroke: 'none',
                states: {
                    hover: {
                        fill: 'white'
                    },
                    select: {
                        style: {
                            color: 'white'
}
}
}
},
      buttonSpacing: 15,
      buttons: [{
         type: 'day',
         count: 1,
         text: '1 day'
         },
         {
         type: 'day',
         count: 3,
         text: '3 day'
         
               },{
         type: 'week',
         count: 1,
         text: '1 week'
         },{
         type: 'month',
         count: 1,
         text: '1 month'
         }]
   
   },
    title: {

        text: 'Temperaturen hos Max'

    },
    yAxis: {

        title: {
            text: 'Celcius'
        }   

    },
      xAxis: {
      type: 'datetime'
       
    },


    series: []

};
           
$.get('/temperature/logs/5min.log', function(data) {
//$.get('5min.csv', function(data) {
// Split the lines
var lines = data.split('\n');
lines = lines.map(function(line) {
    var data = line.split(',');
    data[1] = parseFloat(data[1]);
    data[0] = parseFloat(data[0]);
    return data;
       
});
     
var series = {
    data: lines,
    name: 'Inne'
 
};



 console.log(lines)
options.series.push(series);
   
var graph = new Highcharts.StockChart($.extend({},options));

});

$.get('/temperature/logs/5min_2.log', function(data) {
//$.get('5min.csv', function(data) {
// Split the lines
var lines = data.split('\n');
lines = lines.map(function(line) {
    var data = line.split(',');
    data[1] = parseFloat(data[1]);
    data[0] = parseFloat(data[0]);
    return data;
       
});
     
var series = {
    data: lines,
    name: 'Ute'
 
};



 console.log(lines)
options.series.push(series);
var graph = new Highcharts.StockChart($.extend({},options)); 

});

         
      });


These scripts are all run by cronjobs.

I then use ncftpput to upload the log files to my FTP server with another cronjob
Posts: 138
Joined: Mon Dec 03, 2012 2:22 pm
by anita2r » Mon Dec 24, 2012 3:18 pm
Hi
I have just added a 1-wire setup with 4 sensors to my RPi
This is what I did:
On the header use 3 pins:
3.3v, ground & GPIO 4
Run three wires to a breadboard and connect a 4.7K resistor from Data(GPIO 4) to VCC (3.3v).
Connect a 1-wire temperature sensor:
Connect VCC to 3V,
ground to ground and
Data to GPIO 4.
Add more sensors either on the breadboard for testing or on a cable - twisted pair wire is suggested, and I think that the ground and GPIO 4 wires need to be in a twisted pair as these carry the data
The 3.3 volt wire is just a source of power for the sensors
No more resistors are required

Now setup the required software to run the 1-wire system on pin GPIO 4:
Install pre-compiled kernel and modules:
sudo su
cd /boot
wget http://www.frank-buss.de/raspberrypi/kernel-rpi-w1.tgz
tar -xzf kernel-rpi-w1.tgz
rm -f kernel-rpi-w1.tgz
cd /lib/modules
wget http://www.frank-buss.de/raspberrypi/modules-rpi-w1.tgz
tar -xzf modules-rpi-w1.tgz
rm -f modules-rpi-w1.tgzls
sync
exit
sudo reboot

Examine the system:
sudo su
modprobe w1-gpio
ls /sys/bus/w1/devices/w1_bus_master1/
This shows a series of 'functions' such as 'w1_master_timeout' and any devices attached to the 1-wire system - they appear with the device id which starts with the device family code (28)
Use the device id you find e.g. 28-0000018a4be8, in the next command:
cat /sys/bus/w1/devices/w1_bus_master1/28-0000018a4be8/w1_slave
This should return the temperature sent by the device, after the crc check
f5 01 4b 46 7f ff 0b 10 ea : crc=ea YES
f5 01 4b 46 7f ff 0b 10 ea t=31312
In this case the temperature measured was 31.312 C

I will do another reply showing how I have got a data logging system running.

Hope this helps
Posts: 106
Joined: Sun Dec 23, 2012 6:55 pm
by anita2r » Mon Dec 24, 2012 4:47 pm
This is how I capture and log the data from all of my 1-wire temperature sensors - Its not a database but you do get a series of flat files containing date & time and temperature.
I have been able to use gnuplot to create charts from the data
Where I refer to user or folder anita2R, replace it with your RPi user name

Start by creating a folder to hold the result files:
sudo mkdir /var/1w_files
change to the new folder:
cd /var/1w_files
make a file for each device using its unique id: and start with a header line (##date time temperature - note that the ## at the start is required)
e.g. echo "##date time temperature" > 28-0000018a4be8
(the connected device names can be found by listing the contents of folder w1_bus_master1
ls /sys/bus/w1/devices/w1_bus_master1/
cd ..
change ownership & permissions:
sudo chown -R anita2R 1w_files
sudo chmod -R 0760 1w_files

Create a logging script named '1w_logging.sh' in the home/anita2R/ folder:
Code: Select all
      #!/bin/bash
      FILES=`ls /sys/bus/w1/devices/w1_bus_master1/ | grep '^28'`
      for file in $FILES
         do
            echo `date +"%d-%m-%Y %H:%M:%S "; cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave | grep t= | sed -n 's/.*t=//;p'` >> /var/1w_files/$file
         done
      exit 0

This script gets all temperature sensor names with family code 28, from the directory /sys/bus/w1/devices/w1_bus_master1/
(If your sensors are the econo type they are family code 22, so change 28 to 22 after grep)
Then it calls the conversion routine 'w1_slave' for each device
The returned two lines from each device are piped through the grep command which returns the line containing the temperature result
The sed command gives us the end of the line following 't=' which is the 5 digit temperature
A formatted date & time is put in front and the result is output to a file with the device name in folder /var/1w_files
Each line looks like this
22-12-2012 09:45:01 23034

Note the back ticks (4 in total) in the script - these are NOT replaceable by single quotes

Make the file 1w_logging.sh executable for you
sudo chmod 0770 1w_logging.sh
sudo chown anita2R 1w_logging.sh

Now add a task to the cron system using the command 'crontab -e' (don't use sudo for this - if you do it will create cron jobs that run as root rather than as you)
Add the following line to crontab - it will run the 1w_logging.sh script on a regular schedule
0,15,30,45 * * * * /home/anita2R/1w_logging.sh

The command part of the cron line matches the full path to where you saved 1w_logging.sh
In this example temperatures are logged every 15 minutes of every hour of every day
If it is the first time you have used cron, it asks you what text editor it will use - select the one you prefer
Save and close crontab

You will now have a flat file for each temperature sensor on your 1-wire system which will be updated at the interval set in crontab -e

When you add a new temperature sensor just create a file for it in the /var/1w_files folder
e.g. echo "##date time temperature" > 28-0000018a3b30
The logging script will automatically start logging the new sensor - you don't need to edit anything else

Hope this works for you - I only set this up yesterday so it has been running for less than 24 hours
You will need to find a way to manage the log files - some sort of archiving system
You could use cron jobs to do this, say weekly

I will post how I charted the data from these log files in another post - I used a program called gnuplot

Hope this helps
Posts: 106
Joined: Sun Dec 23, 2012 6:55 pm
by repton » Mon Dec 24, 2012 6:11 pm
anita2r wrote:Install pre-compiled kernel and modules:
sudo su
cd /boot
wget http://www.frank-buss.de/raspberrypi/kernel-rpi-w1.tgz
tar -xzf kernel-rpi-w1.tgz
rm -f kernel-rpi-w1.tgz
cd /lib/modules
wget http://www.frank-buss.de/raspberrypi/modules-rpi-w1.tgz
tar -xzf modules-rpi-w1.tgz
rm -f modules-rpi-w1.tgzls
sync
exit
sudo reboot


If you have a vaguely recent kernel on your RasPi then you don't need to do any of this as the code is already compiled in there.

Paul
UK Supplier of 1-Wire components, kits and modules:
http://www.sheepwalkelectronics.co.uk/
Posts: 84
Joined: Sat Mar 17, 2012 6:06 pm
Location: North Yorkshire, UK.
by anita2r » Mon Dec 24, 2012 7:44 pm
Thanks for that information Paul

I've only been using Linux for 6 months and my Raspberry Pi for 2 weeks so it's often hard to know if what you find on the internet is out of date

It's ALL new to me ...

Thanks again
anita2R
Posts: 106
Joined: Sun Dec 23, 2012 6:55 pm
by anita2r » Wed Dec 26, 2012 10:00 pm
Creating charts from the log files

This is how I used the gnuplot program to automatically chart my data.

The data is held in simple flat files in this format:
22-12-2012 09:00:02 21187
one line per reading - in this case 21187 is the temperature reading from the 1-wire sensor - 21.187 C

The data for each sensor is held in a file with the same name as the sensor ID
All the files are in a folder /var/1w_files
In my case ls /var/1w_files shows this:
28-0000018a36db 28-0000018a36f2 28-0000018a3b30 28-0000018a4be8 28-0000018a5826 28-0000018a67e2

I installed gnuplot with:
sudo apt-get install gnuplot

gnuplot creates charts using a combined script and template file
(This is the first time I have used gnuplot, so my use of terms may be poor!)

Here is a template file I created to output a chart in png format using data from two sensors for a 24 hour period:

#!/usr/bin/gnuplot
reset
set terminal png size 1024,512
set output "/var/www/hvac/Plenum24hrsTo26122012-1558.png"
set xdata time
set timefmt "%d-%m-%Y %H:%M:%S"
set format x "%H:%M"
set xtics 3600 rotate font "arial,6" nomirror
set mxtics 4
set xlabel "Time" font "arial,12"
set xrange ["25-12-2012 15:58":"26-12-2012 15:58"]
set ylabel "Temperature (C)" font "arial,12"
set yrange [15:40]
set ytics font "arial,10"
set title "Supply & Return Air Temperatures"
set key reverse Left outside font "arial,10"
set grid
set style data linespoints
plot "/var/1w_files/28-0000018a36db" using 1:($3/1000) title "Return air", \
"/var/1w_files/28-0000018a4be8" using 1:($3/1000) title "Supply air"

This creates a basic line chart called 'Plenum24hrsTo26122012-1558.png' in the folder /var/www/hvac/ - set output creates this, although you can run this file without the output command and pass the folder/name information as a parameter
The data for the chart is specified in the line or lines following the command 'plot'
The plot command is one long line with ', \' at the end of lines allowing the text to be split over multiple lines
The first part of each line to be charted gives the path and filename of the data:
"/var/1w_files/28-0000018a36db"
The next part starts with the word 'using' which identifies which parts of the data in the file to use. Data is separated by white space
If your data was just two columns, 'using 1:2' would take the x-axis data from the first column and the y-axis data from the second column
The data I used was in three columns with the temperature in the third column, so 'using 1:3 would have worked
In this example the $ sign allows the data in that column to be manipulated before being charted and as the temperature values need to be divided by a thousand to display normally I used 'using 1:($3/1000)'
Finally there is 'title' which provides the legend for this particular line on the chart

The temperature data is a timeseries and this is setup by the line 'set xdata time', so the x-axis is a time series and the command set timefmt "%d-%m-%Y %H:%M:%S" must have exactly the format that the date/time information is stored in. Although the date and time are in columns 1 & 2, the set timefmt allows both columns to be used as a single date/time 'column'
Note that the x-axis information on the plot line is 'using 1:' even though the x-axis will show times for this 24 hour chart which are in column2.
I started by doing this: 'using 2:($3/1000)' and I wasted a lot of time trying to work out why it wouldn't work!!!
'using1:($3/1000)' works just fine

Now some of the other commands:
set format x "%H:%M" allows you to specify how the date/time will be displayed on the x-axis - you don't have to use the same format that the date/time data is stored in
set xtics 3600 rotate font "arial,6" nomirror - the 3600 is the interval in seconds for major ticks on the x axis (obviously only applies to date series) and 3600 is 1 hour, so hourly major tick marks with grid lines
set mxtics 4 gives three minor ticks between the major ones - (4, 15 minute time periods)
nomirror suppresses ticks along the top border (when used in the xtics line)
and range specifies the date/time range to use - note that as there is a space in the date/time data, you must use double quotes and the range information must be exactly as it is stored in the log files

I think that the other commands are self-explanatory

Please note that as I have only been using gnuplot for a couple of days, my use of it and the description is rudimentary - but at least it creates a usable output.

Automating the process
I soon realized that having to create a new format every time I wanted a new chart was just too much ! What I read suggested that I couldn't pass lots of parameters to gnuplot in the way you can with a bash script, so I decided to write a bash script that could be automated
The script then creates a new gnuplot format file containing the changed information and then runs it.

This is the sequence:
1. At 07:59 crontab calls my script
2. The script creates the range for the data based on the date/time it is called and a date/time 24 hours earlier - so the range is effectively 8AM yesterday to 7:45AM today (the temperatures are logged at 15 minute intervals)
3. The script creates a name for the output chart png image using the end time
4. It writes a gnuplot format file - like the one shown above (which was generated by the script although not called from crontab)
5. It makes the file executable and then
6. the script calls the gnuplot format file which generates the chart image file

Here is my script - it is in my home folder: /home/anita2R/1w_plot_SR_last24hr.sh
Code: Select all
#!/bin/bash
#
# a script to create and run a gnuplot template file for the last 24 hours
#
# create name of gnuplot template file
PLOTOUT="/home/anita2R/gnuplotSRlast24.gp"
#
# create end time = time when this script is called
PLOTEND=`date +"%d-%m-%Y %H:%M"`
#
# create start time 24 hours ago
PLOTSTART=`date -d"yesterday" +"%d-%m-%Y %H:%M"`
#
# create 'png' chart file name using date & time now i.e. the end date/time
PLOTPNG=/var/www/hvac/Plenum24hrsTo`date +"%d%m%Y-%H%M"`.png
#
# create gnuplot format file & first line
echo "#!/usr/bin/gnuplot" > $PLOTOUT
#
# append remaining lines:
echo "reset" >> $PLOTOUT
echo "set terminal png size 1024,512" >> $PLOTOUT
echo "set output \"$PLOTPNG\"" >> $PLOTOUT
echo "set xdata time" >> $PLOTOUT
echo "set timefmt \"%d-%m-%Y %H:%M:%S\"" >> $PLOTOUT
echo "set format x \"%H:%M\"" >> $PLOTOUT
echo "set xtics 3600 rotate font \"arial,6\" nomirror" >> $PLOTOUT
echo "set mxtics 4" >> $PLOTOUT
echo "set xlabel \"Time\" font \"arial,12\"" >> $PLOTOUT
echo "set xrange [\"$PLOTSTART\":\"$PLOTEND\"]" >> $PLOTOUT
echo "set ylabel \"Temperature (C)\" font \"arial,12\"" >> $PLOTOUT
echo "set yrange [15:40]" >> $PLOTOUT
echo "set ytics font \"arial,10\"" >> $PLOTOUT
echo "set title \"Supply & Return Air Temperatures\"" >> $PLOTOUT
echo "set key reverse Left outside font \"arial,10\"" >> $PLOTOUT
echo "set grid" >> $PLOTOUT
echo "set style data linespoints" >> $PLOTOUT
echo "plot \"/var/1w_files/28-0000018a36db\" using 1:(\$3/1000) title \"Return air\", \\" >> $PLOTOUT
echo "\"/var/1w_files/28-0000018a4be8\" using 1:(\$3/1000) title \"Supply air\"" >> $PLOTOUT
#
# make our new gnuplot template executable
chmod 0760 $PLOTOUT
#
# call the new gnuplot template file
$PLOTOUT
#
exit 0

Note that several lines in the script use backticks - these cannot be replaced by single quotes
In the echo lines all double quotes that must appear in the gnuplot format file are 'escaped' using backslashes as in this line:
echo "set xlabel \"Time\" font \"arial,12\"" >> $PLOTOUT
In the gnuplot format file this is how it comes out:
set xlabel "Time" font "arial,12"

Now add a line to crontab to run the script each morning:
crontab -e
add this line:
58 07 * * * /home/anita2R/1w_plot_SR_last24hr.sh
write & exit crontab

The script can be tested or used at anytime - it does not have to run from crontab
/home/anita2R/1w_plot_SR_last24hr.sh

You can create several of these script files using different temperature sensors and appropriate titles/labels - but remember to change the gnuplot format filename in the line PLOTOUT="/home/anita2R/gnuplotSRlast24.gp"
I used .gp just to make it easier to identify the format files - but it is not required

Also note that as the file 1w_plot_SR_last24hr.sh is a bash script you can pass parameters to it and have the script use them - for example to change the sensors used or to change the range
I tried changing the start date/time line to this:
Code: Select all
PLOTSTART=`date -d"$1 hours ago" +"%d-%m-%Y %H:%M"`

and then calling it like this:
./1w_plot_SR_last24hr.sh 4
and it created a chart with just the last 4 hours of data
(as '4' was the first parameter passed, $1 in the script was replaced by 4)

Hope this helps you to get your 1-wire system up and producing usable output
anita2R
Posts: 106
Joined: Sun Dec 23, 2012 6:55 pm
by drewibbo » Tue Apr 09, 2013 5:44 pm
Hi,

I have done pretty much the same thing on my website. I have a Pi logging external temperatures that saves to a text file. This is then uploaded to my website and converted into a graph. My tutorial makes use of Cron, FTP, and reading the data from the sensor on a half hour basis.

Tutorial: http://andyseasysite.com/?p=11

Live demo: http://www.andyseasysite.com/pifiles/graph.php

Have fun :D
Pi Pi Pi...
User avatar
Posts: 35
Joined: Tue Feb 26, 2013 11:54 am
Location: Worthing, UK