Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple script to control the temperature of our raspberry pi. This script save the temperature in a log file and if it's greater than 70 ºC, our raspberry will be shutdown for security
#!/bin/bash
cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp)
cpuTemp1=$(($cpuTemp0/1000))
cpuTemp2=$(($cpuTemp0/100))
cpuTempM=$(($cpuTemp2 % $cpuTemp1))
gpuTemp=$(/opt/vc/bin/vcgencmd measure_temp)
# Function to write the temperature into the log
function writeToLog() {
# The direction of the file
# you can put here another route
file="/home/pi/temp.log"
# Check if the file exists
if [ ! -f "$file" ] ; then
# if not create the file
touch "$file"
fi
echo "$1" >> "$file"
}
# Save the value
writeToLog "$(date): CPU temp - $cpuTemp1.$cpuTempM'C, GPU temp - $gpuTemp;"
# Check the temperature
if [ "$cpuTemp1" -gt "70" ]
then writeToLog "Shutdown.......;"; `shutdown -h now`
fi

INSTALL

The installation is very easy. First, you need to download the file below: checkTemp.sh. To complet this task, open a terminal an execute this command:

wget https://gist.github.com/Angelmmiguel/e13fed981e91bf6a298c/raw/0c33849753f17bd3b70d3aa2a4cfc06e05abafb3/checktemp.sh

The second step is to copy this file to the Crontab folder (Crontab is an application to schedule scripts in Unix systems):

sudo cp checktemp.sh /etc/cron.d/

The last step is to initialize the crontab task. You must open the crontab file to save the task with this command:

sudo crontab -e

We need to use sudo because the command shutdown needs root privileges. When the file is open, go to the bottom and, after the comments (# lines), and write this line:

*/5 * * * * /etc/cron.d/checktemp.sh

This task will execute checkTemp every 5 minutes. More info about schedule time options in this nice post :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.