12

I know you can get the temperature using the tool vcgencmd but I was wondering if there is any API I can use in C to get the temperature programatically without reading the stdout of vcgencmd ?

1

2 Answers 2

13

You can read the file /sys/class/thermal/thermal_zone0/temp, as specified in this answer. There it's about measuring from the command line, and the file is read with cat. But you should be able to just open the file in C. The temperature is returned in milli-degrees Centigrade and as ASCII numbers. Perhaps like this, not tested :)

FILE *temperatureFile;
double T;
temperatureFile = fopen ("/sys/class/thermal/thermal_zone0/temp", "r");
if (temperatureFile == NULL)
  ; //print some message
fscanf (temperatureFile, "%lf", &T);
T /= 1000;
printf ("The temperature is %6.3f C.\n", T);
fclose (temperatureFile);
3
  • Experience has lead me to believe the high level stream interface is not reliable on proc/sys files, and you should use open() and read() instead -- but YMMV. There's also a "libsysfs", but it's been abandoned and the kernel devs have explicitly told people to stay away from it.
    – goldilocks
    Commented Apr 13, 2013 at 11:58
  • @goldilocks Interesting! I did not know this, thought it just behaves like any file. You may very well be right.
    – Frepa
    Commented Apr 13, 2013 at 15:21
  • According to the "official" documentation, vcgencmd measure_temp and the value in /sys/class/thermal/thermal_zone0/temp are different temperatures. The documentation is rather vague on this (as it is on many hardware-related items), but it suggests that vcgencmd provides the GPU temp, and /sys.../temp is the CPU temp. In any event, the values are typically close.
    – Seamus
    Commented May 3, 2020 at 18:28
2

As @Frepa said, there is kernel thermal driver for RaspberryPi now so the easiest way is to use it. As far as I know, that's not the way vgencmd works however. It was able to read the temperature even before thermal kernel driver existed. It is using special communication mechanism available on RaspberryPi called mailbox in order to communicate with VideoCore OS running on GPU. It is partly documented here.

1
  • The Baking Pi course has some more mailbox material, however there it is used only for graphics.
    – Frepa
    Commented Apr 12, 2013 at 15:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.