User avatar
tonyhughes
Posts: 951
Joined: Wed Dec 26, 2012 3:46 am

TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $3.05

Fri Aug 30, 2013 12:55 am

Temperature sensing with Bash.
No Python.
No C/C++.
5 minutes including wiring the parts and creating the script.

LETS GO!

I took the following:

* Raspberry Pi running up to date Raspian.

and added:

* One 4.7k resistor (5 cents at my local electronics shop - but you can get cheaper per item in bulk).
* One DS18B20 temperature sensor ($3 from a New Zealand auction site).

Wired them up according to this diagram (note the Pi cobbler and breadboard aren't required for this....):

Image

Then get the unique ID for your sensor:

Code: Select all

$ sudo modprobe w1-gpio
$ sudo modprobe w1-therm
$ cd /sys/bus/w1/devices
$ ls
... the unique ID is 28-xxxxxxxxxxxx. Use this ID in the following script.

Create a script:

Code: Select all

$ nano ~/temp.sh
Make it executable:

Code: Select all

chmod +x temp.sh
Copy and paste this code in (remember to insert your unique sensor ID):

Code: Select all

#! /bin/bash
sudo modprobe w1-gpio
sudo modprobe w1-therm
roomtemp=$(cat /sys/bus/w1/devices/28-xxxxxxxxxxxx/w1_slave | grep  -E -o ".{0,0}t=.{0,5}" | cut -c 3-)
echo "Temperature: $roomtemp"
And save it by pressing CTRL+X and confirm the filename.

Now run...

Code: Select all

$ ./temp.sh
and you will see the following...

Code: Select all

[email protected] ~ $ ./temp.sh
Temperature: 22500
[email protected] ~ $
Where 22500 is 22.5 degrees...

That's it.

From here the world is your oyster - you might want to do maths on the output, run multiple sensors, feed the data to a server, graph it, log it, whatever!

# Note the image is hotlinked from Adafruit - if Adafruit or RPF don't like this, I'll find a free image to re-host. Adafruit are awesome - buy stuff from them...
# Note that code/commands above are a combination of code lifted from other tutorials, and dirty hacks found on the internet, there might be better ways than this.

User avatar
tonyhughes
Posts: 951
Joined: Wed Dec 26, 2012 3:46 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Sat Aug 31, 2013 4:52 am

If there is any interest, I can elaborate on my setup, which currently includes:

2 sensors on one RPi (super easy by the way, still using Bash) (but I am going to have 5 sensors across 4 RPis soon).
Temperatures displaying on my lock screen of my Android phone (using Tasker & HTTP GET).
Tasker being able to do things like send temperatures to my partner on request, and at scheduled times.

Plus I am going to home brew some sort of basic logging system, possibly also in Bash.

User avatar
joan
Posts: 13617
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Sat Aug 31, 2013 7:46 am

Good job. Have you tried to see what distance from the Pi you can manage with the devices?

User avatar
tonyhughes
Posts: 951
Joined: Wed Dec 26, 2012 3:46 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Sun Sep 01, 2013 1:47 am

No, I need to though - I am hoping to get 10-15M working, so that I can simply use one Pi for the sensors I need.

I was hoping to run one of my Raspbmc box, but it appears the 1-wire support is not in that kernel :(

User avatar
Dan`
Posts: 2
Joined: Thu Oct 03, 2013 6:34 am
Location: Australia/Adelaide

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Oct 03, 2013 6:53 am

tonyhughes wrote:If there is any interest, I can elaborate on my setup, which currently includes:

Temperatures displaying on my lock screen of my Android phone (using Tasker & HTTP GET).
Tasker being able to do things like send temperatures to my partner on request, and at scheduled times.
im definately keen to hear more about this. i have just setup my RPi to log 2 ds1820's (more about to be added too) in cacti and will have it setup to email me once it reaches threshold temps (i had this working a year ago but with a usb temp sensor) but would be very interested to hear about having it show on my fone as well.
Cheers
Dan
One By One The Penguins Are Stealing My Sanity

spatimouth01
Posts: 1
Joined: Thu Oct 03, 2013 2:18 pm

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Oct 03, 2013 2:24 pm

So far I've installed a sensor on each of my 3 raspberry pis. They work pretty well, but needed some calibration math to output the true temp reading in F degrees. One thing I can't figure out is how to setup a private html page that outputs the current live temperature reading. The only ones I can find and get working are logging graphs in C degrees. Can anyone point me to something that would work? Thanks

supermarcie
Posts: 1
Joined: Tue Dec 10, 2013 8:04 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Tue Dec 10, 2013 8:07 am

Hi tonyhughes,

is there a possibility to share the code that you used for your project?

GMawston
Posts: 18
Joined: Mon Jul 02, 2012 7:11 pm

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Mon Dec 16, 2013 12:41 pm

The guide is excellent and does exactly what is required. If you want to polish it off have a quick look at the video I did that shows you how to get the readings to display on a web page. I can easily see what the temperature is anywhere in the world now.

http://www.youtube.com/watch?v=4B4bBqEgYKo

funtomas
Posts: 9
Joined: Mon Dec 02, 2013 10:12 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Sat Jan 04, 2014 6:12 pm

sudo apt-get install bc
nano ./bin/thermometer.sh
chmod +x ./bin/thermometer.sh

Code: Select all

#!/bin/bash
red='\e[0;31m'
yellow='\e[1;33m'
green='\e[0;32m'
NC='\e[0m' # No Color
#Black       0;30     Dark Gray     1;30
#Blue        0;34     Light Blue    1;34
#Green       0;32     Light Green   1;32
#Cyan        0;36     Light Cyan    1;36
#Red         0;31     Light Red     1;31
#Purple      0;35     Light Purple  1;35
#Brown       0;33     Yellow        1;33
#Light Gray  0;37     White         1;37
sudo modprobe w1-gpio
sudo modprobe w1-therm
echo
echo -e "${yellow}<-${green} T H E R M O M E T E R ${yellow}->${NC}"
echo
roomtemp=$(cat /sys/bus/w1/devices/28-000004eec632/w1_slave | grep  -E -o ".{0,0}t=.{0,5}" | cut -c 3-)
cputemp=$(cat /sys/class/thermal/thermal_zone0/temp)
echo -e "${red}Room temperature ${yellow}= ${NC}"$(bc <<< "scale=3; $roomtemp/1000")"${red}'C${NC}"
echo -e "${red}CPU temperature  ${yellow}= ${NC}"$(bc <<< "scale=3; $cputemp/1000")"${red}'C${NC}"
echo -e "${red}Temp difference  ${yellow}= ${NC}"$(bc <<< "scale=3; ($cputemp-$roomtemp)/1000")"${red}'C${NC}"
echo

anita2r
Posts: 226
Joined: Sun Dec 23, 2012 6:55 pm
Location: Ottawa, Canada

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Mon Jan 06, 2014 1:59 am

tonyhughes
Temperature sensing with Bash.
Here is a bit more bash script - (Python or C not needed)
This finds all your sensors automatically, reads the temperatures, checks for errors, does a re-read if there was an error, then logs the results to individual sensor files.

Code: Select all

#!/bin/bash
# a script to read and save temperature readings from all the group 28 1-wire temperature sensors
#
# get all devices in the '28' family
FILES=`ls /sys/bus/w1/devices/w1_bus_master1/ | grep '^28'`
# iterate through all the devices
for file in $FILES
    do
      # get the 2 lines of the response from the device
      GETDATA=`cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave`
      GETDATA1=`echo "$GETDATA" | grep crc`
      GETDATA2=`echo "$GETDATA" | grep t=`
      # get temperature
      TEMP=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
      #
        # test if crc is 'YES' and temperature is not -62 or +85
        if [ `echo $GETDATA1 | sed 's/^.*\(...\)$/\1/'` == "YES" -a $TEMP != "-62" -a $TEMP != "85000"  ]
           then
               # crc is 'YES' and temperature is not -62 or +85 - so save result
               echo `date +"%d-%m-%Y %H:%M:%S "; echo $GETDATA2 | sed -n 's/.*t=//;p'` >> /var/1w_files/$file
           else
               # there was an error (crc not 'yes' or invalid temperature)
               # try again after waiting 1 second
               sleep 1
               # get the 2 lines of the response from the device again
               GETDATA=`cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave`
               GETDATA1=`echo "$GETDATA" | grep crc`
               GETDATA2=`echo "$GETDATA" | grep t=`
               # get the temperature from the new response
               TEMP=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
                  if [ `echo $GETDATA1 | sed 's/^.*\(...\)$/\1/'` == "YES" -a $TEMP != "-62" -a $TEMP != "85000" ]
                      then
                      # save result if crc is 'YES' and temperature is not -62 or +85 - if not, just miss it and move on
                      echo `date +"%d-%m-%Y %H:%M:%S "; echo $GETDATA2 | sed -n 's/.*t=//;p'` >> /var/1w_files/$file
                  fi
               # this is a retry so log the failure - record date/time & device ID
               echo `date +"%d-%m-%Y %H:%M:%S"`" - ""$file" >> /var/1w_files/err.log
           fi
    done
exit 0
Make script executable
Call from crontab at required lntervals

Regards

anita2R

lifebeginsatsixty
Posts: 26
Joined: Fri Mar 29, 2013 3:39 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Wed Jan 08, 2014 5:37 pm

Well, I wonder if a shell script and one of these temp sensors will be the way to control my sous vide cooking (rather do it simpler than Mathematica). I've done around thirty runs of sous vide with a basic PID controller and a 6 L. rice cooker and will do another tomorrow. Not very knowledgable about Linux or the Pi. Did hook up a DS18B20 once just to see if it'd work.

The PID controller uses a PT-100 (precision resistor) sensor and outputs a 3v. signal I use to control a solid-state relay on a heat sink. This rice cooker draws 1000 w. and is the simplest kind, the old-fashioned kind. Coming up to temp there's a lot of overshoot as it isn't looking at the approach rate as it comes close to the set point to modify the heating. Doesn't seem to cause me problems but I'd rather it do better.

I'm cooking steak medium rare so I set it for 39 C. for an hour or two, then 49 C. for an hour or two, then 52.6 C for the actual cooking of an hour or two usually (times depend on thickness). The two lower temp settings are for something called 'turbo aging' if I remember right; pulled off the sous vide forums as an idea worth trying. Whether it helps or not the steaks turn out great so I'm happy.

I don't know the relative merits or precision of the PT-100 and the DS18B20 sensors or whether it'd be simple to use the PT-100 with the Pi. I like simple. Any of the more experienced people feel like putting a little time into this?

Thanks,
lifebeginsatsixty

anita2r
Posts: 226
Joined: Sun Dec 23, 2012 6:55 pm
Location: Ottawa, Canada

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Wed Jan 08, 2014 8:01 pm

Hi,

I don't know enough about your current programming, to be able to say whether a Pi and some bash script would be easier.

With the Pi you have potential for such things as remote control via a web interface, visual display of temperature and cooking progress, and even automatically keeping records of what you have done.

One thing to note about 'pure' bash scripts is that you only get integer math. To be able to calculate to decimal values you have to do something such as piping the calculations through a program called 'bc', (I note that you have cooking temperatures down to +/- 0.5 degrees).

The 1-wire temperature sensors are more than accurate enough for cooking, and of course their output is digital - no analogue to digital conversion required, although the Pi's 1-wire system temperature results must be divided by 1000 to get the Centigrade value.

With a 1-wire system it's easy to add more sensors, so you could monitor in more than one spot

Regards

anita2R

lifebeginsatsixty
Posts: 26
Joined: Fri Mar 29, 2013 3:39 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 2:17 am

Hello back,

Currently what programming I might do is "done" by the little gizmo called a PID controller. You give it a target temperature, hook it up to the sensor (mine uses a PT-100) and the relay control side. The 220v wiring to the rice cooker and a 220v cord to plug it all in and that's all. The PID controller has the "programming" inside and you never see it.

So that's as simple for programming as you can get - zero. Nothing. Maybe I don't want it quite that simple but not as much as using the Mathematica language now available for the Pi. That's where I saw the mention, in this announcement:

Mathematica and the Wolfram Language on Raspberry Pi: a guest post from Wolfram Research
8 comments Tags: Arnoud Buzing, Mathematica, Wolfram Language, Wolfram Research 6 days ago by liz

And got the idea, bet you could do that in the shell and be closer to what's actually going on - have more fun. I'm just now starting to use the shell on another project (and another machine). When PERL was taking far too long to do some stuff I wanted to a big text file I tried system calls from PERL to egrep and saw it was a lot faster so I'm slowly developing that. Of course I could do it in PERL easier but surely it wouldn't hurt me to learn a bit about using the shell.

Just started the steak for today - wanted to have a DS18B20 in there to check it against what I know works but didn't make it. Next time.

On integer arithmetic, doesn't that sensor return the temp x 100 or x1000 anyway? Seems like doing the math at that level using integers would be plenty accurate.

Thanks,
lifebeginsatsixty

User avatar
Richard-TX
Posts: 1549
Joined: Tue May 28, 2013 3:24 pm
Location: North Texas

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 4:29 am

lifebeginsatsixty wrote:W

I'm cooking steak medium rare so I set it for 39 C. for an hour or two, then 49 C. for an hour or two, then 52.6 C for the actual cooking of an hour or two usually (times depend on thickness).
6 hours to cook a steak and at temps below 125 F?
Richard
Doing Unix since 1985.
The 9-25-2013 image of Wheezy can be found at:
http://downloads.raspberrypi.org/raspbian/images/raspbian-2013-09-27/2013-09-25-wheezy-raspbian.zip

anita2r
Posts: 226
Joined: Sun Dec 23, 2012 6:55 pm
Location: Ottawa, Canada

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 5:47 am

Hi,

If you are OK with integer temperatures, then bash scripts are straightforward.

For some reason, and I don't know what it is, when you read temperatures from 1-wire sensors on the Pi, the values have to be divided by 1000. A value of 49562.5 is a temperature of 49.5625 C.

The 1-wire temperature sensors actually return the temperature as 2-bytes from their scratchpad memory. The default setting at the sensor end results in readings to 0.0625 degrees C. If you want to be pedantic, the temperature data is stored as a 16-bit sign-extended two’s complement number in the temperature register of the sensor and this is what is transmitted in the two bytes.
The Pi's 1-wire modules read & convert this to a value such as 49562.5. I don't know why the modules don't convert direct to degrees C.

As far as I know, using PERL is going to be faster than using bash scripts. I use PERL a lot, and keep bash scripts for simple actions. However for your temperature conversions and simple gpio control, the minor speed differences are of no consequence, so give it a go with Bash scripts. The odd millisecond is not going to ruin a steak.

As to Mathematica - I haven't explored it at all - but for what you are doing, bash, perl or python scripts will suffice and probably with a smaller learning curve.

Regards

anita2R
Only a few days to our next BBQ and great steaks - charcoal BBQ with cooking time based on a sophisticated BDRU system.








BDRU:
(Beer Drinking Rate Units)

lifebeginsatsixty
Posts: 26
Joined: Fri Mar 29, 2013 3:39 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 12:04 pm

Richard, yup, you heard me right. This url might be a place to start if you're interested:
http://forums.egullet.org/topic/140062- ... ontroller/

anita2r, I'll go for it. And coincidentally immortalize your guiding philosophy to BBQ steaks as a variable or subroutine name. My development is usually a slow-motion kindof thing, we'll see what happens. I know I've seen something about tapering off the power input as a setpoint is neared (?) that will help the business. Should be fun.

Best,
lifebeginsatsixty

User avatar
Richard-TX
Posts: 1549
Joined: Tue May 28, 2013 3:24 pm
Location: North Texas

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 12:22 pm

I am happy to see other people using shell scripts to do what they need. Having said that, I personally avoid bash whenever possible. I use /bin/sh for all my scripts. The reason is simple. Not every *nix system in the world has bash but every *nix system has /bin/sh. As a personal shell, I use ksh and then set the mode to vi. (set -o vi) Previous command search, recall, and full screen editing of commands are the primary reasons for using ksh. Bash has most, but not all of these features.

Python is a nice prototyping language but it isn't needed for everything.
Richard
Doing Unix since 1985.
The 9-25-2013 image of Wheezy can be found at:
http://downloads.raspberrypi.org/raspbian/images/raspbian-2013-09-27/2013-09-25-wheezy-raspbian.zip

User avatar
Richard-TX
Posts: 1549
Joined: Tue May 28, 2013 3:24 pm
Location: North Texas

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 12:50 pm

I use the following construct to do division in a shell script.
VAR=`expr $VAR / 1000`

an example is:
VAR=100000
VAR=`expr $VAR / 1000`
echo $VAR

Other basic math functions can be done as well as substring functions with expr.

The nice thing about *nix systems is that there is no one "right" answer. If it works, then it is a success. :D :D
Richard
Doing Unix since 1985.
The 9-25-2013 image of Wheezy can be found at:
http://downloads.raspberrypi.org/raspbian/images/raspbian-2013-09-27/2013-09-25-wheezy-raspbian.zip

User avatar
Richard-TX
Posts: 1549
Joined: Tue May 28, 2013 3:24 pm
Location: North Texas

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 1:05 pm

lifebeginsatsixty wrote: I've seen something about tapering off the power input as a setpoint is neared (?) that will help the business. Should be fun.
Hysteresis is an interesting problem especially when dealing with cooking/heating. One has to take care of overshoot and the possibility of too many on-off cycles. Remember the term "fuzzy logic"? Now it is called "adaptive ....". That is pretty much what you need here. The problem gets stickier if the heating element output can be infinitely adjusted.

You will succeed. Of that there is no doubt. :D :D

Richard
Richard
Doing Unix since 1985.
The 9-25-2013 image of Wheezy can be found at:
http://downloads.raspberrypi.org/raspbian/images/raspbian-2013-09-27/2013-09-25-wheezy-raspbian.zip

achrn
Posts: 326
Joined: Wed Feb 13, 2013 1:22 pm

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 2:10 pm

lifebeginsatsixty wrote: Currently what programming I might do is "done" by the little gizmo called a PID controller. You give it a target temperature, hook it up to the sensor (mine uses a PT-100) and the relay control side. The 220v wiring to the rice cooker and a 220v cord to plug it all in and that's all. The PID controller has the "programming" inside and you never see it.
There isn't much 'programming' to a PID loop, and in fast-moving applications you get 95% of the benefit in the P alone. In slow-moving ones (such as sous-vide, which it seems we are discussing) you get 90% in the P the next 9% of benefit in the I.

The programming you don't get to see is the optimisation of the three magic parameters that go into the PID algorithm. This (the 'tuning') is what uses proprietary approaches / fuzziness / adaptiveness etc.

If you want to implement PID (or PI, or P) controller, the best reference I know of is to start reading at http://brettbeauregard.com/blog/2011/04 ... roduction/ As I understand it, Brett is a professional programmer-of-PID-code. Last I corresponded with him, his employer wouldn't let him talk about tuning (non-disclosure clauses in employment contracts etc) but in all other respects that series of articles is excellent. The code examples are all in Arduino, but it's all explained very clearly. As long as your maths is up to it, implementing it in another language is easy if you follow step-by-step through the articles.

anita2r
Posts: 226
Joined: Sun Dec 23, 2012 6:55 pm
Location: Ottawa, Canada

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Thu Jan 09, 2014 3:00 pm

Richard-TX wrote:Having said that, I personally avoid bash whenever possible. I use /bin/sh for all my scripts. The reason is simple. Not every *nix system in the world has bash but every *nix system has /bin/sh.
I am not in IT and have only been using Linux for a couple of years, so I wasn't too worried about using bash - when I started I didn't even know that bash was not part of all *nix flavours.

I use bash for a lot of functions, but if I need to expand and re-write the function I re-do it in Perl.
I find that Perl always seems to have a module for what you want to do.

For example I create daily statistics from temperature log files - originally in Bash scripts, but when I wanted to speed up the process and read the log files from the end backwards, rather than wasting time starting at the beginning, I used Perl and the module:
use File::ReadBackwards;
Wow - what an improvement in performance, especially when near the end of a month when the log file was at its largest

Also as I am often working with log files with date & time stamps, I find that Perl is great for date manipulation. For example a 24 hour statistic needs to have a last date/time 24 hours less 1 second after the start date/time and Perl has a module with a function that will do just that.
Add_Delta_DHMS in Date::Calc

Regards

anita2R

lifebeginsatsixty
Posts: 26
Joined: Fri Mar 29, 2013 3:39 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Sat Jan 11, 2014 6:25 pm

Thanks for the input.

Richard, I'm probably going into PERL with this and have my shell learning come from other things. See following.

I'm thinking about signing "Doing steaks since 1965" or something like that. Haven't put my rice cooker on variable power input, just clunk on off. Well, no "clunk" with solid-state relays.

Achm, I got the series you refer to. That finished product is 105 lines of C or C-ish code, not all code of course. For the math, I'll have to depend on his taking the initial equation and putting it into code correctly. I'll start with that and put it into PERL which I somewhat understand. Maybe I can scaffold it and run it as a model while actually doing the work still with the PID I'm using now and compare the results.

Best to all,
lifebeginsatsixty

lifebeginsatsixty
Posts: 26
Joined: Fri Mar 29, 2013 3:39 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Mon Jan 13, 2014 10:54 am

Trying to get the basic wiring going at the same time. Question: with the wiring Pi stuff installed, are the basic instructions at the top of this page (thread) still right? I've assumed I may need to add the "/w1_bus_master1" to the line "cd /sys/bus/w1/devices" but still not getting anything like a 28- file or folder.

lifebeginsatsixty

anita2r
Posts: 226
Joined: Sun Dec 23, 2012 6:55 pm
Location: Ottawa, Canada

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Mon Jan 13, 2014 12:17 pm

Hi,

These are the notes I made when I first started using 1-wire sensors on the Pi.
(replace <username> with whichever user you are logged on as)
(the notes include a script that runs every 5 minutes to log the results from all sensors - it's not required to make the 1-wire sensors work)

Load the modules:
sudo su
modprobe wire
modprobe w1-gpio
modprobe w1-therm

Make modules load at boot:
Add these three lines to the file /etc/modules:
wire
w1-gpio
w1-therm

Examine the system:
ls /sys/bus/w1/devices/w1_bus_master1/
This shows these 'functions':
driver, subsystem, power, uevent
w1_master_add, w1_master_attempts, w1_master_max_slave_count, w1_master_name, w1_master_pointer
w1_master_pullup, w1_master_remove, w1_master_search, w1_master_slave_count, w1_master_slaves & w1_master_timeout
When a 1-wire device is added it should show up here as well

Connect a 1-wire temperature sensor:
Connect VCC to 3.3V,
ground to ground and
Data to GPIO #4.
Then connect a 4.7K resistor (yellow, violet, red) from Data to VCC (3.3v).
Repeat the 'examine the system' steps and the temperature sensor should show up.
Here is a temperature measurement:
enter this command:
cat /sys/bus/w1/devices/w1_bus_master1/28-0000018a4be8/w1_slave
this returns:
49 01 4b 46 7f ff 07 10 f6 : crc=f6 YES
49 01 4b 46 7f ff 07 10 f6 t=20562
giving a temperature of 20.6 C (to 1 decimal place)

Log the data:
Start by creating a folder to hold the result files
sudo mkdir /var/1w_files
cd /var/1w_files
make a file for each device using its unique id
e.g. touch 28-0000018a4be8
Move back to the folder before:
cd ..
change ownership & permissions of all your new device log files:
sudo chown -R <username> 1w_files
sudo chmod -R 0760 1w_files

Create a logging script:
# gets all temperature sensor names from directory /sys/bus/w1/devices/w1_bus_master1/
# calls the conversion routine w1_slave for each device
# grep returns the line containing the temperature
# and sed gives us the end of the line following t=
#
# a formatted date & time is added to the result
# and the result is output to files with the device names in folder /var/1w_files
#
# save this file in your home directory - matching the path you used in crontab -e
#
# The script has been enhanced to catch known error conditions such as no temperature conversion
# by the sensor and CRC failures.
# A second read is attempted if there is one of these failures - but a repeat failure results in the
# sensor being ignored for the current read cycle so that a faulty sensor doesn't stop the whole
# process. A log is kept of errors, including date/time and sensor id.
#

The actual script is in the home/<username>/ folder and is named:
1w_logging.sh

Code: Select all

#!/bin/bash
# a script to read and save temperature readings from all the group 28 1-wire temperature sensors
#
# get all devices in the '28' family
FILES=`ls /sys/bus/w1/devices/w1_bus_master1/ | grep '^28'`
# iterate through all the devices
for file in $FILES
    do
      # get the 2 lines of the response from the device
      GETDATA=`cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave`
      GETDATA1=`echo "$GETDATA" | grep crc`
      GETDATA2=`echo "$GETDATA" | grep t=`
      # get temperature
      TEMP=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
      #
        # test if crc is 'YES' and temperature is not -62 or +85
        if [ `echo $GETDATA1 | sed 's/^.*\(...\)$/\1/'` == "YES" -a $TEMP != "-62" -a $TEMP != "85000"  ]
           then
               # crc is 'YES' and temperature is not -62 or +85 - so save result
               echo `date +"%d-%m-%Y %H:%M:%S "; echo $GETDATA2 | sed -n 's/.*t=//;p'` >> /var/1w_files/$file
           else
               # there was an error (crc not 'yes' or invalid temperature)
               # try again after waiting 1 second
               sleep 1
               # get the 2 lines of the response from the device again
               GETDATA=`cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave`
               GETDATA1=`echo "$GETDATA" | grep crc`
               GETDATA2=`echo "$GETDATA" | grep t=`
               # get the temperature from the new response
               TEMP=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
                  if [ `echo $GETDATA1 | sed 's/^.*\(...\)$/\1/'` == "YES" -a $TEMP != "-62" -a $TEMP != "85000" ]
                      then
                      # save result if crc is 'YES' and temperature is not -62 or +85 - if not, just miss it and move on
                      echo `date +"%d-%m-%Y %H:%M:%S "; echo $GETDATA2 | sed -n 's/.*t=//;p'` >> /var/1w_files/$file
                  fi
               # this is a retry so log the failure - record date/time & device ID
               echo `date +"%d-%m-%Y %H:%M:%S"`" - ""$file" >> /var/1w_files/err.log
           fi
    done
exit 0
Note the back ticks ` in the script - these are NOT replaceable by single quotes '.
The line starting 'FILES' gets all the temperature sensor device names from the folder 'w1_bus_master1/' (family code 28)
The lines starting GETDATA= get the two lines of data for each device then GETDATA1 gets the line with the crc and GETDATA2 gets the line with the temperature.

Make the 1w_logging script accessible
sudo chown <username> 1w_logging.sh
sudo chmod 0750 1w_logging.sh

Create a cron job to run the logging script at appropriate intervals
enter this command: (if crontab has not been used before it will ask you to select which text editor to use)
crontab -e
add this line
*/5 * * * * /home/<username>/1w_logging.sh

write/save & close the file - depending on text editor being used

That's it
I hope this helps

Regards

anita2R
Last edited by anita2r on Tue Jan 14, 2014 7:41 pm, edited 1 time in total.

lifebeginsatsixty
Posts: 26
Joined: Fri Mar 29, 2013 3:39 am

Re: TUTORIAL: DS18B20 temp sensor. No C or Python!!! Cost: $

Mon Jan 13, 2014 11:08 pm

Thanks Anita, big help for writing a script. Hope the steaks were good.

On the wiring answered my own question; adding a line to set the mode of the pin to input got things working again. Now for a little header cable to a breadboard.

Richard, my browser hadn't been showing the Hobbes before for some reason. Saw it the first time last night. I like Calvin & Hobbes a lot.

Best to all,
lifebeginsatsixty

Return to “Automation, sensing and robotics”