Where to initialize SPI chip select pin in library

I see libraries that initialize the SPI CS (and other pins) in various places. Some do nothing, some just save the pin numbers to local variables in the constructor, others also set the pinMode there, while others also set the value via digitalWrite. What is the best practice? It seems to me setting the pins up completely in the constructor makes the most sense, especially if one is using several peripherals that use SPI. If the CS pin is set up in a Begin or Init function, then when the SPI is accessed to set up the first device then other devices may also be accessed if their not-yet-initialized CS pin floats low, which can cause unintended behavior. This can be fixed in hardware with pullups on CS, but it seems doing it in software is better. Is there a good reason not to set the pins up completely in the constructor? Is there documentation that shows best practice?

It does make sense to set the pin number via the constructor. However, you should never touch the hardware in the constructor because it might not have been properly configured at the time the constructor runs. This can result in some very confusing bugs that only affect specific boards.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.