Skip to content

Instantly share code, notes, and snippets.

@ochaochaocha3
Created December 25, 2014 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochaochaocha3/ad185721b3717b98cf6f to your computer and use it in GitHub Desktop.
Save ochaochaocha3/ad185721b3717b98cf6f to your computer and use it in GitHub Desktop.
Raspberry Pi 電子工作:CPU 温度を LED に表示する
/*
* LED で CPU 温度を表示する
*
* LED 5 個で表示できるように、基準温度を設定する
* 表示範囲は基準温度 + 0〜31 ℃
*
* [例]
* # 40 ℃ を基準温度として表示する
* $ sudo ./led-cputemp 40
*/
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <signal.h>
typedef void (*sighandler_t)(int);
// LED で CPU 温度を表示する
void led_show_cpu_temp(int ref_temp);
// シグナルを捕捉する
sighandler_t trap_signal(int sig, sighandler_t handler);
// 終了処理:LED 消灯
void terminate(int sig);
#define N_LEDS 5
int main(int argc, char* argv[]) {
int ref_temp = 30;
int interval = 500;
int i;
wiringPiSetup();
for (i = 0; i < N_LEDS; i++) {
pinMode(i, OUTPUT);
}
trap_signal(SIGINT, terminate);
trap_signal(SIGTERM, terminate);
if (argc > 3) {
fprintf(
stderr, "Usage: %s [REF_TEMP] [INTERVAL_MSEC]\n", argv[0]
);
exit(1);
}
// 基準温度を設定する
if (argc > 1) {
ref_temp = (int)strtol(argv[1], NULL, 10);
if (ref_temp < 0 || ref_temp > 80) {
fprintf(stderr, "Reference temperature must be between 0 and 80\n");
exit(1);
}
}
// 更新間隔を設定する
if (argc == 3) {
interval = (int)strtol(argv[2], NULL, 10);
if (interval < 1 || interval > 9999) {
fprintf(stderr, "Interval must be between 1 and 9999\n");
exit(1);
}
}
while (1) {
led_show_cpu_temp(ref_temp);
delay(interval);
}
return 0;
}
void led_show_cpu_temp(int ref_temp) {
char buf[16];
long n;
int i;
FILE* fd;
fd = fopen("/sys/devices/virtual/thermal/thermal_zone0/temp", "r");
if (!fd) {
goto clear_lcd;
}
if (!fgets(buf, 16, fd)) {
goto clear_lcd;
}
fclose(fd);
n = (int)strtol(buf, NULL, 10) / 1000 - ref_temp;
if (n < 0 || n > 31) {
goto clear_lcd;
}
for (i = 0; i < N_LEDS; i++) {
digitalWrite(i, n & (1 << i));
}
return;
clear_lcd:
for (i = 0; i < N_LEDS; i++) {
digitalWrite(i, 0);
}
}
sighandler_t trap_signal(int sig, sighandler_t handler) {
struct sigaction act = {
.sa_handler = handler,
.sa_flags = SA_RESTART
};
struct sigaction old;
sigemptyset(&act.sa_mask);
if (sigaction(sig, &act, &old) < 0) {
perror("trap_signal");
exit(1);
}
return old.sa_handler;
}
void terminate(int sig) {
int i;
for (i = 0; i < N_LEDS; i++) {
digitalWrite(i, LOW);
}
exit(0);
}
CC=gcc
CFLAGS=-Wall
LIBS=-lwiringPi
TARGETS=led-cputemp
led-cputemp: led-cputemp.c
$(CC) $(CFLAGS) -o $@ $< $(LIBS)
all: $(TARGETS)
clean:
rm -f *.o
.PHONY: all clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment