//***********************************************************
// **** MAIN routine FOR Interfacing microSD/SDHC CARD ****
//***********************************************************
//Controller: ATmega32 (Clock: 8 Mhz-internal)
//Compiler	: AVR-GCC (winAVR with AVRStudio)
//Version 	: 2.3
//Author	: CC Dharmani, Chennai (India)
//			  www.dharmanitech.com
//Date		: 08 May 2010
//***********************************************************

//Link to the Post: http://www.dharmanitech.com/2009/01/sd-card-interfacing-with-atmega8-fat32.html

#define F_CPU 16000000UL		//freq 8 MHz
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "SPI_routines.h"
#include "SD_routines.h"
#include "FAT32.h"


unsigned char loadfile(unsigned char *fileName)
{
struct dir_Structure *dir;
unsigned long cluster, byteCounter = 0, fileSize, firstSector, pos=0;
unsigned int k;
unsigned char j, error, sx=0, sy=0, x=0,y=0, cmp=0, cnt=0, tt=0, p;
error = convertFileName (fileName); //convert fileName into FAT format
if(error) return 2;
dir = findFiles (fileName); //get the file location
if(dir == 0) return (8);
cluster = (((unsigned long) dir->firstClusterHI) << 16) | dir->firstClusterLO;
fileSize = dir->fileSize;
tt=0;
while(1)
{
  firstSector = getFirstSector (cluster);
  for(j=0; j<sectorPerCluster; j++)
  {
    SD_readSingleBlock(firstSector + j);
	for(k=0; k<512; k++)
    {
     if ((byteCounter++) >= fileSize ) return 0;
	 pos++;
    }
  }
  cluster = getSetNextCluster (cluster, GET, 0);
}
return 0;
}


unsigned char card_init(void)
{
unsigned char error;
unsigned int i;
// настройка портов
PORTB = 0xFF;
DDRB  = 0xBF; //MISO line i/p, rest o/p
// настройка SPI init
SPCR = (1<<MSTR)|(1<<SPE); // SPI config
SPSR=(1<<SPI2X); // double speed
// попытка инициализировать карту
cardType = 0;
for (i=0; i<10; i++) {error = SD_init();if(!error) break;}
if(error) return 1;
_delay_ms(1);   //some delay
error = getBootSectorData (); //read boot sector and keep necessary data in global variables
if(error) return 1;
return 0;
}





//*************************** MAIN *******************************//
int main(void)
{
 char fn[]="filename";
 card_init();
 loadfile(fn);
}
//********** END *********** www.dharmanitech.com *************
