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.
RPi SPI
// 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;
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);
close(fd);
if (ret < 1)
return SPI_XFER_ERROR;
else
return SPI_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment