📄 sd.c
字号:
#include "config.h"
#include "sd.h"
//----------------------------------------
//SPI initialize
void spi_init(void)
{
DDRB = 0xB7; //SI输入,SO,SCK,SS输出
SPCR = 0x50; //setup SPI
SPSR = 0x01; //setup SPI
}
//----------------------------------------
void Write_Byte_SPI(unsigned char byte)
{
SPDR = byte;
while (!SPSR_Bit7);
}
//----------------------------------------
unsigned char Read_Byte_SPI(void)
{
SPDR = 0xFF;
while (!SPSR_Bit7);
return SPDR;
}
unsigned char SD_Buffer[512];
//****************************************************************************
//Send a Command to SD-Card
//Return: the second byte of response register of SD-Card
//****************************************************************************
unsigned char Write_Command_SD(unsigned char cmd,unsigned long arg,unsigned char crc7)
{
unsigned char tmp;
unsigned char retry=0;
//set MMC_Chip_Select to high (SD-Card disable)
SD_Disable();
//send 8 Clock Impulse
Write_Byte_SPI(0xFF); //for ZZZZZZZZ state
//set MMC_Chip_Select to low (SD-Card active)
SD_Enable();
//send 6 Byte Command to SD-Card
Write_Byte_SPI(cmd|0x40); //送头命令
Write_Byte_SPI( (arg>>24) & 0xff );
Write_Byte_SPI( (arg>>16) & 0xff );
Write_Byte_SPI( (arg>> 8) & 0xff );
Write_Byte_SPI( arg&0xff);
Write_Byte_SPI(crc7); //仅仅对RESET有效的CRC效验码
//get 16 bit response
Read_Byte_SPI(); //read the first byte,ignore it.
do
{ //Only last 8 bit is used here.Read it out.
tmp = Read_Byte_SPI();
retry++;
}
while((tmp==0xff)&&(retry<100));
return(tmp);
}
//****************************************************************************
//Routine for Init SD card(SPI-MODE)
//****************************************************************************
unsigned char SD_Init(void)
{
unsigned char retry,temp;
unsigned char i;
spi_init();
//MMC_Port_Init(); //Init SPI port
for(i=0;i<200;i++) //Wait SD ready...
{
NOP();
}
SD_Enable();
for (i=0;i<0xff;i++)
{
Write_Byte_SPI(0xFF); //send 74 clock at least!!!
}
//Send Command CMD0 to SD Card
retry=0;
do
{ //retry 200 times to send CMD0 command
temp=Write_Command_SD(00,00,0x95);
retry++;
if(retry==200)
{
SD_Disable(); //set SD_Chip_Select to high
return(INIT_CMD0_ERROR);//CMD0 Error!
}
}
while(temp!=1);
delay_ms(30);
//Send Command CMD1 to SD-Card
retry=0;
do
{
temp=Write_Command_SD(0x01,0x00,0xFF);
retry++;
if(retry==100)
{
SD_Disable(); //set SD_Chip_Select to high
return(INIT_CMD1_ERROR);//CMD1 Error!
}
}
while(temp!=0);
Write_Command_SD(16,512,0xFF); //sent com16 to sd to set a block len
SD_Disable(); //set SD_Chip_Select to high
return(0); //All commands have been taken.
}
unsigned char SD_Read_Block(unsigned long addr)
{
unsigned char tmp;
unsigned int i;
addr<<=9;
tmp=Write_Command_SD(17,addr,0xff);
while (Read_Byte_SPI()!= 0xfe){ WDR(); }
for(i=0;i<512;i++)
{
SD_Buffer[i]=Read_Byte_SPI();
}
SD_Disable();
return(tmp);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -