Advertisement
DragonEmbers

Untitled

Oct 16th, 2014
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <sys/ioctl.h>
  2. #include <linux/spi/spidev.h>
  3. #include <errno.h>
  4. #include <fcntl.h>    /* For O_RDWR */
  5. #include <unistd.h>   /* For open(), creat() */
  6. #include <cstdio>     /* For printf() */
  7.  
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11.     printf("version: %d\n", 7);
  12.    
  13.     int fd = 0;
  14.     fd = open("/dev/spidev3.0", O_RDWR);
  15.     if (fd < 0)
  16.     {
  17.         printf("SPI : can't open device");
  18.         return -1;
  19.     }
  20.    
  21.     bool ret = ioctl(fd, SPI_IOC_WR_MODE, SPI_MODE_2);
  22.     if (ret == -1)
  23.     {
  24.         printf("SPI : can't set spi mode");
  25.         close(fd);
  26.         return 1;
  27.     }
  28.    
  29.     ret = ioctl(fd, SPI_IOC_WR_LSB_FIRST, SPI_LSB_FIRST);
  30.     if (ret == -1)
  31.     {
  32.         printf("SPI : can't set spi LSB_FIRST mode");
  33.         close(fd);
  34.         return 1;
  35.     }
  36.    
  37.     ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, 7000);
  38.     if (ret == -1)
  39.     {
  40.         printf("SPI : can't set spi MAX_SPEED mode");
  41.         close(fd);
  42.         return 1;
  43.     }
  44.    
  45.     {
  46.         unsigned char spiData[4];
  47.         spiData[0] = 0b00001111; // 0x0F read
  48.         spiData[1] = 0b00000000; // 0x00 msB Address
  49.         spiData[2] = 0b00001000; // 0x08 lsB Address
  50.         spiData[3] = 0b00000000; // 0x00 data byte
  51.  
  52.         for(int j = 0; j < 500; j++)
  53.         {
  54.             for(int i = 0; i < 6; i++)
  55.             {
  56.                 if(spiData[2] == 0xFF)
  57.                 {
  58.                     spiData[2] = 0;
  59.                 }
  60.                 spiData[2] = spiData[2] + 1; // first register read is 0x09
  61.                 spiData[3] = 0b00000000;
  62.                
  63.                 struct spi_ioc_transfer mesg;
  64.  
  65.                 mesg.tx_buf = (unsigned long)spiData;
  66.                 mesg.rx_buf = (unsigned long)spiData;
  67.                 mesg.len = 4;
  68.                 mesg.bits_per_word = 8;
  69.  
  70.                 ret = ioctl(fd, SPI_IOC_MESSAGE(1), mesg);
  71.                 if (ret < 0)
  72.                 {
  73.                     printf("SPI : failed transaction");
  74.                     close(fd);
  75.                     return 1;
  76.                 }
  77.                
  78.                 printf("MAC %d %d: %02X %02X %02X %02X\n", i, j, spiData[0], spiData[1], spiData[2], spiData[3]);
  79.             }
  80.         }
  81.     }
  82.    
  83.     close(fd);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement