51單片機讀寫SD卡程序
//================================================================
//往SD卡指定地址寫數(shù)據(jù),一次最多512字節(jié)
//unsigned char SdWriteBlock(unsigned char *Block, unsigned long address,int len)
unsigned char SdWriteBlock(unsigned long address,int len)
{
unsigned int count;
unsigned char dataResp;
//Block size is 512 bytes exactly
//First Lower SS
SD_CS=0;
//Then send write command
SdCommand(0x18,address,0xff);
if(SdResponse()==00)
{
SdWrite(0xff);
SdWrite(0xff);
SdWrite(0xff);
//command was a success - now send data
//start with DATA TOKEN = 0xFE
SdWrite(0xfe);
//now send data
//for(count=0;count
//data block sent - now send checksum
SdWrite(0xff); //兩字節(jié)CRC校驗, 為0XFFFF 表示不考慮CRC
SdWrite(0xff);
//Now read in the DATA RESPONSE token
dataResp=SdRead();
//Following the DATA RESPONSE token
//are a number of BUSY bytes
//a zero byte indicates the MMC is busy
while(SdRead()==0);
dataResp=dataResp&0x0f; //mask the high byte of the DATA RESPONSE token
SD_CS=1;
SdWrite(0xff);
if(dataResp==0x0b)
{
//printf("DATA WAS NOT ACCEPTED BY CARD -- CRC ERROR");
return 0;
}
if(dataResp==0x05)
return 1;
//printf("Invalid data Response token.");
return 0;
}
//printf("Command 0x18 (Write) was not received by the MMC.");
return 0;
}
//=======================================================================
//從SD卡指定地址讀取數(shù)據(jù),一次最多512字節(jié)
unsigned char SdReadBlock(unsigned char *Block, unsigned long address,int len)
{
unsigned int count;
//Block size is 512 bytes exactly
//First Lower SS
SD_CS=0;
//Then send write command
SdCommand(0x11,address,0xff);
if(SdResponse()==00)
{
//command was a success - now send data
//start with DATA TOKEN = 0xFE
while(SdRead()!=0xfe);
for(count=0;count
//data block sent - now send checksum
SdRead();
SdRead();
//Now read in the DATA RESPONSE token
SD_CS=1;
SdRead();
return 1;
}
return 0;
}
void initbaud(void)
{
TMOD=0X20;
TH1=0XFD;
TL1=0XFD;
PCON=0X00;
TR1=1;
SCON=0X50;//8位波特可變
//SCON=0X52;//8位波特可變 TI開中斷
}
//============================================================
//主程序
main()
{
}
可以在串口中看到SD卡中被寫入的數(shù)據(jù),程序在MCU-51/AVR開發(fā)板進行了實驗。具體介紹可訪問:
http://item.taobao.com/item.htm?spm=0.0.0.50.xZjZ87&id=21441052281,http://item.taobao.com/item.htm?spm=1103*oQM.3-5SusJ.h-2Yh1mq&id=14049701171&
評論