updated chan_fatfs

Dependents:   HARP2 HARP3

Fork of chan_fatfs by Eli Hughes

diskio.cpp

Committer:
tylerjw
Date:
2012-12-28
Revision:
8:1f9748c6b865
Parent:
4:f88948891a05

File content as of revision 8:1f9748c6b865:

/*-----------------------------------------------------------------------*/
/* Low level disk I/O module skeleton for FatFs     (C)ChaN, 2007        */
/*-----------------------------------------------------------------------*/
/* This is a stub disk I/O module that acts as front end of the existing */
/* disk I/O modules and attach it to FatFs module with common interface. */
/*-----------------------------------------------------------------------*/

#include "diskio.h"
#include "mbed.h"
#include "mbed_debug.h"


//******************************************************************************************************************
// MBED SPI/CS Select functions.... Modify for your layout.
//**************************************************************************************

SPI _spi(p5, p6, p7); // mosi, miso, sclk
DigitalOut _cs(p8);

//******************************************************************************************************************
// Low Level Sector Access Function Prototypes('C' Castrated versions of Simon Ford's C++ MBED SDFileSystem class
//******************************************************************************************************************
int _cmd(int cmd, int arg);
int _read(BYTE *buffer, int length);
int _write(BYTE *buffer, int length);
uint32_t ext_bits(BYTE *data, int msb, int lsb);
int _sd_sectors();
int _sectors;
int _cmd(int cmd, int arg);
int _cmdx(int cmd, int arg);
int _cmd8();
int _cmd58();
int cdv;

#define SD_COMMAND_TIMEOUT 5000

#define R1_IDLE_STATE           (1 << 0)
#define R1_ERASE_RESET          (1 << 1)
#define R1_ILLEGAL_COMMAND      (1 << 2)
#define R1_COM_CRC_ERROR        (1 << 3)
#define R1_ERASE_SEQUENCE_ERROR (1 << 4)
#define R1_ADDRESS_ERROR        (1 << 5)
#define R1_PARAMETER_ERROR      (1 << 6)


//******************************************************************************************************************
// Sector Access functions for CHAN FatFs
//******************************************************************************************************************

DRESULT disk_ioctl (
    BYTE drv,        /* Physical drive nmuber (0..) */
    BYTE ctrl,        /* Control code */
    void *buff        /* Buffer to send/receive control data */
)
{
    DRESULT res;

    switch(ctrl) {
        case CTRL_SYNC:
            res = RES_OK;
            break;

        case GET_SECTOR_SIZE:
            res = RES_OK;
            *(WORD *)buff = 512;
            break;

        case GET_SECTOR_COUNT:
            res = RES_OK;
            *(DWORD *)buff = (WORD)_sd_sectors();
            break;

        case GET_BLOCK_SIZE:
            res = RES_OK;
            *(DWORD *)buff = 1;
            break;

        default:
            res = RES_OK;
            break;
    }
    return res;
}

DSTATUS card_initialize(BYTE Drive)
{
    // Set to 100kHz for initialisation, and clock card with cs = 1
    _spi.frequency(100000);
    _cs = 1;
    for (int i = 0; i < 16; i++) {
        _spi.write(0xFF);
    }

    // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
    if (_cmd(0, 0) != R1_IDLE_STATE) {
        debug("No disk, or could not put SD card in to SPI idle state\n");
        return STA_NOINIT;
    }

    // send CMD8 to determine whther it is ver 2.x
    int r = _cmd8();
    if (r == R1_IDLE_STATE) {
        for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
            wait_ms(50);
            _cmd58();
            _cmd(55, 0);
            if (_cmd(41, 0x40000000) == 0) {
                _cmd58();
                //debug_if(SD_DBG, "\n\rInit: SDCARD_V2\n\r");
                cdv = 1;
                return 0;
            }
        }
        debug("Timeout waiting for v2.x card\n");
        return STA_NOINIT;

    } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
        for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
            _cmd(55, 0);
            if (_cmd(41, 0) == 0) {
                cdv = 512;
                //debug_if(SD_DBG, "\n\rInit: SEDCARD_V1\n\r");
                return 0;
            }
        }
        debug("Timeout waiting for v1.x card\n");
        return STA_NOINIT;

    } else {
        debug("Not in idle state after sending CMD8 (not an SD card?)\n");
        return STA_NOINIT;
    }
}

