一定要注意SD卡是3.3V的工作电压,一定要做电平转换,否则会烧坏SD卡!也可以直接让单片机在3.3V下工作。
模拟SPI总线的子程序:
sbit CS=P1^0;
sbit CLK= P1^1;
sbit DATaI=P1^2;
sbit DATaO=P1^3;
#define SD_Disable() CS=1 //Disable CS
#define SD_Enable() CS=0 //Enable CS
unsigned char SPI_TransferByte(unsigned char val)
{
unsigned char BitCounter;
for(BitCounter=8; BiCounter!=0; BitCounter--)
{
CLK=0; DATaI=0; // write
if(val&0x80) DATaI=1;
val<<=1; CLK=1;
if(DATaO)val|=1; // read
}
CLK=0;
return val;
}
初始化SD卡的子程序
unsigned char SD_Init(void)
{
unsigned char retry,temp;
unsigned char i;
for (i=0;i<0x0f;i++)
{ SPI_TransferByte(0xff); //delay }
SD_Enable(); //Enable Chip select
SPI_TransferByte(SD_RESET); //send a reset command
SPI_TransferByte(0x00);
SPI_TransferByte(0x00);
SPI_TransferByte(0x00);
SPI_TransferByte(0x00);
SPI_TransferByte(0x95);
SPI_TransferByte(0xff);
SPI_TransferByte(0xff);
retry=0;
do
{
temp=Write_Command_SD(SD_INIT,0); //Send the initialization command
retry++;
if(retry==100) //retry 100 times
{
SD_Disable(); //disable chip select
return(INIT_CMD1_ERROR); //If retry fails returns an error number
}
}while(temp!=0);
SD_Disable(); //disable card
return(TRUE); //return success
}
有关于SD卡的其他操作,可以参考SD Specifications
http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf