Advertisement
AntonioVillanueva

mcp23017 i2c a la C...... TEST

Nov 29th, 2017
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>     /* exit, EXIT_FAILURE */
  3. #include <fcntl.h>
  4. #include <linux/i2c-dev.h>
  5. #include <errno.h>
  6.  
  7. #include <sys/ioctl.h>
  8. #include <unistd.h>
  9.  
  10. #define I2C_ADDR 0x20
  11. #define DEV_I2C "/dev/i2c-0"
  12. /*--------------------------------------------------------------------*/
  13. int I2COpen(){//Return fd
  14.     int fd;
  15.  
  16.     fd = open(DEV_I2C, O_RDWR);
  17.  
  18.     if (fd < 0) {
  19.         printf("Error opening file: \n");
  20.         return -1; 
  21.     }
  22.  
  23.     if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < 0) {
  24.         printf("ioctl error: \n");
  25.         return -1;
  26.     }
  27.     return fd;
  28. };
  29.  
  30. /*--------------------------------------------------------------------*/
  31. void I2CSetup (int fd) {//Setup mcp23017
  32.     char buffer[2];
  33.    
  34.     buffer[1]=0x00;//Valeur register
  35.    
  36.     //Clear ports mcp23017 GPIOB OUTPUT
  37.     for( size_t reg=0x01 ;reg<0x10;reg++){
  38.         buffer[0]=reg;//load register
  39.         write(fd,buffer,2);
  40.         usleep(1000);
  41.     }
  42.    
  43.     //GPIOA INPUT
  44.     buffer[0]=0x00;//Register IODIRA
  45.     buffer[1]=0xFF;// Value INPUT
  46.     write(fd,buffer,2);
  47.    
  48. };
  49.  
  50. /*--------------------------------------------------------------------*/
  51. int iI2CRead (int fd) {//Read  GPIOA
  52.     char buffer[2];
  53.     buffer[0]=0x12;//GPIOA
  54.     write(fd,buffer,1);
  55.    
  56.     read(fd, &buffer[1], 1);
  57.     return buffer[1];
  58. };
  59.  
  60. /*--------------------------------------------------------------------*/
  61. void iI2CWrite (int fd, unsigned char data){//write GPB
  62.     char buffer[2];
  63.     buffer[0]=0x13;//GPIOB
  64.     buffer[1]=data;
  65.     write(fd,buffer,2);
  66. };
  67.  
  68. /*--------------------------------------------------------------------*/
  69. /*--------------------------------------------------------------------*/
  70. int main (void) {
  71.     char buffer[2];
  72.  
  73.     int fd(-1);
  74.  
  75.     if ( (fd=I2COpen()) <0){exit (0);}
  76.     I2CSetup (fd);//SetUp mcp23017
  77.  
  78.     //Read GPIOA
  79.     printf("0x%02X\n",iI2CRead (fd));
  80.        
  81.     usleep(100000);
  82.    
  83.     //Write GPIOB
  84.     buffer[1]=0xAA;//Write data
  85.     iI2CWrite (fd, buffer[1]);//write GPB
  86.        
  87.    
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement