SPI返回我传输的消息

时间:2015-08-20 13:12:46

标签: c linux spi

我已经编写了以下代码来尝试轮询单轴陀螺仪芯片的值:

#include < stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>

#define ARRAY_SIZE(array) sizeof(array)/sizeof(array[0])

static const char *device = "/dev/spidev0.0";
static uint8_t mode;
static uint32_t speed = 1000000;
static uint16_t delay = 1000;
static uint8_t bits = 8;

static void transfer(int fd)
{
   int ret;
   int i;
   uint8_t tx[6] = {0b00001000, 0x00, 0x00, 0x00, 0x00, 0x00};

   uint8_t check = 0x00;
   for (ret = 0; ret < 5; ret++)
      check += tx[ret];
   tx[5] = ~check;

   uint8_t rx[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

   struct spi_ioc_transfer tr = {
    .tx_buf = (unsigned long)tx,
    .rx_buf = (unsigned long)rx,
    .len = 6,
    .delay_usecs = delay,
    .speed_hz = speed,
    .bits_per_word = 8,
   };

   ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
   if (ret < 1)
       printf("can't send spi message\n");

   printf("the received data is: ");
   for (ret = 0; ret < ARRAY_SIZE(rx); ret++) {
      printf("%.2X ", rx[ret]);
   }

   printf("\n");

}

int main(int argc, char *argv[])
{
   int ret = 0;
   int fd;

   fd = open(device, O_RDWR);
   ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);

   if (ret == -1)
      printf("can't set spi mode\n");

   ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);

   if (ret == -1)
      printf("can't get spi mode\n");

   ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);

   if (ret == -1)
      printf("can't set bits per word\n");

    ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
    if (ret == -1)
       printf("can't get bits per word\n");

    ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);

    if (ret == -1)
       printf("can't set max speed hz\n");

    ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
    if (ret == -1)
        printf("can't get max speed hz\n");

    while(1){
       transfer(fd);
       sleep(1);
    }

    close(fd);

    return ret;
}

但是,收到的值与我发送的值相同。这是我第一次使用SPI,我当然可以做出一个简单的错误,但我无法看到它。

如果有必要,here是我正在使用的芯片的数据表。

编辑:

在进行数据传输之前澄清一下:

tx = {0x08, 0x00,0x00,0x00,0x00, 0xF7}
rx = {0x00, 0x00,0x00,0x00,0x00, 0x00}

完成数据传输后:

tx = {0x08, 0x00,0x00,0x00,0x00, 0xF7}
rx = {0x08, 0x00,0x00,0x00,0x00, 0xF7}

转移后我的预期是:

rx = {0x81, 0x00,0x00,0x01,0x00, ~0x82}

0 个答案:

没有答案