Read_CSD_SD(sectorBuffer.dat);
//获取总扇区数
vinf->sector_count = sectorBuffer.dat[6] 0x03;
vinf->sector_count = 8;
vinf->sector_count += sectorBuffer.dat[7];
vinf->sector_count = 2;
vinf->sector_count += (sectorBuffer.dat[8] 0xc0) >> 6;
// 获取multiplier
vinf->sector_multiply = sectorBuffer.dat[9] 0x03;
vinf->sector_multiply = 1;
vinf->sector_multiply += (sectorBuffer.dat[10] 0x80) >> 7;
//获取SD卡的容量
vinf->size_MB = vinf->sector_count >> (9-vinf->sector_multiply);
// get the name of the card
Read_CID_SD(sectorBuffer.dat);
vinf->name[0] = sectorBuffer.dat[3];
vinf->name[1] = sectorBuffer.dat[4];
vinf->name[2] = sectorBuffer.dat[5];
vinf->name[3] = sectorBuffer.dat[6];
vinf->name[4] = sectorBuffer.dat[7];
vinf->name[5] = 0x00; //end flag
}
以上程序将信息装载到一个结构体中,这个结构体的定义如下:
typedef struct SD_VOLUME_INFO
{ //SD/SD Card info
unsigned int size_MB;
unsigned char sector_multiply;
unsigned int sector_count;
unsigned char name[6];
} VOLUME_INFO_TYPE;
5) 扇区读
扇区读是对SD卡驱动的目的之一。SD卡的每一个扇区中有512个字节,一次扇区读操作将把某一个扇区内的512个字节全部读出。过程很简单,先写入命令,在得到相应的回应后,开始数据读取。
扇区读的程序例程:
C程序
unsigned char SD_Read_Sector(unsigned long sector,unsigned char *buffer)
{
unsigned char retry;
//命令16
unsigned char CMD[] = {0x51,0x00,0x00,0x00,0x00,0xFF};
unsigned char temp;
//地址变换 由逻辑块地址转为字节地址
sector = sector 9; //sector = sector * 512
CMD[1] = ((sector 0xFF000000) >>24 );
CMD[2] = ((sector 0x00FF0000) >>16 );
CMD[3] = ((sector 0x0000FF00) >>8 );
//将命令16写入SD卡
retry=0;
do
{ //为了保证写入命令 一共写100次
temp=Write_Command_MMC(CMD);
retry++;
if(retry==100)
{
return(READ_BLOCK_ERROR); //block write Error!
}
}
while(temp!=0);
//Read Start Byte form MMC/SD-Card (FEh/Start Byte)
//Now data is ready,you can read it out.
while (Read_Byte_MMC() != 0xfe);
readPos=0;
SD_get_data(512,buffer) ; //512字节被读出到buffer中
return 0;
}
其中SD_get_data函数如下:
//---------------------------------------------------------
获取数据到buffer中
//---------------------------------------------------------
void SD_get_data(unsigned int Bytes,unsigned char *buffer)
{
unsigned int j;
for (j=0;jBytes;j++)
*buffer++ = Read_Byte_SD();
}
6) 扇区写
扇区写是SD卡驱动的另一目的。每次扇区写操作将向SD卡的某个扇区中写入512个字节。过程与扇区读相似,只是数据的方向相反与写入命令不同而已。
扇区写的程序例程:
C程序
//-----------------------------------------------------------------
写512个字节到SD卡的某一个扇区中去 返回0说明写入成功
//-----------------------------------------------------------------
unsigned char SD_write_sector(unsigned long addr,unsigned char *Buffer)
{
unsigned char tmp,retry;
unsigned int i;
//命令24
unsigned char CMD[] = {0x58,0x00,0x00,0x00,0x00,0xFF};
addr = addr 9; //addr = addr * 512
CMD[1] = ((addr 0xFF000000) >>24 );
CMD[2] = ((addr 0x00FF0000) >>16 );
CMD[3] = ((addr 0x0000FF00) >>8 );
//写命令24到SD卡中去
retry=0;
do
{ //为了可靠写入,写100次
tmp=Write_Command_SD(CMD);
retry++;
if(retry==100)
{
return(tmp); //send commamd Error!
}
}
while(tmp!=0);
//在写之前先产生100个时钟信号
for (i=0;i100;i++)
{
Read_Byte_SD();
}
//写入开始字节
Write_Byte_MMC(0xFE);
//现在可以写入512个字节
for (i=0;i512;i++)
{
Write_Byte_MMC(*Buffer++);
}
//CRC-Byte
Write_Byte_MMC(0x
|