if(retry==100) //重试100次 {
SD_Disable(); //关片选
return(INIT_CMD1_ERROR); //如果重试100次失败返回错误号 }
}while(temp!=0);
MSD_Disable(); //关片选
SPCR=0x50; //设置SPI为2分频。进行高速读写 SPSR=0x01;
return(TRUE); //返回成功 }
//**************************************************************************** //发送命令给 MMC/SD卡
//Return: 返回MMC/SD卡对命令响应的第2字节,作为命令成功判断
unsigned char Write_Command_SD(unsigned char cmd,unsigned long address)
//**************************************************************************** {
unsigned char tmp; unsigned char retry=\
SD_Disable();
SPI_TransferByte(0xFF);
SD_Enable();
SPI_TransferByte(cmd); //将32位地址进行移位作为地址字节 SPI_TransferByte(address>>24); SPI_TransferByte(address>>16); SPI_TransferByte(address>>8); SPI_TransferByte(address); SPI_TransferByte(0xFF);
SPI_TransferByte(0xFF); do{
tmp = SPI_TransferByte(0xFF); //发送8个时钟接受最后一个字节 retry++;
}while((tmp==0xff)&&(retry<8)); return(tmp); }
//****************************************************************************
//写一个扇区(512Byte) to MMC/SD-Card //如果写完成返回TRUE
unsigned char SD_write_sector(unsigned long addr,unsigned char *Buffer)
//**************************************************************************** {
unsigned char temp; unsigned int i;
SPI_TransferByte(0xFF); //延迟8个时钟
SD_Enable(); //开片选
temp
Write_Command_MMC(MMC_WRITE_BLOCK,addr<<9); 送写扇区命令 if(temp != 0x00) {
SD_Disable(); return(temp); }
SPI_TransferByte(0xFF); SPI_TransferByte(0xFF); SPI_TransferByte(0xFE);
for (i=0;i<512;i++) {
=
//发 SPI_TransferByte(*Buffer++); //发送512字节数据 }
//CRC-Byte
SPI_TransferByte(0xFF); //Dummy CRC SPI_TransferByte(0xFF); //CRC Code
temp = SPI_TransferByte(0xFF); //读SD卡运行响应
if((temp & 0x1F)!=0x05) //如果最后4位为0101,为操作成功。否则为操作失败。 {
SD_Disable();
return(WRITE_BLOCK_ERROR); //返回错误 }
while (SPI_TransferByte(0xFF) != 0xFF);
SD_Disable();
return(TRUE); //返回成功 }
//**********************************************************