DSTATUS disk_initialize(BYTE Drive)
{
    DSTATUS ret = card_initialize(Drive);

    _sectors = _sd_sectors();

    // Set block length to 512 (CMD16)
    if (_cmd(16, 512) != 0) {
        debug("Set 512-byte block timed out\n");
        return STA_NOINIT;
    }

    _spi.frequency(10000000); // Set to 10MHz for data transfer
    return ret;
}

DRESULT disk_write(BYTE Drive,const BYTE * Buffer, DWORD SectorNumber, BYTE SectorCount)
{
    BYTE i;

    BYTE * MyBufOut = (BYTE *)Buffer;

    for(i=0; i<SectorCount; i++) {
        // set write address for single block (CMD24)
        if(_cmd(24, (SectorNumber + i) * 512 ) != 0) {
            return RES_ERROR;
        }

        // send the data block
        _write(MyBufOut, 512);

        MyBufOut+=512;
    }
    return RES_OK;
}

DRESULT disk_read(BYTE Drive, BYTE * Buffer,DWORD SectorNumber, BYTE SectorCount)
{
    BYTE i;
    for(i=0; i<SectorCount; i++) {
        // set read address for single block (CMD17)
        if(_cmd(17, (SectorNumber+i) * 512) != 0) {
            return RES_ERROR;
        }
        // receive the data
        _read(Buffer, 512);

        Buffer+=512;
    }
    return RES_OK;
}


DWORD get_fattime(void)
{
    time_t CurrentTimeStamp;
    tm *CurrentLocalTime;
    DWORD FATFSTimeCode;

    CurrentTimeStamp = time(NULL);
    CurrentLocalTime = localtime(&CurrentTimeStamp);

    //Map the tm struct time into the FatFs time code
    FATFSTimeCode =  ((CurrentLocalTime->tm_year-80)<<25) |
                     ((CurrentLocalTime->tm_mon+1)<<21)   |
                     ((CurrentLocalTime->tm_mday)<<16)    |
                     ((CurrentLocalTime->tm_hour)<<11)    |
                     ((CurrentLocalTime->tm_min)<<5)     |
                     ((CurrentLocalTime->tm_sec));

    return FATFSTimeCode;
}

DSTATUS disk_status(BYTE Drive)
{
    return 0;
}

//**************************************************************************************
// Low Level Sector Access Functions (Castrated versions of Simon Fords C++ MBED class
//**************************************************************************************

int _cmd(int cmd, int arg)
{
    _cs = 0;

    // send a command
    _spi.write(0x40 | cmd);
    _spi.write(arg >> 24);
    _spi.write(arg >> 16);
    _spi.write(arg >> 8);
    _spi.write(arg >> 0);
    _spi.write(0x95);

    // wait for the repsonse (response[7] == 0)
    for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
        int response = _spi.write(0xFF);
        if (!(response & 0x80)) {
            _cs = 1;
            _spi.write(0xFF);
            return response;
        }
    }
    _cs = 1;
    _spi.write(0xFF);
    return -1; // timeout
}
int _cmdx(int cmd, int arg)
{
    _cs = 0;

    // send a command
    _spi.write(0x40 | cmd);
    _spi.write(arg >> 24);
    _spi.write(arg >> 16);
    _spi.write(arg >> 8);
    _spi.write(arg >> 0);
    _spi.write(0x95);

    // wait for the repsonse (response[7] == 0)
    for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
        int response = _spi.write(0xFF);
        if (!(response & 0x80)) {
            return response;
        }
    }
    _cs = 1;
    _spi.write(0xFF);
    return -1; // timeout
}


int _cmd58()
{
    _cs = 0;
    int arg = 0;

    // send a command
    _spi.write(0x40 | 58);
    _spi.write(arg >> 24);
    _spi.write(arg >> 16);
    _spi.write(arg >> 8);
    _spi.write(arg >> 0);
    _spi.write(0x95);

    // wait for the repsonse (response[7] == 0)
    for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
        int response = _spi.write(0xFF);
        if (!(response & 0x80)) {
            int ocr = _spi.write(0xFF) << 24;
            ocr |= _spi.write(0xFF) << 16;
            ocr |= _spi.write(0xFF) << 8;
            ocr |= _spi.write(0xFF) << 0;
            _cs = 1;
            _spi.write(0xFF);
            return response;
        }
    }
    _cs = 1;
    _spi.write(0xFF);
    return -1; // timeout
}

