3

I am making a graph on the temperature using a NTC resistor and also by reading the CPU temperature, however I'd also like to read the GPU temperature.

I read this answer explaining briefly how to read the CPU temperature from C. How would I read the GPU temperature aswell?

If there isn't any better solution I persume one can use the output of vcgencmd

/opt/vc/bin/vcgencmd measure_temp

but is there not a cleaner way?

Linus
  • 529
  • 1
  • 7
  • 17

2 Answers2

5

/opt/vc/bin/vcgencmd measure_temp

This returns the same thing as reading /sys/class/thermal, i.e., the core temp. Reading the /sys file is preferable programmatically because it is just a sequence of open/read system calls, instead of a fork/execute plus a bunch of open/read/write with pipes.

How would I read the GPU temperature aswell?

The BCM2835/6 used on the Pi/Pi 2 is a SoC, i.e., one chip, with one temperature. The GPU temp == the CPU temp.

goldilocks
  • 58,859
  • 17
  • 112
  • 227
  • Oh that makes sense actually. I guess (this)[ https://bhavyanshu.me/tutorials/keeping-a-check-on-the-cpu-and-gpu-temperature-of-raspberry-pi/03/04/2014/] script only checks the average so that's why I thought they differ. – Linus Oct 24 '15 at 18:23
  • @Linus your link is broken: here it is not broken for future readers. – randers Oct 24 '15 at 20:05
0

Here's a function called get_temp that returns the temperature in Farenheit or Celcius.

Make a file called temp.c and compile it with gcc temp.c -o temp

Here is temp.c:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
double get_temp(bool use_farenheit);
int main(int argc,char *argv[])
{
  // Display the temperature to the user.
  printf("Temperature = %3.3f'C or %3.3f'F\n",get_temp(false),get_temp(true));
  return 0;
}
// Returns the temp in Farenheit or Celcius. Returns -1000 if something went wrong.
double get_temp(bool use_farenheit)
{
  const int BUFFER_SIZE = 100;
  char data[BUFFER_SIZE];
  FILE *finput;
  size_t bytes_read;
  double temp = -1000;
  finput = fopen("/sys/class/thermal/thermal_zone0/temp","r");
  if (finput != NULL) {
    memset(data,0,BUFFER_SIZE);
    fread(data,BUFFER_SIZE,1,finput);
    temp = atoi(data);
    temp /= 1000;
    if (use_farenheit) {
      temp = temp * 9 / 5 + 32;
    }
    fclose(finput);
  }
  return temp;
}
Russell Hankins
  • 201
  • 2
  • 7