I am trying to use this bash code to get the temperature of my Raspberry Pi, convert to Fahrenheit and display both Fahrenheit and Celsius then save as text file:
#!/bin/bash
echo ""
cpu="$(/opt/vc/bin/vcgencmd measure_temp)"
far=$((cpu/1000))
far2=$((far*9))
far3=$((far2/5))
far4=$((far3+32))
echo "CPU => $((cpu/1000))' C or $((far4))' F"
echo ""
echo "Pi temp $far4 degrees F" > /var/www/html/pitemp.txt
However when i run it, the Fahrenheit is ok, but why is the Celsius not shown?
pi@raspberrypi:~ $ nano checkTemp.sh
pi@raspberrypi:~ $ ./checkTemp.sh
./checkTemp.sh: line 3: temp=40.0'C: command not found
CPU => 0' C or 32' F
pi@raspberrypi:~ $ /opt/vc/bin/vcgencmd measure_temp
temp=40.0'C
I checked the value of cpu and far but it seems not to be working. Any advice?[solved]
#!/usr/bin/env bash
echo ""
cpu="$(/opt/vc/bin/vcgencmd measure_temp | sed -E 's/.*=([0-9.]*).*/\1/')"
## convert to Fahrenheit
far=$( echo "$cpu * 9/5 + 32" | bc -l)
## Remove extra decimal digits
printf "CPU => %.2f' C or %.2f' F\n" "$cpu" "$far"
echo ""
printf "Pi temp %.2f degrees F\n" "$cpu" > /var/www/html/pitemp.txt
echo "C:$cpu F:$far"
this new code is working however the Fahrenheit seems has issue becasue the output is:
pi@raspberrypi:~ $ nano checkTemp.sh
pi@raspberrypi:~ $ ./checkTemp.sh
./checkTemp.sh: line 5: bc: command not found
CPU => 43.00' C or 0.00' F
C:43.0 F:
pi@raspberrypi:~ $ /opt/vc/bin/vcgencmd measure_temp
temp=43.0'C
pi@raspberrypi:~ $
/opt/vc/bin/vcgencmd measure_temp.invalid arithmetic operatorerror, not a command not found.