Advertisement
AntonioVillanueva

MCP23017 PORT EXPANDER ACCESO RASPBERRY PI POR DRIVER

Dec 20th, 2016
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. //i2c bus expander mcp23017 with driver ....raspberryPi
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <string.h>
  5. #define GPIO_ADDR 496 // mcp base address
  6. enum dir{IN,OUT};
  7.  
  8. void gpioExport(int gpio)
  9. {
  10.     int fd;
  11.     char buf[255];
  12.     fd = open("/sys/class/gpio/export", O_WRONLY);
  13.     sprintf(buf, "%d", gpio);
  14.     write(fd, buf, strlen(buf));
  15.     close(fd);
  16. }
  17.  
  18. void gpioDirection(int gpio, int direction) // 1 for output, 0 for input
  19. {
  20.     int fd;
  21.     char buf[255];
  22.         sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio);
  23.         fd = open(buf, O_WRONLY);
  24.  
  25.         if (direction){
  26.         printf ("gpio %d out\n",gpio);
  27.             write(fd, "out", 3);
  28.         }else{
  29.         printf ("gpio %d in\n",gpio);
  30.         write(fd, "in", 2);
  31.     }
  32.         close(fd);
  33. }
  34.  
  35. void gpioSet(int gpio, int value)
  36. {
  37.     int fd;
  38.     char buf[255];
  39.         sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  40.         fd = open(buf, O_WRONLY);
  41.         sprintf(buf, "%d", value);
  42.         write(fd, buf, 1);
  43.         close(fd);
  44. }
  45.  
  46. int main (){
  47.     int offset=0;
  48.     do{
  49.         gpioExport(GPIO_ADDR+offset);
  50.         gpioDirection ( GPIO_ADDR+offset ,offset <8 ?IN:OUT);
  51.     }while (GPIO_ADDR+(offset++) <(GPIO_ADDR+15));
  52.  
  53.     //gpioExport(506);
  54.     //gpioDirection(506,OUT);
  55.     //gpioSet(506,1);
  56.  
  57.     do {//Set OUTs PORTB MCP23017
  58.         gpioSet(GPIO_ADDR+offset,0);
  59.  
  60.     }while ((GPIO_ADDR+ (offset--)) >=GPIO_ADDR);
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement