#include <m8c.h>        // part specific constants and macros
#include "PSoCAPI.h"    // PSoC API definitions for all User Modules
#include "psocdynamic.h"


#include "main.h"
#include "mmc_driver.h"



unsigned char MMC_CMD(unsigned char CMD,unsigned long ADDR,unsigned char MMC_CRC){
	unsigned char USERBUF;
	SPI_SEND(0xff);
	SPI_SEND(0x40 + CMD);						
	SPI_SEND((ADDR >> 24) & 0xff);
	SPI_SEND((ADDR >> 16) & 0xff);
	SPI_SEND((ADDR >> 8) & 0xfe);
	SPI_SEND(/*ADDR  & */0x00);
	SPI_SEND(MMC_CRC & 0xFF);		
	//----------------------------
	//	wait R1 resp
	//----------------------------
	for(;;){
		USERBUF	=	SPI_SEND(0xff);
		if(!(USERBUF & 0x80))break;	
	}//timed out
	return(USERBUF);
}

void MMC_INIT(void)
{
	unsigned char LP1;
	
	SPIM_1_Start(SPIM_1_SPIM_MODE_0 | SPIM_1_SPIM_MSB_FIRST);
	// ----------- SD memory Card initialize ------------
	// 74 or more cycle dummy clock sending
	// --------------------------------------------------
	MMC_xCS = 1;	// CS = High
	
	for(LP1=100;LP1!=0;LP1--)SPI_SEND(0xff);
	// -------- dummy clock send was over ---------------
	
	// ------- Send CMD0 to MMC or SD memory Card -------
	MMC_xCS = 0;			// CS = Low
	MMC_CMD(0,0,0x95);		//CMD0,CRC=0x95
	
	
	// -------- Send ACMD41 to SD memory Card -------
	// -------- 	ACMD41 = CMD55 + CMD41	  -------
	do{
		MMC_CMD(55,0,0xFF);				//CMD55,CRC=0xFFh
	}while(MMC_CMD(41,0,0x01) != 0x00);	//CMD41,CRC=0x01h 
	// --------		ACMD41 send was End			-------
	// ------------------------------------------------
	
	
	while(!SPI_SEND(0xff));				//wait busy
	while(!SPI_SEND(0xff));				//wait busy
	MMC_CMD(16,512,0x01);				//SET_BLOCKLEN = 512 byte
	
}

void MMC_SEND_STOP(void){
	unsigned char LP1;
	
 
	MMC_xCS = 0;						// CS = Low	
	for(LP1=100;LP1!=0;LP1--)SPI_SEND(0xff);
	MMC_CMD(12,0,0x01);					//CMD12
	while(!SPI_SEND(0xff));				//wait busy
	while(!SPI_SEND(0xff));				//wait busy
	for(LP1=100;LP1!=0;LP1--)SPI_SEND(0xff);
}
