Advertisement
silver2row

learning from #beagle IRC

Mar 25th, 2022
1,283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. /*
  2.  
  3. Example of programming GPIO from C using the sysfs interface on
  4. a BeagleBone Black with RelayCape.
  5.  
  6. Will toggle physical pin 3.16 or P9.30 or gpio108 (which is gpio3_16 and it is 32 * 3 + 12 = 108) on the
  7. RelayCape attached to the BBBW for a change in seconds and then exits on CTRL-C.
  8.  
  9. The original source can be found here by Mr. Tranter: https://github.com/tranter/blogs/blob/master/gpio/part5/demo1.c
  10.  
  11. Jeff Tranter <jtranter@ics.com>
  12.  
  13. and...Seth. I changed the source a bit to fit the BBBW and RelayCape! SysFS!
  14.  
  15. */
  16.  
  17. #include <errno.h>
  18. #include <fcntl.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <unistd.h>
  22.  
  23. int main()
  24. {
  25.  
  26.     // Export the desired pin by writing to /sys/class/gpio/export
  27.  
  28.     int fd = open("/dev/gpio/relay-jp3/value", O_WRONLY);
  29.     if (fd == -1) {
  30.         perror("Unable to open /dev/gpio/relay-jp3/value");
  31.         exit(1);
  32.     }
  33.  
  34.     // Toggle LED 50 ms on, 50ms off, 100 times (10 seconds)
  35.  
  36.     for (int i = 0; i < 100; i++) {
  37.         if (write(fd, "1", 1) != 1) {
  38.             perror("Error writing to /dev/gpio/relay-jp3/value");
  39.             exit(1);
  40.         }
  41.         usleep(50000);
  42.  
  43.         if (write(fd, "0", 1) != 1) {
  44.             perror("Error writing to /dev/gpio/relay-jp3/value");
  45.             exit(1);
  46.         }
  47.         usleep(500000);
  48.     }
  49.  
  50.     close(fd);
  51.  
  52.     // And exit
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement