I’m trying to command a stepper motor controller through SPI, and I found that I could not send commands as quickly as I was expecting. After some profiling, I narrowed it down to this call:
clock_gettime(CLOCK_MONOTONIC, &ts0); // Check time before
ioctl(fd, SPI_IOC_MESSAGE(1), xfer); // spi_ioc_transfer structure
clock_gettime(CLOCK_MONOTONIC, &ts1); // Check time after
The message I’m trying to send is 6 bytes, and the SPI clock rate is 5MHz. So this should take about 10 microseconds plus a little system call overhead.
Instead, I’m finding that this call usually takes a 8 to 22 milliseconds, usually on the higher end.
For reference, here’s how I do initialization:
static int configure_spi(int fd)
{
char mode = SPI_MODE_3;
char bits = 8;
int speed = 5000000;
char lsbfirst = 0;
check_ioctl(fd, SPI_IOC_WR_MODE, &mode);
check_ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
check_ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
check_ioctl(fd, SPI_IOC_WR_LSB_FIRST, &lsbfirst);
return 0;
}
And here’s the setup for a transaction:
struct spi_ioc_transfer xfer[1];
memset(xfer, 0, sizeof(xfer));
xfer[0].tx_buf = (unsigned long) tbuf;
xfer[0].rx_buf = (unsigned long) rbuf;
xfer[0].len = len;
xfer[0].speed_hz = 5000000;
xfer[0].bits_per_word = 8;
ioctl(fd, SPI_IOC_MESSAGE(1), xfer);
Can anyone tell me how I might go about figuring out what’s wrong and how to fix it? Take 22 milliseconds for a single SPI transaction is completely intolerable for my application, so I have to fix this.
Thanks!