Advertisement
smithwinston

i2cscan.c

Apr 30th, 2014
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. /*
  2.  * i2cscan  FreeBSD version of i2cdetect
  3.  *          Compile with:
  4.  *              cc i2cscan.c -o i2cscan
  5.  *
  6.  * Winston Smith <smith.winston.101@gmail.com>
  7.  */
  8.  
  9. #include <sys/cdefs.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <fcntl.h>
  13. #include <sys/ioctl.h>
  14. #include <errno.h>
  15. #include <unistd.h>
  16. #include <dev/iicbus/iic.h>
  17.  
  18.  
  19. /*
  20.  * Scan for the specified slave by trying to read a byte
  21.  */
  22. int scan(int fd, int slave)
  23. {
  24.     uint8_t              buf[2] = { 0, 0 };
  25.     uint16_t             offset = 0;
  26.     struct iic_msg       msg[2];
  27.     struct iic_rdwr_data rdwr;
  28.  
  29.  
  30.     msg[0].slave = slave;
  31.     msg[0].flags = !IIC_M_RD;
  32.     msg[0].len = sizeof(offset);
  33.     msg[0].buf = (uint8_t*)&offset;
  34.  
  35.     msg[1].slave = slave;
  36.     msg[1].flags = IIC_M_RD;
  37.     msg[1].len = sizeof(buf);
  38.     msg[1].buf = buf;
  39.  
  40.    
  41.     rdwr.nmsgs = 2;
  42.     rdwr.msgs = msg;
  43.  
  44.     if (ioctl(fd, I2CRDWR, &rdwr) < 0) {
  45.         switch (errno) {
  46.         case ENXIO:
  47.             // Doesn't exist
  48.             return 1;
  49.         case EBUSY:
  50.             // Currently in use
  51.             return 2;
  52.         default:
  53.             perror("ioctl(I2CRDWR) failed");
  54.             return -1;
  55.         }
  56.     }
  57.  
  58.     return 0;
  59. }
  60.  
  61. int main(int argc, char **argv)
  62. {
  63.     int c, r, fd;
  64.     char* dev = "/dev/iic0";
  65.  
  66.     if (argc > 1) {
  67.         dev = argv[1];
  68.     }
  69.  
  70.     if ((fd = open(dev, O_RDWR)) < 0 )  {
  71.         perror("open failed");
  72.         exit(-1);
  73.     }
  74.  
  75.     printf("Checking device: %s\n", dev);
  76.     printf("     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f\n");
  77.  
  78.     for (r = 0; r < 8; r++) {
  79.         printf("%02X:", r*16);
  80.         for (c = 0; c < 16; c++) {
  81.  
  82.             int addr = (r * 16) + c;
  83.  
  84.             switch (scan(fd, addr)) {
  85.             case 0:
  86.                 printf(" %02X", addr);
  87.                 break;
  88.             case 1:
  89.                 printf(" --");
  90.                 break;
  91.             case 2:
  92.                 printf(" UU");
  93.                 break;
  94.             default:
  95.                 break;
  96.             }
  97.         }
  98.         printf("\n");
  99.     }
  100.  
  101.     close(fd);
  102.     exit(0);
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement