⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sd.c

📁 SD卡上对FAT16文件操作系统的读
💻 C
字号:


/*--------------------------------------------------------------------*/
/* SD卡初始化(SPI-MODE) */
/*--------------------------------------------------------------------*/
uchar sd_init(void)
{
	uchar retry,temp,i,cmd[6];
	DDRB |= (BIT(mosi)|BIT(sck)|BIT(ss));
	DDRB &= ~BIT(miso);
	PORTB |= (BIT(miso)|BIT(ss));
	SPCR = (BIT(SPE)|BIT(MSTR)|BIT(SPR0)|BIT(SPR1));
	for(i=0;i<250;i++)asm("nop");
	for(i=0;i<0x0f;i++)
	{											/* send 74 clock at least! */
		write_byte_spi(0xff);
	}
	/* send command CMD0 to SD Card (reset SD Card) */
	retry=0;
	cmd[0]=0x40,cmd[1]=0,cmd[2]=0,cmd[3]=0,cmd[4]=0,cmd[5]=0x95;
	do
	{
		temp=sd_write_command(cmd);
		retry++;
		if(retry>200)
		{										/* CMD0 error */
			return(1);
		}
	}while(temp != 1);
	/* send command CMD1 to SD Card (set SD Card Model:SPI) */
	retry=0;
	cmd[0]=0x41,cmd[1]=0,cmd[2]=0,cmd[3]=0,cmd[4]=0,cmd[5]=0xff;
	do
	{
		temp=sd_write_command(cmd);
		retry++;
		if(retry>100)
		{										/* CMD1 error */
			return(2);
		}
	}while(temp != 0);
	SPCR &= ~(BIT(SPR0)|BIT(SPR1));
	SPSR |= BIT(SPI2X);
	PORTB |= BIT(ss);
	return(0);
}

uchar sd_write_command(uchar *cmd)
{
	uchar temp,retry;
	PORTB |= BIT(ss);
	/* send 80 clock impulse */
	for(temp=0;temp<10;temp++)write_byte_spi(0xff);
	PORTB &= ~BIT(ss);							/* 使能SD卡 */
	/* send command to sd (都为6Bytes) */
	for(temp=0;temp<6;temp++)
	{
		write_byte_spi(*cmd++);
	}
	/* get 8 bit response */
	retry=0;
	do
	{
		temp=read_byte_spi();
		retry++;
		if(retry>100)
		{										/* 没收到有效命令 */
			return(temp);
		}
	}while(temp==0xff);
	return(temp);
}

/*--------------------------------------------------------------------*/
/* 从SD卡读一个扇区  Return 0 if no Error */
/*--------------------------------------------------------------------*/
uchar sd_read_block(ulong address,uchar *data)
{
	uchar temp;
	uint i;
	uchar cmd[6]={0x51,0,0,0,0,0xff}; 
	address=address<<9; 						/* address = address * 512 */
	cmd[1]=((address & 0xff000000) >>24 );
	cmd[2]=((address & 0x00ff0000) >>16 );
	cmd[3]=((address & 0x0000ff00) >>8 );
	temp=sd_write_command(cmd);
	if(temp!=0)
	{											/* 读数据出错 */
		return(temp);
	}
	while(read_byte_spi()!=0xfe);				/* 等待数据开始位0xfe */
	for(i=0;i<512;i++)
	{
		*data++=read_byte_spi();
	}
	read_byte_spi();							/* CRC - Byte */
	read_byte_spi();							/* CRC - Byte */
	PORTB |= ~BIT(ss);							/* 关闭SD卡使能 */
	return(temp);
}

void write_byte_spi(uchar data)
{
	SPDR=data;
	while(!(SPSR & BIT(SPIF)));
}

uchar read_byte_spi(void)
{
	SPDR=0;
	while(!(SPSR & BIT(SPIF)));
	return(SPDR);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -