Skip to content

Instantly share code, notes, and snippets.

@mentha
Created January 27, 2018 13:15
Show Gist options
  • Save mentha/feeaa25a7de370e79047479c43124536 to your computer and use it in GitHub Desktop.
Save mentha/feeaa25a7de370e79047479c43124536 to your computer and use it in GitHub Desktop.
RPI status led showing system load
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/sysinfo.h>
#define LEDCTL "/sys/class/leds/led0/brightness"
float getload()
{
static int ncpus = -1;
if (ncpus < 0)
ncpus = get_nprocs_conf();
FILE *f = fopen("/proc/loadavg", "r");
if (f == NULL)
return -1;
float r;
fscanf(f, "%f", &r);
fclose(f);
return r / ncpus;
}
void ledctl(int ctl) {
FILE *f = fopen(LEDCTL, "w");
if (f == NULL)
return;
fputs(ctl ? "1" : "0", f);
fclose(f);
}
void ledtoggle() {
static int stat = 0;
ledctl((stat = !stat));
}
void cleanup(int sig) {
ledctl(0);
exit(0);
}
int main() {
signal(SIGINT, cleanup);
signal(SIGTERM, cleanup);
for (;;) {
ledtoggle();
float w = 1 - getload();
usleep(100000);
usleep(w * 1000000);
};
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment