I set up two DS18B20 temperature sensors on my FishPi to monitor each side of the tank. While most scripts I found utilized Python to grab the temperature from the sensors, I of course wanted to do it in bash since while I understand Python I don’t “know” it well enough to write out a script that I would have to maintain.
With that being said, enter my simple bash script to grab the temperature from the sensors. The following script is for a single sensor but should give you a working idea of how to craft your own script to do the same.
The sensors themselves can be seen in the following directory, XXXXXXX being the ID of the sensor. Again if you have multiple sensors you will see multiple IDs to choose from.
The temperature is stored within that directory in the w1_salve file. If you cat the file you should see the following output.
65 01 4b 46 7f ff 0b 10 2c : crc=2c YES 65 01 4b 46 7f ff 0b 10 2c t=22312
The value we are looking for is the t=22312 which is the temperature stored in Celcius. Now that we have the value we need to parse that out into something more usable. Using the cut command you can grab this value quite easily. For example, this is how I am grabbing it for one of my sensors
cat /sys/bus/w1/devices/28-000006738761/w1_slave | tail -n1 | cut -d '=' -f2
The above command should give you the value of 22312. Now that you have the temperature in Celsius you can bring the script altogether and convert it to Fahrenheit as shown here. *Note you will need to make sure that you have the bc binary installed.
#!/bin/bash temp_c=`cat /sys/bus/w1/devices/28-000006738761/w1_slave | tail -n1 | cut -d '=' -f2` temp_f=`echo "scale=3; $temp_c/1000 * 9.0 / 5.0 + 32.0" | bc` echo $temp_f
If everything worked correctly you should see the temp in Fahrenheit such as 72.161 when running the script. I have included my complete script for outputting both temperature readings below (Mainly so I have it on file somewhere in case the Pi meets a sudden death).
#!/bin/bash temp_filter_c=`cat /sys/bus/w1/devices/28-000006738761/w1_slave | tail -n1 | cut -d '=' -f2` temp_filter_f=`echo "scale=3; $temp_filter_c/1000 * 9.0 / 5.0 + 32.0" | bc` temp_heater_c=`cat /sys/bus/w1/devices/28-00000673acb8/w1_slave | tail -n1 | cut -d '=' -f2` temp_heater_f=`echo "scale=3; $temp_heater_c/1000 * 9.0 / 5.0 + 32.0" | bc` echo "Filter temp: " $temp_filter_f echo "Heater temp: " $temp_heater_f