Best practices when using SPI and timer interrupts in a library

Hi,

Question 1 - I'm writing a library that uses SPI. Is it appropriate to call SPI.begin() in my own begin() method, or should I leave that for the sketch writer? In particular, I'm wondering what will happen if a sketch uses multiple SPI devices (e.g. Ethernet, SD card, my own gizmo) and SPI.begin() ends up being called more than once.

Question 2 - My library also uses timer interrupts. I've no problem configuring the timer and handing interrupts, but should I call sei() (or rather, interrupts()) in my begin() method? It seems rather bad practice for my library to turn on interrupts when other libraries may not be initialized yet, but OTOH my library won't work unless somebody eventually turns on interrupts. Should I leave that to the sketch programmer, or do it for him?

What's the usual practice in these cases when writing libraries?

Thanks!

  1. Let the user sketch determine which SPI bus (if processor has several) and pass a SPIClass pointer or reference to it into either your constructor or begin() function. No need for the user sketch to call .begin() for that SPIClass object. You should do so from YOUR begin function.

  2. Interrupts are enabled by default. Don't do anything unless your code disables them. Then you should re-enable them ASAFP.

gfvalvo:
2. Interrupts are enabled by default.

How about that? Didn't know that - thanks!

gfvalvo:
... pass a SPIClass ... reference ...

Didn't know the Arduino supported multiple SPI instances either, but I guess that makes sense for devices like the ESP8266 that have more than one.

Speaking of which, is there a processor/platform independent way to get timer interrupts at roughly a 5kHz rate? My current implementation works fine, but is specific to the AVR timers...

Thanks again

SpareTimeGizmos:
Didn't know the Arduino supported multiple SPI instances either, but I guess that makes sense for devices like the ESP8266 that have more than one.

Teensy 3.5 and 3.6 Boards have 3.

Speaking of which, is there a processor/platform independent way to get timer interrupts at roughly a 5kHz rate?

There are probably libraries available that mask the platform dependence making the user think they're not. But, you're dealing with low-level, hardware-specific features. So, of course there's going to be platform dependence. At least between different platform families.