gpio.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include "gpio.h"
  6. #include "elog.h"
  7. #if 1
  8. #define LOGD log_d
  9. #define LOGE log_e
  10. #else
  11. #define LOGD printf
  12. #define LOGE printf
  13. #endif
  14. int gpio_init(int gpio, int io)
  15. {
  16. int r,fd;
  17. char tmp[20],path[100];
  18. sprintf(path,"/sys/class/gpio/export");
  19. fd = open(path, O_WRONLY);
  20. if(fd< 0){
  21. return -1;
  22. }
  23. sprintf(tmp, "%d", gpio);
  24. write(fd, tmp, strlen(tmp));
  25. close(fd);
  26. sprintf(path,"/sys/class/gpio/gpio%d/direction", gpio);
  27. fd = open(path, O_WRONLY);
  28. if(fd< 0){
  29. LOGE("open %s error\n", path);
  30. return -1;
  31. }
  32. if(io==GPIO_IN) {
  33. sprintf(tmp, "in");
  34. }
  35. else {
  36. sprintf(tmp, "out");
  37. }
  38. r = write(fd, tmp, strlen(tmp));
  39. if(r<0){
  40. LOGE("write gpio direction failed\n");
  41. return -1;
  42. }
  43. close(fd);
  44. sprintf(path,"/sys/class/gpio/gpio%d/value", gpio);
  45. fd = open(path, O_WRONLY);
  46. if(fd< 0){
  47. LOGE("open gpio value failed\n");
  48. return -1;
  49. }
  50. return fd;
  51. }
  52. int gpio_deinit(int fd)
  53. {
  54. close(fd);
  55. return 0;
  56. }
  57. int gpio_set(int fd, int hl)
  58. {
  59. int r;
  60. char tmp[20];
  61. sprintf(tmp, "%d", hl);
  62. r = write(fd, tmp, strlen(tmp));
  63. if(r<0){
  64. LOGE("gpio_set failed\n");
  65. return -1;
  66. }
  67. return 0;
  68. }
  69. int gpio_get(int fd)
  70. {
  71. int r;
  72. char tmp[20];
  73. r = read(fd, tmp, sizeof(tmp)-1);
  74. if (r<0) {
  75. return -1;
  76. }
  77. if (tmp[0]=='0'){
  78. return 1;
  79. } else{
  80. return 0;
  81. }
  82. }