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 ?
You might find this useful: mjmwired.net/kernel/Documentation/sysfs-rules.txt– goldilocks ♦Apr 13, 2013 at 11:59
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);
Experience has lead me to believe the high level stream interface is not reliable on proc/sys files, and you should use
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 ♦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.– FrepaApr 13, 2013 at 15:21
According to the "official" documentation,
vcgencmd measure_tempand the value in
/sys/class/thermal/thermal_zone0/tempare different temperatures. The documentation is rather vague on this (as it is on many hardware-related items), but it suggests that
CPUtemp. In any event, the values are typically close.– SeamusMay 3, 2020 at 18:28
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.
The Baking Pi course has some more mailbox material, however there it is used only for graphics.– FrepaApr 12, 2013 at 15:49