libsoc icon indicating copy to clipboard operation
libsoc copied to clipboard

add support for SPI bit ordering

Open cyboflash opened this issue 8 years ago • 3 comments

Based on the source code there doesn't seem to be support for bit ordering for SPI, i.e. MSB / LSB first.

cyboflash avatar May 04 '17 21:05 cyboflash

Hi, how is this manipulated from the user space kernel interface. Do you have an example?

jackmitch avatar May 18 '17 11:05 jackmitch

At this point I don't know. I had a device where I could do it, so I assumed it is possible to do it in the library. However based on this it seems it depends on the device rather than on the library.

cyboflash avatar May 18 '17 18:05 cyboflash

Here is a very simplistic example on how to do this:

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

#define SPIDEV "/dev/spidev0.1"

int querySpiLsb(int fd, uint8_t *spiLsb){
	if(ioctl(fd, SPI_IOC_RD_LSB_FIRST, spiLsb)){
		fprintf(stderr, "Couldn't query SPI MSB-/LSB-setting!\n");
		return -1;
	}

	printf("The SPI-bus is currently set to use ");
	if(!*spiLsb){
		printf("MSB-ordering.\n");
		*spiLsb = SPI_LSB_FIRST;
	}
	else {
		printf("LSB-ordering.\n");
		*spiLsb = 0;
	}
	return 0;
}

int main(int argc, char *argv[])
{
	int fdSpidev;
	uint8_t spiLsb = 0;

	fdSpidev = open(SPIDEV, O_RDWR);
	if(fdSpidev < 0){
		fprintf(stderr, "Couldn't open SPIDEV %s!\n", SPIDEV);
		exit(1);
	}
	if(querySpiLsb(fdSpidev, &spiLsb)){
		close(fdSpidev);
		exit(1);
	}

	printf("Trying to set the SPI-bus to use ");
	if(!spiLsb) printf("MSB-ordering.\n");
	else printf("LSB-ordering.\n");

	if(ioctl(fdSpidev, SPI_IOC_WR_LSB_FIRST, &spiLsb)){
		fprintf(stderr, "Error performing SPI_IOC_WR_LSB_FIRST ioctl() (hardware doesn't support this?)!\n");
		close(fdSpidev);
		exit(1);
	}

	if(querySpiLsb(fdSpidev, &spiLsb)){
		close(fdSpidev);
		exit(1);
	}
}

The Raspberry Pi, for example, does not seem to support changing bit-ordering and the ioctl()-call fails, but on the Orange Pi Plus 2E, on the other hand, this works fine.

WereCatf avatar Aug 12 '17 15:08 WereCatf