#include <p24FJ128GA006.h>
#include "pmp.h"
#include "types.h"

void InitPMP(void)
{

	// PARALLEL PORT CONTROL REGISTER
	PMCONbits.PMPEN = 0;		// PMP Disable
	PMCONbits.ADRMUX1 = 0;	//Non-multiplex
	PMCONbits.ADRMUX0 = 0;
	PMCONbits.PTBEEN = 0;
	PMCONbits.PTWREN = 1;
	PMCONbits.PTRDEN = 1;
	PMCONbits.CSF1 = 0;		// CS 2, 1 -> address 14, 15
	PMCONbits.CSF0 = 0;
	PMCONbits.WRSP = 0;		// nWR
	PMCONbits.RDSP = 0;		// nRD

	// PARALLEL PORT MODE REGISTER
	PMMODEbits.IRQM1 = 0;	// no interrupt
	PMMODEbits.IRQM0 = 0;
	PMMODEbits.INCM1 = 0;	// no increment
	PMMODEbits.INCM0 = 0;
	PMMODEbits.MODE16 = 0;	// 8bit mode
	PMMODEbits.MODE1 = 1;		// master mode 2
	PMMODEbits.MODE0 = 0;		// master mode 2
	PMMODEbits.WAITB1 = 0;
	PMMODEbits.WAITB0 = 0;
	PMMODEbits.WAITM3 = 0;
	PMMODEbits.WAITM2 = 0;
	PMMODEbits.WAITM1 = 1;
	PMMODEbits.WAITM0 = 0;
	PMMODEbits.WAITE1 = 0;
	PMMODEbits.WAITE0 = 0;


	//PARALLEL PORT ENABLE REGISTER
#if (__C30_VERSION__ >= 300)
	PMAEN = 0xFFFF;		//PMA15 ~ PMA0 all enable
#else
	PMPEN = 0xFFFF;		//PMA15 ~ PMA0 all enable
#endif

	PMCONbits.PMPEN = 1;		// PMP Enable
	
}

inline uint8 ReadPMP(uint16 Add) 
{
	uint16	temp;

	PMADDR = Add;
	temp = PMDIN1;
	while(PMMODEbits.BUSY);
	temp = PMDIN1;
	return temp;
}

inline uint8 ReadPMP2(uint16 Add) 
{
	uint16	temp;

	PMADDR = Add;
	while(PMMODEbits.BUSY);
	temp = PMDIN1;
	return temp;
}

inline void WritePMP(uint16 Add, uint8 Dat)
{
	PMADDR = Add;
	PMDIN1 = (uint16)Dat;
}

void FastPMP(void)	// External SRAM, W3150
{
	PMMODEbits.WAITB1 = 0;
	PMMODEbits.WAITB0 = 0;
	PMMODEbits.WAITM3 = 0;
	PMMODEbits.WAITM2 = 0;
	PMMODEbits.WAITM1 = 1;
	PMMODEbits.WAITM0 = 0;
	PMMODEbits.WAITE1 = 0;
	PMMODEbits.WAITE0 = 0;
}

void SlowPMP(void)	// For LCD
{
	PMMODEbits.WAITB1 = 0;
	PMMODEbits.WAITB0 = 1;
	PMMODEbits.WAITM3 = 0;
	PMMODEbits.WAITM2 = 1;
	PMMODEbits.WAITM1 = 0;
	PMMODEbits.WAITM0 = 0;
	PMMODEbits.WAITE1 = 0;
	PMMODEbits.WAITE0 = 1;
}
