/* MTP EEPROM routines */
/* Designed by Paolo Subiaco http://www.creasol.it */

#include "main.h"
#include "mtp_eeprom.h"

#pragma rambank0
void mtp_rtx(uchar type, uchar address, uchar *dataptr, uchar size) {
	uchar i;
	uchar data;
	uint value;
	_bp=1;
	_mp1=0x40;
	mtpee_cs=1;
	_nop();
#ifdef DEBUG_MTPEE
	if (mtpee_do) mtpee_dopin=1; else mtpee_dopin=0;
#endif
	// TX start bit, opcode and 7/9 bit (address)
#if MTP_EEPROM_LENGTH == 256
	value=(uint)type<<7;
	value|=address;
	value<<=4;
	for (i=12;i;i--) {
#else
	value=(uint)type<<5;
	value|=address
	value<<=4;
	for (i=10;i;i--) {
#endif
		_lrlc(&value);
		if (_c) 
			mtpee_di=1;
		else
			mtpee_di=0;
		_nop(); mtpee_sk=1; _nop(); mtpee_sk=0;
	}
	
	if (type==MTP_CMD_READ) {
		// read size bytes
		for (; size; size--) {	// j=number of bytes
			data=0;
			for (i=8;i;i--) {	// i=number of bit
				mtpee_sk=1; _nop(); mtpee_sk=0; _nop(); 
				_rl(&data);
				if (mtpee_do) {
					data|=1;
#ifdef DEBUG_MTPEE
					mtpee_dopin=1;
				} else {
					mtpee_dopin=0;
#endif
				}
			}
			*dataptr=data;

			dataptr++;
			_bp=1;
			_mp1=0x40;
		}
	} else if (type==MTP_CMD_WRITE || type==MTP_CMD_WRAL) {
		// Write or WriteAll 1 byte
		//data=*dataptr;
#asm
		mov a,mtp_rtx2
		mov __mp0,a
		mov a,__iar0
		mov CR2,a		; data local variable
#endasm	
		_bp=1;
		_mp1=0x40;
		for (i=8;i;i--) {
			if (data&0x80) mtpee_di=1; else mtpee_di=0;
			_rl(&data);
			mtpee_sk=1; _nop(); mtpee_sk=0;
		}
	} else {
		// Erase a byte, or erase all, or enable/disable write
		// do nothing else
	}
	mtpee_di=0;
	mtpee_cs=0;
}

void mtp_eepromWrite(uchar address, void *ptr, uchar size) {
	uchar *chptr=(uchar*)ptr;
	uint delay;
	// enable write
	mtp_rtx(MTP_CMD_EWEN,0,0,0);
	while (size) {
		_clrwdt2();
mtp_eepromWritel:
		//outDebugC=0;//DEBUG
		//outDebug=0;	//DEBUG
		mtp_rtx(MTP_CMD_WRITE,address,chptr,0);
		//outDebug=1;	//DEBUG
		// wait at least 2ms (5V) or 5mS (2.2V)
		//for (delay=CPUCLOCK/6;delay;delay--); // wait for 5.8ms
		for (delay=CPUCLOCK/6;delay;delay--) {
			// test DO line
			_bp=1;
			_mp1=0x40;
			mtpee_cs=1;
			_nop();
			if (mtpee_do==1) break;
			mtpee_cs=0;
		}
		mtpee_cs=0;
		if (delay==0) {
			// Error while writing data => eeprom busy
			goto mtp_eepromWritel;
		}
		chptr++;
		address++;
		size--;
	}
	// disable writing
	mtp_rtx(MTP_CMD_EWDS,0,0,0);
}

/* NOT NEEDED!
void mtp_eepromRead(uchar address, void *ptr, uchar size) {
	uchar *chptr=(uchar*)ptr;
	mtp_rtx(MTP_CMD_READ|(size<<2),address,chptr);
}
*/