int _cmd8()
{
    _cs = 0;

    // send a command
    _spi.write(0x40 | 8); // CMD8
    _spi.write(0x00);     // reserved
    _spi.write(0x00);     // reserved
    _spi.write(0x01);     // 3.3v
    _spi.write(0xAA);     // check pattern
    _spi.write(0x87);     // crc

    // wait for the repsonse (response[7] == 0)
    for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) {
        char response[5];
        response[0] = _spi.write(0xFF);
        if (!(response[0] & 0x80)) {
            for (int j = 1; j < 5; j++) {
                response[i] = _spi.write(0xFF);
            }
            _cs = 1;
            _spi.write(0xFF);
            return response[0];
        }
    }
    _cs = 1;
    _spi.write(0xFF);
    return -1; // timeout
}
int _read(BYTE *buffer, int length)
{
    _cs = 0;

    // read until start byte (0xFF)
    while (_spi.write(0xFF) != 0xFE);

    // read data
    for (int i = 0; i < length; i++) {
        buffer[i] = _spi.write(0xFF);
    }
    _spi.write(0xFF); // checksum
    _spi.write(0xFF);

    _cs = 1;
    _spi.write(0xFF);
    return 0;
}


int _write(BYTE *buffer, int length)
{
    _cs = 0;

    // indicate start of block
    _spi.write(0xFE);

    // write the data
    for (int i = 0; i < length; i++) {
        _spi.write(buffer[i]);
    }

    // write the checksum
    _spi.write(0xFF);
    _spi.write(0xFF);

    // check the response token
    if ((_spi.write(0xFF) & 0x1F) != 0x05) {
        _cs = 1;
        _spi.write(0xFF);
        return 1;
    }

    // wait for write to finish
    while (_spi.write(0xFF) == 0);

    _cs = 1;
    _spi.write(0xFF);
    return 0;
}

static uint32_t ext_bits(unsigned char *data, int msb, int lsb)
{
    uint32_t bits = 0;
    uint32_t size = 1 + msb - lsb;
    for (int i = 0; i < size; i++) {
        uint32_t position = lsb + i;
        uint32_t byte = 15 - (position >> 3);
        uint32_t bit = position & 0x7;
        uint32_t value = (data[byte] >> bit) & 1;
        bits |= value << i;
    }
    return bits;
}

int _sd_sectors()
{
    uint32_t c_size, c_size_mult, read_bl_len;
    uint32_t block_len, mult, blocknr, capacity;
    uint32_t hc_c_size;
    uint64_t blocks;

    // CMD9, Response R2 (R1 byte + 16-byte block read)
    if (_cmdx(9, 0) != 0) {
        debug("Didn't get a response from the disk\n");
        return 0;
    }

    uint8_t csd[16];
    if (_read(csd, 16) != 0) {
        debug("Couldn't read csd response from disk\n");
        return 0;
    }

    // csd_structure : csd[127:126]
    // c_size        : csd[73:62]
    // c_size_mult   : csd[49:47]
    // read_bl_len   : csd[83:80] - the *maximum* read block length

    int csd_structure = ext_bits(csd, 127, 126);

    switch (csd_structure) {
        case 0:
            cdv = 512;
            c_size = ext_bits(csd, 73, 62);
            c_size_mult = ext_bits(csd, 49, 47);
            read_bl_len = ext_bits(csd, 83, 80);

            block_len = 1 << read_bl_len;
            mult = 1 << (c_size_mult + 2);
            blocknr = (c_size + 1) * mult;
            capacity = blocknr * block_len;
            blocks = capacity / 512;
            //debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks);
            break;

        case 1:
            cdv = 1;
            hc_c_size = ext_bits(csd, 63, 48);
            blocks = (hc_c_size+1)*1024;
            //debug_if(SD_DBG, "\n\rSDHC Card \n\rhc_c_size: %d\n\rcapacity: %lld \n\rsectors: %lld\n\r", hc_c_size, blocks*512, blocks);
            break;

        default:
            debug("CSD struct unsupported\r\n");
            return 0;
    };
    return blocks;
}