//*****************发送命令函数****************************
unsigned char SD_SendCommand(unsigned char cmd,unsigned long arg)
{
unsigned char r1;
unsigned char retry1=0; //重复操作次数
cs=0; //使能片选信号
SPI_WriteByte(cmd | 0x40); //分别写入命令
SPI_WriteByte(arg>>24); //数据段第4字节
SPI_WriteByte(arg>>16); //数据段第3字节
SPI_WriteByte(arg>>8); //数据段第2字节
SPI_WriteByte(arg); //数据段第1字节
SPI_WriteByte(0x95); //CRC效验和
while((r1 = SPI_WriteByte(0xff)) == 0xff)//等待响应
if(retry1++ > 200) break;//超时退出
cs=1; //清初片选信号
return r1; //返回状态值
}
//*******************SD开初始化函数**************************
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(); //读取数据送显示
本文关键字:程序 电脑-单片机-自动控制,电子学习 - 基础知识 - 电脑-单片机-自动控制
上一篇:Dracula LVS编程介绍