Linux - Accessing SPI Bus from User Space - Part I

There needs to be a way to communicate with your hardware to write a complex device driver. In this post we will see how we can use the SPI Bus to communicate with the device from the user space.

You`ll need to configure your kernel to enable the SPI communication from userspace.

Let's first see the basic Kernel Configs needed to enable SPI support.
CONFIG_SPI
CONFIG_SPI_MASTER
CONFIG_SPI_SPIDEV

The CONFIG_SPI_SPIDEV enables the Userspace SPI framework for us.

Most Processors comes with a built in SPI Bus Module for greater performance and ease of use. If your platform happens to have one with a matching linux device driver. Enable the appropriate config.

E.g) For OMAP24xx or OMAP34xx Platforms you`ll need to enable CONFIG_SPI_OMAP24XX to use the inbuilt McSPI module of the processor.

You will now need to configure your board file to export the SPI bus to Userspace.

Add this piece of code in your board*.c file.

/* Structure for configuing McSPI */
static struct spi_board_info board_spi3_board_info[] = {
{
.modalias = "spidev", /* Expose spi to userspace */
.max_speed_hz = 500000, /* SPI Speed. */
.bus_num = 3, /* McSPI Bus Number */
.chip_select = 0, /* ChipSelect for McSPI */
.mode = 0, /* SPI Mode */
},
};

and add register the SPI bus in the board_init function in the board*.c file.
/*Register SPI device*/
spi_register_board_info(board_spi3_board_info, ARRAY_SIZE(board_spi3_board_info));

Now, when you boot up your system. You should see your spi device in the filesystem at /dev path.
e.g) /dev/spidev2.0 ( 2 - SPI bus number, 0 - Chip Select)

We can use the standard open,read,write and close api's along with /dev/spidevx.y device to send and receive SPI messages to the device.

In the next post we`ll see how to use the /dev/spidevx.y to send and receive messages.

2 Responses to "Linux - Accessing SPI Bus from User Space - Part I"

Jim St responded on December 23, 2010 at 2:55 PM #

I have tried to add in your example code to a simple driver and get an error right out of the gate.

WARNING: "spi_register_board_info" [/home/jws/spimod3/spimod3.ko] undefined!

I have looked at the definition of CONFIG_SPI and the include/spi/spi.h header where the spi_register_board_info is defined, and everything seems to be in order. I am getting this after the compile. from the module build script. Any ideas what is going on?

Unknown responded on January 4, 2014 at 1:07 PM #

I'm also trying to "create" an SPI device using GPIO bitbanging for beagleboard-xM and got the same "error".

I think this is somewhat related to spi_register_board_info not being exported (through EXPORT_SYMBOL or EXPORT_SYMBOL_GPL).

Don't know if it should be exported or not.