Fahrenheit
Posts: 22
Joined: Fri Feb 14, 2014 3:39 am

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Feb 14, 2014 3:44 am

yuusou wrote: I quite liked your script, so I decided to clean it up a little:

Code: Select all

#!/bin/bash
cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp)
cpuTemp1=$(($cpuTemp0/1000))
cpuTemp2=$(($cpuTemp0/100))
cpuTempM=$(($cpuTemp2 % $cpuTemp1))

gpuTemp0=$(/opt/vc/bin/vcgencmd measure_temp)
gpuTemp0=${gpuTemp0//\'/º}
gpuTemp0=${gpuTemp0//temp=/}

echo CPU Temp: $cpuTemp1"."$cpuTempM"ºC"
echo GPU Temp: $gpuTemp0
This works brilliantly! I hate to ask, but do you know what the calculations would be for Fahrenheit? Thanks!

Joe Schmoe
Posts: 4277
Joined: Sun Jan 15, 2012 1:11 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Feb 14, 2014 1:42 pm

This works brilliantly! I hate to ask, but do you know what the calculations would be for Fahrenheit? Thanks!
The basic formula is:

F = 1.8 * C + 32

E.g., 1.8 * 100 = 180 and 180 + 32 = 212

BTW, I think doing this in shell is weird. Yes, the previous poster gets "ain't I slick!" points for being able to do this kind of stuff in shell, but it's a lot more fluid in AWK.
And some folks need to stop being fanboys and see the forest behind the trees.

(One of the best lines I've seen on this board lately)

jamesh
Raspberry Pi Engineer & Forum Moderator
Raspberry Pi Engineer & Forum Moderator
Posts: 25435
Joined: Sat Jul 30, 2011 7:41 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Feb 14, 2014 1:53 pm

AndyD wrote:
phoenixDownunder wrote:temp=64.3'C Is that a bit high? Ambient is 44C here
I think that is reasonable. Is your Raspberry Pi working hard? It is around 30°C in my house at the moment and my Raspberry Pis are idle and running at 55.1°C and 55.6°C. It is going to 44°C today (again) looking forward to a cool change tonight after 5 very hot days.
You can have some of our spare rain if you want. Expecting another 30-40mm today....and we are in the dry part of the country.
Principal Software Engineer at Raspberry Pi (Trading) Ltd.
Contrary to popular belief, humorous signatures are allowed. Here's an example...
“I own the world’s worst thesaurus. Not only is it awful, it’s awful."

Fahrenheit
Posts: 22
Joined: Fri Feb 14, 2014 3:39 am

Re: [Tutorial] Show RPI's Temperature with a command.

Sat Feb 15, 2014 12:39 pm

Joe Schmoe wrote: The basic formula is:

F = 1.8 * C + 32

E.g., 1.8 * 100 = 180 and 180 + 32 = 212

BTW, I think doing this in shell is weird. Yes, the previous poster gets "ain't I slick!" points for being able to do this kind of stuff in shell, but it's a lot more fluid in AWK.
So I'd like to get the CPU temp from "/sys/class/thermal/thermal_zone0/temp" and have it display in Fahrenheit. Since you can't multiply decimals in shell scripts, any idea how to do that?

Joe Schmoe
Posts: 4277
Joined: Sun Jan 15, 2012 1:11 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Sat Feb 15, 2014 12:51 pm

So I'd like to get the CPU temp from "/sys/class/thermal/thermal_zone0/temp" and have it display in Fahrenheit. Since you can't multiply decimals in shell scripts, any idea how to do that?
I don't have my Pi up and running ATM, so I can't test this, but I think it would be like:

Code: Select all

gawk '{print "Temp in degrees Fahrenheit is:",$1/1000 * 1.8 + 32}' /sys/class/thermal/thermal_zone0/temp
And some folks need to stop being fanboys and see the forest behind the trees.

(One of the best lines I've seen on this board lately)

Fahrenheit
Posts: 22
Joined: Fri Feb 14, 2014 3:39 am

Re: [Tutorial] Show RPI's Temperature with a command.

Sat Feb 15, 2014 6:14 pm

Joe Schmoe wrote:
I don't have my Pi up and running ATM, so I can't test this, but I think it would be like:

Code: Select all

gawk '{print "Temp in degrees Fahrenheit is:",$1/1000 * 1.8 + 32}' /sys/class/thermal/thermal_zone0/temp
WOW, that's spot on! I had to change "gawk" to "awk," but that's perfect...simple and elegant. Thank you!

Joe Schmoe
Posts: 4277
Joined: Sun Jan 15, 2012 1:11 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Sat Feb 15, 2014 8:41 pm

I had to change "gawk" to "awk,"
If you don't have gawk on your system, you should fix this ASAP. For some stupid reason, Debian (including Debian-derived systems like Raspbian) use "mask" as the default AWK. This even though GAWK is the GNU AWK and the rest (modulo any other exceptions which may exist) of the "normal" (utility) software on a Linux system is the GNU versions of things. Anyway, nothing against "mask", but gawk is much better and you'll be glad you did.

And its only an "apt-get install" away…
And some folks need to stop being fanboys and see the forest behind the trees.

(One of the best lines I've seen on this board lately)

ionut
Posts: 1
Joined: Mon Feb 17, 2014 8:27 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Mon Feb 17, 2014 8:36 pm

Why not using this command here to display temperature:

Code: Select all

awk '{printf("\nrPI Temperature = %.1f °C\n\n",$1/1e3)}' /sys/class/thermal/thermal_zone0/temp
Result:
  • rPI Temperature = 55.1 °C

kerklein2
Posts: 2
Joined: Fri Apr 11, 2014 3:25 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Apr 11, 2014 3:39 pm

Anyone have thoughts on making this available via a web interface easily? I'm running Volumio on my Pi right now and would to be able just hit 192.168.1.XX:2000 or something and easily see the temp. Even slicker would be embedding it right into the existing Volumio UI.

User avatar
default_user8
Posts: 680
Joined: Mon Nov 18, 2013 3:11 am

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Apr 11, 2014 5:17 pm

There is a web app in the pi store that does that and more, it's called Raspberry Pi Web agent.
Two heads are better than one, unless one's a goat head.

kerklein2
Posts: 2
Joined: Fri Apr 11, 2014 3:25 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Apr 11, 2014 5:57 pm

That looks slick, but I'm having trouble with the Pi Store. Can it not be run via terminal on SSH? Installing Volumio means I can't access the standard GUI, at least as far as I know. Or, can the webagent be installed without Pi Store?

User avatar
TideMan
Posts: 249
Joined: Fri Jun 22, 2012 8:08 am
Location: ChCh, NZ

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Apr 11, 2014 9:04 pm

ionut wrote:

Code: Select all

awk '{printf("\nrPI Temperature = %.1f °C\n\n",$1/1e3)}' /sys/class/thermal/thermal_zone0/temp
Result:
  • rPI Temperature = 55.1 °C
How do you type the degree sign?
If you wish in this world to advance, your merits you're bound to enhance.
You must stir it and stump it and blow your own trumpet, or trust me you haven't a chance.
Ruddigore, G&S

Joe Schmoe
Posts: 4277
Joined: Sun Jan 15, 2012 1:11 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Apr 11, 2014 9:43 pm

How do you type the degree sign?
Good question.

But observe:

Code: Select all

$ gawk 'BEGIN {s=sprintf("%c%cC",0302,0260);print s}'
°C
$
I figured this out by cutting and pasting the string from my browser into "od -bc".
And some folks need to stop being fanboys and see the forest behind the trees.

(One of the best lines I've seen on this board lately)

User avatar
TideMan
Posts: 249
Joined: Fri Jun 22, 2012 8:08 am
Location: ChCh, NZ

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Apr 11, 2014 10:24 pm

Actually, on my m/c it is:

Code: Select all

awk 'BEGIN {s=sprintf("%cC",0176);print s}' 
But what I was getting at is how can you type the degree sign using the keyboard so that it appears in a post like this?
If you wish in this world to advance, your merits you're bound to enhance.
You must stir it and stump it and blow your own trumpet, or trust me you haven't a chance.
Ruddigore, G&S

User avatar
rpdom
Posts: 16349
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: [Tutorial] Show RPI's Temperature with a command.

Sat Apr 12, 2014 5:20 am

TideMan wrote: But what I was getting at is how can you type the degree sign using the keyboard so that it appears in a post like this?
On my laptop (running Debian Wheezy with xfce), I use Shift+AltGr+0 to get the "°" character. That's either Shift key, the Right Alt button and the Zero key. I guess something similar should work on the Pi, but I run all mine headless.

User avatar
BlackberryTart
Posts: 29
Joined: Fri Oct 03, 2014 1:06 am

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Oct 03, 2014 1:09 am

I made a shell script that shows Celsius and Fahrenheit. It requires bc. The formatting is sorta ugly, though. Here is the code:

Code: Select all

#!/bin/bash

milcel=$(cat /sys/class/thermal/thermal_zone0/temp)

echo "CPU Temperature:"
echo
echo "scale=3;$milcel/1000" | bc
echo "°C"
echo
echo "scale=3;(($milcel/1000)*(9/5))+32" | bc
echo "°F"

Here is the output:

Code: Select all

CPU Temperature:

36.856
°C

98.340
°F
Blackberry tarts are sort of like raspberry pies, but they are more purple and sour.

RepublicanSwag
Posts: 21
Joined: Tue Oct 28, 2014 9:15 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Sun Nov 09, 2014 8:46 pm

Any way to set this sensor to check temp every 5 minutes, and shut down if the pi gets too hot?

Could internal temp be displayed on Piglow? (Cool=no lights on, very hot=all lights on bright) :D

User avatar
DougieLawson
Posts: 37644
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: [Tutorial] Show RPI's Temperature with a command.

Sun Nov 09, 2014 9:09 pm

RepublicanSwag wrote:Any way to set this sensor to check temp every 5 minutes, and shut down if the pi gets too hot?

Could internal temp be displayed on Piglow? (Cool=no lights on, very hot=all lights on bright) :D
Yes, but it's 100% pointless. Nobody has ever had an undamaged Pi running at 85°C (the point at which the processor slows until the temp comes down).

Code: Select all

#!/usr/bin/python
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)

while True:
  try:
    tFile = open('/sys/class/thermal/thermal_zone0/temp')
    temp = float(tFile.read())
    tempC = temp/1000
    if tempC > 43.5:
      GPIO.output(17, 1)
      print "HOT"
    else:
      GPIO.output(17, 0)
      print "COLD"

  except:
    tFile.close()
    GPIO.cleanup()
    exit
You could start with that sample and add the stuff for your PiGlow. It's, currently, set to trip at 43.5°C so that the simple act of running that program pushes the temp over the threshold.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

dark_avenger
Posts: 12
Joined: Wed Feb 22, 2012 5:18 am
Contact: Website

Re: [Tutorial] Show RPI's Temperature with a command.

Thu Jun 25, 2015 9:24 am

I know this post is a bit old but it's the first result on google for Raspberry Pi CPU temp so I thought this would be the place to post it.

Below is a python script based off m0rgo's post but injects the data into a mysql database, handy to monitor Pi temp over time or just because you like data :D
Just change the mysql username, password and host to suit.

Code: Select all

#!/bin/python
#script to read a file and extract a number
import time
import MySQLdb
fo = open("sysTemp") # Open a file
str = fo.read(); #read characters in sysTemp and hold them as 'str'
fo.close() #close opened file
print(str) # print string to check
temp1=str[5:9] #chop out required characters
temp2=eval(temp1) #convert string into number

#connect to database
db = MySQLdb.connect(host="host",user="user",passwd="password",db="temps")
curs=db.cursor()

#insert into database
try:
        curs.execute ("INSERT INTO doorbellpi (id, tdate, ttime, temperature) VALUES (NULL, CURRENT_DATE(), NOW(), %s) """, (temp1))
        db.commit()

except db.Error, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        db.rollback()

db.close()
And this is the bash script which runs the python file which I've added to crontab:

Code: Select all

#!/bin/bash
#get system temperarure and save as 'sysTemp'

/opt/vc/bin/vcgencmd measure_temp > sysTemp
# this creates a file called sysTemp in current directory

python tempsys.py
And finally the mysql statement to create the table:

Code: Select all

CREATE TABLE doorbellpi (id MEDIUMINT NOT NULL AUTO_INCREMENT, tdate DATE, ttime TIME, temperature NUMERIC, PRIMARY KEY (id));
Hope this is helpful to somebody :)

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: [Tutorial] Show RPI's Temperature with a command.

Thu Jun 25, 2015 10:57 am

A few things I noticed in your code.

Writing a file just to read it again straight away is nasty. If you've going to do that at least use /dev/shm so you don't wear out the SD card.
AFAIK python doesn't live in /bin on the Pi. I'd adjust the path, chmod +x the file and ditch the launcher script.
str is a function, so over-loading it with a variable is a bad idea.
Your parsing will fail at temperatures at or above 100 and below 10 degrees (though granted, that'll probably be the least of your problems at that point).
eval is a _really_ _bad_ idea. avoid it if you can.

try this:

Code: Select all

#!/usr/bin/python

import subprocess
import MySQLdb

temp_str = subprocess.check_output(('/opt/vc/bin/vcgencmd','measure_temp'))
temp = float(temp_str.split('=')[1].split("'")[0])

# databas stuff here...

dark_avenger
Posts: 12
Joined: Wed Feb 22, 2012 5:18 am
Contact: Website

Re: [Tutorial] Show RPI's Temperature with a command.

Fri Jun 26, 2015 1:24 am

Thanks for that sprinkmeier I'm rather new to Python so the string/number handling code was from earlier in this thread rather than creating my own.
Your code neatens it up a lot :)

Code: Select all

import time
import MySQLdb
import subprocess
#pull cpu temp
temp_str = subprocess.check_output(('/opt/vc/bin/vcgencmd','measure_temp'))
temp = float(temp_str.split('=')[1].split("'")[0])

#connect to database
db = MySQLdb.connect(host="host",user="user",passwd="password",db="temps")
curs=db.cursor()

#insert into database
try:
        curs.execute ("INSERT INTO doorbellpi (id, tdate, ttime, temperature) VALUES (NULL, CURRENT_DATE(), NOW(), %s) """, (temp))
        db.commit()

except db.Error, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        db.rollback()

db.close()

markkulix
Posts: 8
Joined: Mon Jul 06, 2015 6:01 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Wed Aug 05, 2015 7:29 pm

I have my Pi overclocked to 49.2 GHz using Liquid Nitrogen as a cooler!
:lol:

duch
Posts: 1
Joined: Sun Jul 21, 2013 9:24 pm

Re: [Tutorial] Show RPI's Temperature with a command.

Tue Sep 01, 2015 3:26 pm

Thanks for the code ! I just used it and corrected a few mysql related bugs / quirks :

First, the temperature column needs to have a precision and scale specified with its NUMERIC type, or it will default to a 0 scale and truncate after the decimal point. NUMERIC(4,1) is enough even if you get your Pi close to fried ARM temperature as it goes from -999.9 to +999.9

Code: Select all

CREATE TABLE whatever (id MEDIUMINT NOT NULL AUTO_INCREMENT, tdate DATE, ttime TIME, temperature NUMERIC(4,1), PRIMARY KEY (id));
MySQL NOW() function return both the current date and time, so you'll get a warning message telling you that data for this column has been truncated if you use it with a TIME type. You should replace it with CURRENT_TIME() or CURTIME().

Last, my version of MySQLdb (1.2.5) returned an error regarding temp type, it seems to expect a tuple so (temp,) rather than (temp).

Code: Select all

curs.execute ("INSERT INTO whatever (id, tdate, ttime, temperature) VALUES (NULL, CURDATE(), CURTIME(), %s) """, (temp1,))

CodedVision
Posts: 2
Joined: Wed Nov 25, 2015 6:39 am

Re: [Tutorial] Show RPI's Temperature with a command.

Wed Nov 25, 2015 6:49 am

BlackberryTart wrote:I made a shell script that shows Celsius and Fahrenheit. It requires bc. The formatting is sorta ugly, though. Here is the code:

Code: Select all

#!/bin/bash

milcel=$(cat /sys/class/thermal/thermal_zone0/temp)

echo "CPU Temperature:"
echo
echo "scale=3;$milcel/1000" | bc
echo "°C"
echo
echo "scale=3;(($milcel/1000)*(9/5))+32" | bc
echo "°F"

Here is the output:

Code: Select all

CPU Temperature:

36.856
°C

98.340
°F

I modified your script so that the Celsius and Fahrenheit labels are displayed on the same line as the temperature. To do this, the output of bc was stored in a variable. This might be useful for someone looking to store temperature values inside a variable.

Code: Select all

#!/bin/bash

milcel=$(cat /sys/class/thermal/thermal_zone0/temp)

echo "CPU Temperature:"
echo
ctemp=$(echo "scale=3;$milcel/1000" | bc)
echo $ctemp "°C"
echo
ftemp=$(echo "scale=3;(($milcel/1000)*(9/5))+32" | bc)
echo $ftemp "°F"
Example Output:

Code: Select all

CPU Temperature:

48.692 °C

119.645 °F

The_PI_Guy
Posts: 4
Joined: Sun Jan 17, 2016 4:06 am

Re: [Tutorial] Show RPI's Temperature with a command.

Sun Jan 17, 2016 4:13 am

I also use this command quite often to monitor my raspberry pi. But I made the process more efficient. I created a shell script that continually runs the temp command, so I can always know the temp. Simply make a for loop. Simply type Ctrl + c to exit.

Code: Select all

while : do /opt/vc/bin/vcgencmd measure_temp done

Return to “Beginners”