sd_card_spi.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Driver and interface for accessing SD card in SPI mode
  2. #include "ZuluSCSI_platform.h"
  3. #include "ZuluSCSI_log.h"
  4. #include <hardware/spi.h>
  5. #include <SdFat.h>
  6. #ifndef SD_USE_SDIO
  7. class RP2040SPIDriver : public SdSpiBaseClass
  8. {
  9. public:
  10. void begin(SdSpiConfig config) {
  11. }
  12. void activate() {
  13. _spi_init(SD_SPI, m_sckfreq);
  14. spi_set_format(SD_SPI, 8, SPI_CPOL_0, SPI_CPHA_0, SPI_MSB_FIRST);
  15. }
  16. void deactivate() {
  17. }
  18. void wait_idle() {
  19. while (!(spi_get_hw(SD_SPI)->sr & SPI_SSPSR_TFE_BITS));
  20. while (spi_get_hw(SD_SPI)->sr & SPI_SSPSR_BSY_BITS);
  21. }
  22. // Single byte receive
  23. uint8_t receive() {
  24. uint8_t tx = 0xFF;
  25. uint8_t rx;
  26. spi_write_read_blocking(SD_SPI, &tx, &rx, 1);
  27. return rx;
  28. }
  29. // Single byte send
  30. void send(uint8_t data) {
  31. spi_write_blocking(SD_SPI, &data, 1);
  32. wait_idle();
  33. }
  34. // Multiple byte receive
  35. uint8_t receive(uint8_t* buf, size_t count)
  36. {
  37. spi_read_blocking(SD_SPI, 0xFF, buf, count);
  38. if (m_stream_callback && buf == m_stream_buffer + m_stream_count)
  39. {
  40. m_stream_count += count;
  41. m_stream_callback(m_stream_count);
  42. }
  43. return 0;
  44. }
  45. // Multiple byte send
  46. void send(const uint8_t* buf, size_t count) {
  47. spi_write_blocking(SD_SPI, buf, count);
  48. if (m_stream_callback && buf == m_stream_buffer + m_stream_count)
  49. {
  50. m_stream_count += count;
  51. m_stream_callback(m_stream_count);
  52. }
  53. }
  54. void setSckSpeed(uint32_t maxSck) {
  55. m_sckfreq = maxSck;
  56. }
  57. void set_sd_callback(sd_callback_t func, const uint8_t *buffer)
  58. {
  59. m_stream_buffer = buffer;
  60. m_stream_count = 0;
  61. m_stream_callback = func;
  62. }
  63. private:
  64. uint32_t m_sckfreq;
  65. const uint8_t *m_stream_buffer;
  66. uint32_t m_stream_count;
  67. sd_callback_t m_stream_callback;
  68. };
  69. void sdCsInit(SdCsPin_t pin)
  70. {
  71. }
  72. void sdCsWrite(SdCsPin_t pin, bool level)
  73. {
  74. if (level)
  75. sio_hw->gpio_set = (1 << SD_SPI_CS);
  76. else
  77. sio_hw->gpio_clr = (1 << SD_SPI_CS);
  78. }
  79. RP2040SPIDriver g_sd_spi_port;
  80. SdSpiConfig g_sd_spi_config(0, DEDICATED_SPI, SD_SCK_MHZ(25), &g_sd_spi_port);
  81. void azplatform_set_sd_callback(sd_callback_t func, const uint8_t *buffer)
  82. {
  83. g_sd_spi_port.set_sd_callback(func, buffer);
  84. }
  85. #endif