微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > SD卡读写实验程序

SD卡读写实验程序

时间:03-30 来源:互联网 点击:

return r1; //返回状态值
}

//*******************SD开初始化函数**************************
unsigned char sd_reset()
{
unsigned char i,tmp;
unsigned char retry; //重复次数
unsigned char r1=0;
retry=0;
delay();
delay();
do
{
for(i=0;i100;i++) SPI_WriteByte(0xff);

r1 = SD_SendCommand(0,0);//发idle命令
retry++;
if(retry>20) return 1; //超时退出
} while(r1 != 0x01); //等待IDLE命令返回

retry = 0;
cs=0;
do
{
for(i=0;i100;i++) SPI_WriteByte(0xff);

r1 = SD_SendCommand(1, 0); //发Active命令
retry++;
if(retry>254) return 1; //超时退出
} while(r1);

for(i=0;i100;i++) SPI_WriteByte(0xff);

r1 = SD_SendCommand(59, 0); //关crc
if (r1) return 1; //返回不正确,退出初始化

for(i=0;i100;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;i100;i++) SPI_WriteByte(0xff);

r1 = SD_SendCommand(24, sector9);//写命令
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; i512; i++) //送512字节数据
{
if(i255) 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(!((r10x0f)==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, sector9);//读命令
retry++;
if(retry>10) return 1; //超时退出
} while(r1 != 0x00);
cs=0;
while(SPI_WriteByte(0xff)!= 0xfe) //等待接收到开始字节
{
if(retry++ >100) return 1; //超时退出
}
for(i=0; i512; 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;j500;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);
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top