Skip to content

Instantly share code, notes, and snippets.

@JSchaenzle
Last active August 29, 2015 14:01
Show Gist options
  • Save JSchaenzle/bf433e7e8e4393959d28 to your computer and use it in GitHub Desktop.
Save JSchaenzle/bf433e7e8e4393959d28 to your computer and use it in GitHub Desktop.

Revisions

  1. JSchaenzle revised this gist May 23, 2014. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions rpi_spi.c
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,10 @@
    // Mode options: SPI_LOOP, SPI_CPHA, SPI_CPOL, SPI_LSB_FIRST,
    // SPI_CS_HIGH, SPI_3WIRE, SPI_NO_CS, SPI_READY
    static uint8_t mode = SPI_CPHA;
    static uint8_t bits = 8;
    static uint32_t speed = 3000000;
    static uint16_t delay = 0;

    SPI_RESULT_T SPI_DoTransfer(char * device, uint8_t * p_rx_buf, uint8_t * p_tx_buf, uint32_t len)
    {
    int fd;
  2. JSchaenzle revised this gist May 23, 2014. 1 changed file with 3 additions and 6 deletions.
    9 changes: 3 additions & 6 deletions rpi_spi.c
    Original file line number Diff line number Diff line change
    @@ -39,13 +39,10 @@
    };

    ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
    close(fd);

    if (ret < 1)
    {
    return SPI_XFER_ERROR;
    }
    else
    {
    }
    close(fd);
    return SPI_SUCCESS;
    return SPI_SUCCESS;
    }
  3. JSchaenzle created this gist May 23, 2014.
    51 changes: 51 additions & 0 deletions rpi_spi.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    SPI_RESULT_T SPI_DoTransfer(char * device, uint8_t * p_rx_buf, uint8_t * p_tx_buf, uint32_t len)
    {
    int fd;
    int ret;

    // Open the device
    fd = open(device, O_RDWR);
    if (fd < 0) return SPI_ERR_OPENING_DEVICE;

    // Set SPI mode
    ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
    if (ret == -1) return SPI_ERR_CFGING_PERIPH;

    ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
    if (ret == -1) return SPI_ERR_CFGING_PERIPH;

    // Set the Bits per Word
    ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
    if (ret == -1) return SPI_ERR_CFGING_PERIPH;

    ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
    if (ret == -1) return SPI_ERR_CFGING_PERIPH;

    // Set the max speed
    ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
    if (ret == -1) return SPI_ERR_CFGING_PERIPH;

    ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
    if (ret == -1) return SPI_ERR_CFGING_PERIPH;

    struct spi_ioc_transfer tr =
    {
    .tx_buf = (unsigned long)p_tx_buf,
    .rx_buf = (unsigned long)p_rx_buf,
    .len = len,
    .delay_usecs = delay,
    .speed_hz = speed,
    .bits_per_word = bits,
    };

    ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
    if (ret < 1)
    {
    return SPI_XFER_ERROR;
    }
    else
    {
    }
    close(fd);
    return SPI_SUCCESS;
    }