How to read a Raspberry PI temperature in C code

Raspberry PiReading the temperature of a Raspberry PI can be done in a couple of ways. This command:

vcgencmd measure_temp

Outputs something like temp=32.7’C. My 3B+ PI has heatsinks and a cooling fan so runs cool. Even with asteroids it only peaked at 50.5C. Well below the throtle back temperature of 85C.

Another way (I suspect they are the same) is to do

cat /sys/class/thermal/thermal_zone0/temp

Which outputs values like 32705. Just divide by 1000 to get the temperature in Celsius.

But how do we do it in code? Well I’ve tested this code below and it seems to work.

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

int main(void) {
  char buffer[10];
  char * end;
  FILE * temp = fopen("/sys/class/thermal/thermal_zone0/temp","rt");
  int numread = fread(buffer,10,1,temp);
  fclose(temp);
  printf("Temp = %5.2fC\n",strtol(buffer,&end,10)/1000.0);
}

It reads the device as a string then converts to a long using strtol and divides that by 1000 then prints it. Output is something like:

Temp (C) = 34.88C

Now it just needs combined with the code to detect that it’s running on a Pi and you’re good.

Leave a Reply

Your email address will not be published. Required fields are marked *