SPI on the Raspberry Pi

Over the last few days I have been writing a driver for the Raspberry Pi’s SPI peripheral. This driver will let you use the SPI pins on the GPIO header properly rather than relying on bit-banging. Someone already wrote a driver but it was incomplete and I didn’t much care for the code, so I decided to roll my own.

One of the primary advantages of my code at the moment is that the clock speed on the SPI port can be set properly, rather than being hard-coded to an invalid value. The SPI clock speed is determined by dividing the SPI peripherals reference clock (250 MHz) by a power-of-2 divider between 2 and 65536. This gives you a number of speeds from 3.8 KHz to (theoretically) 125 MHz. Given a clock rate in Hz, my driver will pick the fastest speed possible less than or equal to the given speed, so if you request 500 KHz, you get 488 KHz instead (250 MHz ÷ 512).

You can find all the necessary patches in the rpi-spi branch on my GitHub.

Please note: If you want to use this code you’ll need to download switchPinCtrl from the person who wrote the other SPI driver to put the SPI pins into the right mode. If you don’t do this, the pins will remain set up as GPIOs and you will not get anything from the SPI driver on those pins. This will be fixed when I get round to writing a pin control driver so that this can be managed from within the kernel. This is on the TODO list.

Also on the TODO list for this driver is interrupt-driven mode which should greatly reduce the CPU load.

5 thoughts on “SPI on the Raspberry Pi

  1. Very nice. I don’t have my pi yet, but I will give it a rip when I do. I didn’t know you could achieve 125MHz on the pi. Is this just a single pin or multiples?

    • Well 125 MHz is the minimum clock divider. I don’t really think you have any chance of getting signals in and out of the Pi at that rate though! As I mentioned I couldn’t get anywhere above 7.8 MHz with my jumper leads; maybe you can do better with a proper PCB attached to the GPIO expansion port but I very much doubt 125 MHz.

  2. Hi you mentioned working on pinctrl — I’ve not going to finish it in the next couple of weeks, so feel free to have a go. It should compile up as a starting point, and then need finishing and populating and tie in with the drivers.

    I’m not on github as such, so you can grab it here.


  3. Ok, great — didn’t realise someone had already started. Probably doesn’t add anything if he’s got something going already — it was part of our early testing.

Comments are closed.