March 2, 2013

Formatting output from Raspberry Pi temperature sensors

Raspberry Pi crew released tools and drivers than enabled reading from CPU and GPU temperature sensors.

In order to read GPU temperature use:

$ /opt/vc/bin/vcgencmd measure_temp
$ temp=43.3'C

Reading CPU temperature is similar, just read value from sys file system:

$ cat /sys/class/thermal/thermal_zone0/temp
$ 43850

As you can see both outputs need additional formatting to get only number values from them, and if you wish to have decimal precision then it gets a bit more complicated...

GPU Temperature
Formatting GPU temperature output can be done with cut command, so lets show only characters from 6 to 9.

$ /opt/vc/bin/vcgencmd measure_temp|cut -c6-9
$ 43.3

CPU temperature
Acquiring and formatting CPU temperature is similar procedure but with a twist...

$ cat /sys/class/thermal/thermal_zone0/temp
$ 43850

CPU temperature is shown without decimal point, but it is obvious that numbers after first two are decimal.

If you just divide by 1000 in bash you loose precision of decimal places because bash doesn't work with decimal numbers :(

$ echo $((`cat /sys/class/thermal/thermal_zone0/temp`/1000))
$ 43

So lets try something else...

$ echo $((`cat /sys/class/thermal/thermal_zone0/temp|cut -c1-2`)).$((`cat /sys/class/thermal/thermal_zone0/temp|cut -c3-5`))
$ 43.312

Or you can use variable to get same effect:

CPUOUT=`cat /sys/class/thermal/thermal_zone0/temp`
CPU=`cut -c1-2 < << $CPUOUT`.`cut -c3-5 <<< $CPUOUT`
$ 43.312

This prints first two digits, then decimal point and lastly last three digits. If anybody has other solution please share it in the comments...