Low level SD card access

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Low level SD card access

Jump to solution
1,849 Views
MPotts
Contributor III

 

I am trying to implement low level access (read and write single sectors) from/to an SD card. I have studied the SPI and SD Card sections in the I/O Drivers Guide and the sdcard sample and come up with the following code (including scard.c and sdcard_spi.c plus headers):

 

MCF5XXX_QSPI_INIT_STRUCT _qspi0_init = {
   0,                            /* SPI channel                     */
   MCF5XXX_QSPI_QDR_QSPI_CS0,    /* Chip Select 0                   */
   SPI_DEVICE_MASTER_MODE,       /* Transfer mode                   */
   BSP_QSPI_BAUDRATE,            /* SPI Baud rate register value    */
   BSP_SYSTEM_CLOCK/2,           /* Clock Speed                     */
   SPI_CLK_POL_PHA_MODE0,        /* SPI clock phase                 */
   BSP_QSPI_RX_BUFFER_SIZE,      /* Rx Buffer Size (interrupt only) */
   BSP_QSPI_TX_BUFFER_SIZE       /* Tx Buffer Size (interrupt only) */
};

SDCARD_INIT_STRUCT _sdcard0_init = {
    _io_sdcard_spi_init,
    _io_sdcard_spi_read_block,
    _io_sdcard_spi_write_block,
    MCF5XXX_QSPI_QDR_QSPI_CS0
};
   
  _mcf5xxx_qspi_polled_install("spi0:", &_qspi0_init);
  spifd = fopen("spi0:", SPI_FLAG_HALF_DUPLEX);
  rc = _io_sdcard_install("sdcard:", &_sdcard0_init, spifd);
  rc = _io_sdcard_spi_init(spifd));
  rc = _io_sdcard_open(spifd, "", "");
  rc = _io_sdcard_write_blocks(spifd, buffer, n);
  rc = _io_sdcard_read_blocks(spifd, buffer, n);

On execution the code hangs in _io_sdcard_spi_init(). Any suggestions as to possible causes appreciated.

 

Mark

Labels (1)
Tags (1)
0 Kudos
1 Solution
715 Views
MPotts
Contributor III

 

Solved the fwread/fwrite problem. The counts are in sectors (512 bytes) not bytes. All now working well.

 

Mark

View solution in original post

0 Kudos
3 Replies
715 Views
PetrM
Senior Contributor I

Hello,

 

you should access sdcard through its posix API:

 

  _mcf5xxx_qspi_polled_install("spi0:", &_qspi0_init);

  spifd = fopen("spi0:", SPI_FLAG_HALF_DUPLEX);
  rc = _io_sdcard_install("sdcard:", &_sdcard0_init, spifd);

  sdcardfd = fopen ("sdcard:", NULL);  // this calls _io_sdcard_spi_init() internally

  fwrite (buffer, 1, n, sdcardfd);
  fread (buffer, 1, n, sdcardfd);
    

 

Regards,

PetrM

0 Kudos
715 Views
MPotts
Contributor III

Hi PetrM,

 

Thanks, this works a lot better. It now fails to open the SD card if it no card is present present but succeeds if there is!

 

However fwrite() and fread() both return -1 which I assume indicates an error. How do I determine the precise error?

 

Mark

0 Kudos
716 Views
MPotts
Contributor III

 

Solved the fwread/fwrite problem. The counts are in sectors (512 bytes) not bytes. All now working well.

 

Mark

0 Kudos