Saturday, October 26, 2013

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);
}

5 comments:

  1. Hi aswin,

    Thanks for the above code. I tried it and worked fine. I would also like to get help for the code in php to control the external led via webpage.

    Thanks in advance.

    ReplyDelete
  2. Thanks a lot for your code
    How to compile this code for BBB

    ReplyDelete
  3. The code is a bit misleading, the fix should include separating the direction (as an output) before the for loop and then set the value to high and low. I know the code works but it is not technically correct. Thanks for sharing the code though.

    ReplyDelete
  4. scope error are occured for file cmt

    ReplyDelete