Program BBB using C (Blink onboard LED)

21 Feb 2015
If you are familiar with linux, you may know that everything in linux is a file. You can talk to a hardware as if you are writing to a file.
There are 4 on board LEDs in BBB. You can play with that LED.

Go to /sys/class/leds/beaglebone:green:usr3/

cd /sys/class/leds/beaglebone:green:usr3/

If you write a '1' to the file corresponding to LED3, then it will light that LED. Writing '0' will switch off the LED.

echo 1 > brightness

It will switch on the LED forever. :-) If you want to switch off it again type

echo 0 > brightness

Let's do it in c.

First ssh into your BBB (refer here). Then create a directory to work with.

mkdir helloworld
cd helloworld


Open your favourite texteditor.

nano LEDBlink.c

Then type this program.


#include<stdio.h>

int main()
{
        FILE *LEDHandler=NULL;
        char *LEDPath="/sys/class/leds/beaglebone:green:usr3/brightness";
        if(LEDHandler=fopen(LEDPath,"r+")){
                fwrite("1", 1, 1,LEDHandler);
                fclose(LEDHandler);
        }
        sleep(3);
        if(LEDHandler=fopen(LEDPath,"r+")){
                fwrite("0", 1, 1,LEDHandler);
                fclose(LEDHandler);
        }

        return 0;
}

Save the program using Cntrl+O and close it using Cntrl+X.
Then compile the program using

gcc LEDBlink.c

Then run your first program.

./a.out

The program will switch on the LED for 3s and then switch off.



Comments