How to Use Generic SPI Devices with Zephyr

Originally published at: How to Use Generic SPI Devices with Zephyr - Golioth

If there’s a driver built into Zephyr, controlling a part over Serial Peripheral Interface (SPI) is a snap. But there’s an ocean of parts out there and only so many built-in drivers in existence. Today I’m going to show you how to use generic SPI devices with Zephyr so you can try writing your own test code in userspace, to be used for the long term or in preparation for creating a driver. SPI is simple, right? In practice, communicating with SPI devices is simple…but only after you get the hardware peripheral configured for your chip. Zephyr is built for cross-compatibility, but that is sometimes its biggest usability flaw. The SPI bus and the devices themselves are abstracted so much that it’s hard to know where to begin if you need to do it all yourself. I spent far too long searching the internet for a guide before I remembered that all Zephyr systems have tests. Don’t be me, check the test files before you head to Google. It turns out that the Zephyr SPI driver tests tell us how to register a generic SPI device, and then how to talk to it. Zephyr SPI Step-by-Step For this experiment I have chosen perhaps the easiest SPI chip ever, the Microchip MCP3201 12-bit ADC. No need to send register settings to that device, you simply enable the chip-select pin and toggle the clock signal to start shifting out ADC readings. In short: all I need is to read 4-bytes. That’s it! 1. Enable SPI in KConfig First things first, we need to tell Zephyr to build SPI support into the app. We also need the ability to control GPIO pins. Add…