Advertisement
Guest User

Untitled

a guest
Aug 29th, 2012
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7.  
  8. #define GPIO_DIR_IN 1
  9. #define GPIO_DIR_OUT 0
  10.  
  11. int gpio_export(unsigned gpio)
  12. {
  13. int fd, len;
  14. char buf[11];
  15.  
  16. fd = open("/sys/class/gpio/export", O_WRONLY);
  17. if (fd < 0) {
  18. perror("gpio/export");
  19. return fd;
  20. }
  21.  
  22. len = snprintf(buf, sizeof(buf), "%d", gpio);
  23. write(fd, buf, len);
  24. close(fd);
  25.  
  26. return 0;
  27. }
  28.  
  29. int gpio_unexport(unsigned gpio)
  30. {
  31. int fd, len;
  32. char buf[11];
  33.  
  34. fd = open("/sys/class/gpio/unexport", O_WRONLY);
  35. if (fd < 0) {
  36. perror("gpio/export");
  37. return fd;
  38. }
  39.  
  40. len = snprintf(buf, sizeof(buf), "%d", gpio);
  41. write(fd, buf, len);
  42. close(fd);
  43. return 0;
  44. }
  45.  
  46. int gpio_dir(unsigned gpio, unsigned dir)
  47. {
  48. int fd, len;
  49. char buf[60];
  50.  
  51. len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/direction", gpio);
  52.  
  53. fd = open(buf, O_WRONLY);
  54. if (fd < 0) {
  55. perror("gpio/direction");
  56. return fd;
  57. }
  58.  
  59. if (dir == GPIO_DIR_OUT)
  60. write(fd, "out", 4);
  61. else
  62. write(fd, "in", 3);
  63.  
  64. close(fd);
  65. return 0;
  66. }
  67.  
  68. int gpio_dir_out(unsigned gpio)
  69. {
  70. return gpio_dir(gpio, GPIO_DIR_OUT);
  71. }
  72.  
  73. int gpio_dir_in(unsigned gpio)
  74. {
  75. return gpio_dir(gpio, GPIO_DIR_IN);
  76. }
  77.  
  78. int set_gpio_value(unsigned gpio, unsigned value)
  79. {
  80. int fd, len;
  81. char buf[60];
  82.  
  83. len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
  84.  
  85. fd = open(buf, O_WRONLY);
  86. if (fd < 0) {
  87. perror("gpio/value");
  88. return fd;
  89. }
  90.  
  91. if (value)
  92. write(fd, "1", 2);
  93. else
  94. write(fd, "0", 2);
  95.  
  96. close(fd);
  97. return 0;
  98. }
  99.  
  100. int get_gpio_value(unsigned gpio)
  101. {
  102. FILE *fp;
  103. int c, d, len;
  104. char buf[60];
  105. len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
  106. //fp = fopen("/sys/class/gpio/gpio54/value", "r");
  107. fp = fopen(buf, "r");
  108. while((c = fgetc(fp)) != EOF){
  109. if (c == '0'){
  110. d = 0;
  111. }
  112. if (c == '1'){
  113. d = 1;
  114. }
  115. }
  116. fclose(fp);
  117. return d;
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement