Press "Enter" to skip to content

blink.c: How to let LED0 on Raspberry Pi blink (C Source Code Example)

This tiny example shows how to let LED0 on a Raspberry Pi blink using a program written in C. This is the way how RBridge indicates its operating mode on the RPI platform (usually, this LED shows flash IO activity).

Here’s the source code of “blink.c”:

#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>
#include <unistd.h>

int main(int argc, char** argv) {
  FILE* fp;

  if((fp=fopen("/sys/class/leds/led0/brightness","a+")) == NULL) {
    fprintf(stderr, "cannot open file\n");
    exit(EX_UNAVAILABLE);
  }

  for(;;) {
    fprintf(fp,"1\n");
    fflush(fp);
    usleep(1000000);

    fprintf(fp,"0\n");
    fflush(fp);
    usleep(1000000);
  }
}

Compilation and executing looks as follows (writing to the LED control file requires root permissions):

pi@rpi:~ $ gcc -o blink blink.c
pi@rpi:~ $ sudo ./blink
^C
pi@rpi:~ $