Friday, 2 January 2015

Blink external LED on Beaglebone Black using C programming


LED connected to GPIO0_23 (P8.13) through 470 ohm resistor.
Do not use lesser value resistors in series with the LED.
GPIO0_23 means 0*32 + 23 = 23. Hence pass this value to the 'export' file.

Connect BBB to computer as explained here.
In terminal/ Putty, type nano Blink_external_LED.cpp
Paste the below code, press Ctrl+X, Y and Enter.
Type g++ Blink_external_LED.cpp -o Blink_external_LED and compile
Type ./Blink_external_LED and run

Code:

#include <unistd.h>
#include <stdio.h>
using namespace std;

int main()
{
        FILE *export_file = NULL;        //declare pointers
        FILE *IO_direction = NULL;
        char str1[] = "low";
        char str2[] = "high";
        char str[] = "23";                       //value to pass to export file
        export_file = fopen ("/sys/class/gpio/export", "w");
        fwrite (str, 1, sizeof(str), export_file);
        fclose (export_file);

for (int i=0; i<10; i++){        //blink LED 10 times
        IO_direction = fopen ("/sys/class/gpio/gpio23/direction", "w");
        fwrite (str2, 1, sizeof(str1), IO_direction);   //set the pin to HIGH
        fclose (IO_direction);
        usleep (1000000);

        IO_direction = fopen ("/sys/class/gpio/gpio23/direction", "w");
        fwrite (str1, 1, sizeof(str1), IO_direction);   //set the pin to LOW
        fclose (IO_direction);
        usleep (1000000);}

        export_file = fopen ("/sys/class/gpio/unexport", "w");   //remove the mapping
        fwrite (str, 1, sizeof(str), export_file);
        fclose (export_file);
}

No comments:

Post a Comment