UserSPIDriver.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // An example of an external SPI driver.
  2. //
  3. #include "SPI.h" // Only required if you use features in the SPI library.
  4. #include "SdFat.h"
  5. #if SPI_DRIVER_SELECT == 3 // Must be set in SdFat/SdFatConfig.h
  6. // SD chip select pin.
  7. #define SD_CS_PIN SS
  8. // This is a simple driver based on the the standard SPI.h library.
  9. // You can write a driver entirely independent of SPI.h.
  10. // It can be optimized for your board or a different SPI port can be used.
  11. // The driver must be derived from SdSpiBaseClass.
  12. // See: SdFat/src/SpiDriver/SdSpiBaseClass.h
  13. class MySpiClass : public SdSpiBaseClass {
  14. public:
  15. // Activate SPI hardware with correct speed and mode.
  16. void activate() { SPI.beginTransaction(m_spiSettings); }
  17. // Initialize the SPI bus.
  18. void begin(SdSpiConfig config) {
  19. (void)config;
  20. SPI.begin();
  21. }
  22. // Deactivate SPI hardware.
  23. void deactivate() { SPI.endTransaction(); }
  24. // Receive a byte.
  25. uint8_t receive() { return SPI.transfer(0XFF); }
  26. // Receive multiple bytes.
  27. // Replace this function if your board has multiple byte receive.
  28. uint8_t receive(uint8_t* buf, size_t count) {
  29. for (size_t i = 0; i < count; i++) {
  30. buf[i] = SPI.transfer(0XFF);
  31. }
  32. return 0;
  33. }
  34. // Send a byte.
  35. void send(uint8_t data) { SPI.transfer(data); }
  36. // Send multiple bytes.
  37. // Replace this function if your board has multiple byte send.
  38. void send(const uint8_t* buf, size_t count) {
  39. for (size_t i = 0; i < count; i++) {
  40. SPI.transfer(buf[i]);
  41. }
  42. }
  43. // Save SPISettings for new max SCK frequency
  44. void setSckSpeed(uint32_t maxSck) {
  45. m_spiSettings = SPISettings(maxSck, MSBFIRST, SPI_MODE0);
  46. }
  47. private:
  48. SPISettings m_spiSettings;
  49. } mySpi;
  50. #if ENABLE_DEDICATED_SPI
  51. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SD_SCK_MHZ(50), &mySpi)
  52. #else // ENABLE_DEDICATED_SPI
  53. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SD_SCK_MHZ(50), &mySpi)
  54. #endif // ENABLE_DEDICATED_SPI
  55. SdFat sd;
  56. //------------------------------------------------------------------------------
  57. void setup() {
  58. Serial.begin(9600);
  59. if (!sd.begin(SD_CONFIG)) {
  60. sd.initErrorHalt(&Serial);
  61. }
  62. sd.ls(&Serial, LS_SIZE);
  63. Serial.println("Done");
  64. }
  65. //------------------------------------------------------------------------------
  66. void loop() {}
  67. #else // SPI_DRIVER_SELECT
  68. #error SPI_DRIVER_SELECT must be three in SdFat/SdFatConfig.h
  69. #endif // SPI_DRIVER_SELECT