retry = 0;
cs=0;
do
{
for(i=0;i<100;i++) SPI_WriteByte(0xff);
r1 = SD_SendCommand(1, 0); //发Active命令
retry++;
if(retry>254) return 1; //超时退出
} while(r1);
for(i=0;i<100;i++) SPI_WriteByte(0xff);
r1 = SD_SendCommand(59, 0); //关crc
if (r1) return 1; //返回不正确,退出初始化
for(i=0;i<100;i++) SPI_WriteByte(0xff);
r1 = SD_SendCommand(16, 512); //设扇区大小512
if(r1!=0) return 1; //返回不正确,退出初始化
return 0; //正常返回
}
//********************写一个扇区**************************
unsigned char SD_WriteSingleBlock(unsigned long sector)
{
unsigned char r1;
unsigned int i;
unsigned char retry=0;
do
{
for(i=0;i<100;i++) SPI_WriteByte(0xff);
r1 = SD_SendCommand(24, sector<<9);//写命令
retry++;
if(retry>10) return 1; //超时退出
} while(r1 != 0x00);
cs=0;
SPI_WriteByte(0xff);
SPI_WriteByte(0xff);
SPI_WriteByte(0xff);
SPI_WriteByte(0xff);
SPI_WriteByte(0xff);
SPI_WriteByte(0xff);
SPI_WriteByte(0xfe); //发开始符
for(i=0; i<512; i++) //送512字节数据
{
if(i<255) SPI_WriteByte(i); //发送0--255
else SPI_WriteByte(512-i); //发送255--0
}
SPI_WriteByte(0x95);
SPI_WriteByte(0x95); //16-bits CRC
r1 = SPI_WriteByte(0xff); //读响应位
if(retry++ >10) return 1; //超时退出
while(!((r1&0x0f)==5)); //等待数据成功接受返回信息
while(!(SPI_WriteByte(0xff))); //等待SD卡内部编程完成
return 0;
}
//******************读SD卡一个扇区************************
unsigned char SD_ReadSingleBlock(unsigned long sector)
{
unsigned char r1,temp;
unsigned int i,j;
unsigned char retry=0;
do
{
r1 = SD_SendCommand(17, sector<<9);//读命令
retry++;
if(retry>10) return 1; //超时退出
} while(r1 != 0x00);
cs=0;
while(SPI_WriteByte(0xff)!= 0xfe) //等待接收到开始字节
{
if(retry++ >100) return 1; //超时退出
}
for(i=0; i<512; i++) //读512个数据
{
temp = SPI_WriteByte(0xff); //读取接收到的数据
lcd[0]=(temp/100)+48;
lcd[1]=((temp%100)/10)+48;
lcd[2]=((temp%100)%10)+48;
lcd_display(); //读取数据送显示
for(j=0;j<500;j++) {delay();}
}
SPI_WriteByte(0xff); //伪16-bits crc
SPI_WriteByte(0xff);
cs=1;
return 0;
}
//***********************延时程序*************************
void delay() //延时程序
{
int i; //定义整形变量
for(i=0x100;i--;); //延时
}
//************************主函数**************************
int main(void)
{
unsigned char loop,res;
delay();
delay();
delay();
loop=1;
cs=1;
while(loop)
{
spi_init(); //调用系统初始化函数
res= sd_reset(); //调用SD卡初始化函数
if(res) break; //SD卡初始化是否正常,不正常,退出循环,不执行下面的读写操作
SD_WriteSingleBlock(1); //调用写SD卡单BLOCK函数,其中扇区号为1
if(res) break;
SD_ReadSingleBlock(1); //调用读SD卡单BLOCK函数,其中扇区号为1
if(res) break;
loop=0;
while(1);
}
while(1);
}