Bit Banging SPI in SD Filesystem

26 Jan 2013

After figure out how SPI working, I decided to build one in software(just for learning purpose). The code is quite simple, but after I replace it with the SPI.write() function in SD Filesystem, no response from SD card, miso is high all the time.

void SDFileSystem::spiWrite(int spi_data)
{
    for (int i = 0; i <8; i++)
    {
        
        if(spi_data & 0x80)
        {
           _mosi = 1;
        }
        else
        {
           _mosi = 0;
        }
        
        
        _sclk = 0;
 
        wait_us(0.01);
        
        spi_data <<= 1;
        
        _sclk = 1;
 
     }
        
      wait_us(0.02); 
 
        _sclk = 0;

}

int SDFileSystem::spiRead()
{


    int data = 0;
    _mosi =1;
    
    for(int i = 0; i<8; i++)
    {
        _sclk =1;
        
        data <<= 1;
       wait_us(0.01);
        
     if(_miso)
     {
        data |=1;
     }
        
        _sclk = 0;
    }
    
    return data;
}

int SDFileSystem::initialise_card() {
//clock card with cs = 1 
    _cs = 1;
    for(int i=0; i<16; i++) {   

          spiWrite(0xFF);  
       
    }

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

    // send CMD8 to determine whther it is ver 2.x
    int r = _cmd8();
    if(r == R1_IDLE_STATE) {
        return initialise_card_v2();
    } else if(r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
        return initialise_card_v1();
    } else {
        fprintf(stderr, "Not in idle state after sending CMD8 (not an SD card?)\n");
        return SDCARD_FAIL;
    }
}

I thought this code should act same as the hardware SPI, but SD card can't be initialized, is there anything wrong in this code?

26 Jan 2013

Wait_us expects an integer, so it probably isnt doing anything. Even if it was doing anyting, those would be 10ns waits, that isnt too long. Now DigitalOuts arent exceptionally fast, but it might be too fast for your SD card.

You say you checked MISO? Did you then also check MOSI, and simply compare it to the normal SPI library.