How to make a library that uses SPI compatible with both Uno and Due

I have written a custom library that uses the Arduino SPI library. It works just fine with the Uno but not with the Due because of the Due's different SPI functions.

I would like to make my library compatible with the Due and its extended SPI usage. However, I am not quit sure how to best accomplish this. I can't figure out how to conditionally use the extended SPI functions when the user compiles for a Due.

The only idea I've come up with so far, which I don't like since this library will be released with a product, is to create a duplicate library for use with the Due, which includes the special functions like SPI.begin(x) and SPI.transfer(x,x, SPI_CONTINUE) rather than the standard SPI library equivalents.

Is there a way to make a library that calls the SPI functions work with both Uno and Due? Maybe by using some other conditional compiling directive like #ifdef's in my library? Or is the standard approach to just not include SPI functions in a library?

Any guidance is appreciated!

You do not need to duplicate the common functionality.

  1. Keep your library declaration in a single header (like you already have).

  2. Create a .cpp for the common functionality (again, probably already there).

  3. Create an avr only .cpp use #ifdef to test for ARDUINO_ARCH_AVR (only include code if using AVR)

  4. Create a sam only .cpp (myLib_SAM.cpp) and test for ARDUINO_ARCH_SAM

Move the functions which use device specific stuff into both the AVR and SAM .cpp files. (As long the cpp files all include the header, you can spread a lib over many files). If you feel you are duplicating too much common stuff, break your code down further into functions that remove the uncommon bits.

On the AVR boards, the HardwareSerial library (Serial) uses this method to add in extra functionality if you are using a board with more than one UART. You can use the #ifdef method in a single .cpp, however a large library with lots on incompatibilities between boards will turn into a huge selectively compiled mess.