How to Monitor Temperature on Raspberry Pi

2019-08-06 | 262 words

You don’t want your Raspberry Pi to catch fire, do you?

In this article, we will create a simple bash script that we will run with cron and when the temperature of the Raspberry Pi exceeds a certain threshold, it will send us an email. It’s more for fun than for any real use :)

Sending Emails

First, we will install ssmtp so that we can send emails:

sudo apt-get install ssmtp sudo apt-get install mailutils

We will modify the configuration. For example, I use UPC internet, so I just need to enter their public, freely available SMTP server. Plus hostname, from which emails will be sent. Then you will whitelist this domain in your email so that emails from Pi don’t fall into spam.

sudo nano /etc/ssmtp/ssmtp.conf

mailhub=smtp.dkm.cz hostname=your-domain.cz

Script for Measuring CPU Temperature

We will create a file called temperature.sh and its contents will be as follows. It is a carefully crafted piece of script that I put together by trial and error. Bash is not my strong suit.

#!/bin/bash

val=$(vcgencmd measure_temp | egrep -o ‘[0-9]*’ | head -1 | bc -l) max=60

if [ “$val” -gt “$max” ]; then echo “$val” | mail -s “RPI - Temperature” your@email.com fi

We will give it permission to run:

chmod +x temperature.sh

And we can test it (I recommend lowering the temperature to 30 for testing):

sh temperature.sh

Regular Check with Cron

We will run it with cron every 5 minutes. We will start editing cron with this command:

crontab -e

*/5 * * * * sh /home/pi/temperature.sh

And that’s it :)