微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > STC52单片机的SD卡底层驱动——SPI

STC52单片机的SD卡底层驱动——SPI

时间:11-22 来源:互联网 点击:

time = 0;
do{
temp = SD_Write_Cmd(pcmd);
time++;
if(time==TRY_TIME){ //CMD1写入失败
SD_CS=1;
return(INIT_CMD1_ERROR);
}
}while(temp!=0);

Is_init = 0; //讲Is_init设置为0,提高SPI速度
SD_CS = 1;//关闭片选
SD_spi_write(0xff); //补充8个时钟
return(0);
}

unsigned char SD_Write_Sector(unsigned long addr,unsigned char *buffer)
{
unsigned char temp,time;
unsigned int i;
unsigned char pcmd[]={0x58,0x00,0x00,0x00,0x00,0xff};

addr<=9;
pcmd[1] = ((addr&0xff000000)>>24);
pcmd[2] = ((addr&0x00ff0000)>>16);
pcmd[3] = ((addr&0x0000ff00)>>8);

SD_CS = 0;
time = 0;

do{
temp=SD_Write_Cmd(pcmd);//写入CMD0
time++;
if(time == TRY_TIME)
{
SD_CS = 1; //关闭片选
return(temp); //写入失败
}
}while(temp!=0);

for(i=0;i<100;i++) //插入若干个字节的时钟,保持稳定性
{
SD_spi_write(0xff);
}

SD_spi_write(0xfe); //写入0xfe,后面就是要写入的数据

for(i=0;i<512;i++)
{
SD_spi_write(buffer[i]);
}

SD_spi_write(0xff); //两个字节的CRC校验码
SD_spi_write(0xff);

temp = SD_spi_read(); //读取返回值
if((temp&0x1f)!=0x05){
SD_CS = 1;
return(WRITE_BLOCK_ERROR); //写块数据失败
}
while(SD_spi_read()!=0xff);//SD卡忙状态,等待

SD_CS = 1;

SD_spi_write(0xff);//补充8个时钟
return(0);

}

unsigned char SD_Read_Sector(unsigned long addr,unsigned char *buffer)
{
unsigned int j;
unsigned char time,temp;
unsigned char pcmd[]={0x51,0x00,0x00,0x00,0x00,0xff}; //CMD17的字节序列

addr<=9; //addr=addr*512 将块地址(扇区地址)转为字节地址

pcmd[1]=((addr&0xff000000)>>24);//将字节地址写入到CMD17字节序列中
pcmd[2]=((addr&0x00FF0000)>>16);
pcmd[3]=((addr&0x0000FF00)>>8);

SD_CS=0;//打开片选

time=0;
do{
temp = SD_Write_Cmd(pcmd);
time++;
if(time==TRY_TIME){
return(READ_BLOCK_ERROR);
}
}while(temp!=0);

while(SD_spi_read()!=0xfe); //读到0xfe,说明后面是512字节的数据

for(j=0;j<512;j++)
{
buffer[j]=SD_spi_read();
}

SD_spi_read(); //读取两个字节的CRC校验码
SD_spi_read();

SD_CS=1;

SD_spi_write(0xff); //补充8个时钟

return 0;

}

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

网站地图

Top