#include <main.h>

extern struct qei ENC;		  // Struct to hold all encoder events
extern struct work context;	  // Struct to hold working context

void QEIinit()
{
	// Unlock PD7 for QEI modul insted of NMI
	GPIO_PORTD_LOCK_R = GPIO_LOCK_KEY;
	GPIO_PORTD_CR_R |= GPIO_PIN_7;
	GPIO_PORTD_AFSEL_R |= GPIO_PIN_7;
	GPIO_PORTD_PCTL_R  |= 0x60000000;
	GPIO_PORTD_DEN_R |= (GPIO_PIN_6+GPIO_PIN_7);
	//
	GPIO_PORTD_CR_R &= ~GPIO_PIN_7;								// Re-lock PD7

	// Configure the port pins
	SysCtlPeripheralEnable(SYSCTL_PERIPH_QEI0); 				// Enable clock for QEI modul
	SysCtlPeripheralEnable(SYSCTL_PERIPH_QEI1); 				// Enable clock for QEI modul
	//GPIOPinConfigure(GPIO_PH4_PHA0);							// Select AF for the gpios
	//GPIOPinConfigure(GPIO_PH5_PHB0);
	//GPIOPinConfigure(GPIO_PC5_PHA1);							// Select AF for the gpios
	//GPIOPinConfigure(GPIO_PC6_PHB1);
	GPIOPinTypeQEI(QEI0_PORT, QEI0_PINS);						// Select portpins as QEI0 pins
	GPIOPinTypeQEI(QEI1_PORT, QEI1_PINS);						// Select portpins as QEI1 pins


	QEIDisable(QEI0_BASE);										// Disable QEI for setings
	QEIDisable(QEI1_BASE);										// Disable QEI for setings
	QEIIntDisable(QEI0_BASE,QEI_INTERROR | QEI_INTTIMER | QEI_INTINDEX);
	QEIIntDisable(QEI1_BASE,QEI_INTERROR | QEI_INTTIMER | QEI_INTINDEX);
	// Configure quadrature encoder, top limit of 1000, invert both pins
	QEIConfigure(QEI0_BASE,(QEI_CONFIG_CAPTURE_A_B|QEI_CONFIG_NO_RESET|QEI_CONFIG_QUADRATURE|
				 QEI_CONFIG_SWAP|QEI_CONFIG_INVA|QEI_CONFIG_INVB|QEI_CTL_FILTCNT_M|QEI_CTL_FILTEN),4000);
	QEIConfigure(QEI1_BASE,(QEI_CONFIG_CAPTURE_A_B|QEI_CONFIG_NO_RESET|QEI_CONFIG_QUADRATURE|
				 QEI_CONFIG_NO_SWAP|QEI_CONFIG_INVA|QEI_CONFIG_INVB|QEI_CTL_FILTCNT_M|QEI_CTL_FILTEN),4000);
	QEIEnable(QEI0_BASE);  			 		// Enable the quadrature encoder 0.
	QEIEnable(QEI1_BASE);   				// Enable the quadrature encoder 1.
	QEIPositionSet(QEI0_BASE, 100);  		// Set position to a middle value
	QEIPositionSet(QEI1_BASE, 100);  		// Set position to a middle value
	QEIIntClear(QEI0_BASE,QEI_INTDIR);		// Clear all previews interrupts for QEI0
	QEIIntClear(QEI1_BASE,QEI_INTDIR);		// Clear all previews interrupts for QEI1
	QEIIntEnable(QEI0_BASE, QEI_INTDIR);	// Enable dir change interrupt for QEI0
	QEIIntEnable(QEI1_BASE, QEI_INTDIR);	// Enable dir change interrupt for QEI1
}

void setQEIMax(int maximum,int base)
{
	QEIDisable(QEI0_BASE);
	QEIDisable(QEI1_BASE);
	if(base) HWREG(QEI1_BASE + QEI_O_MAXPOS) = maximum;
	else	 HWREG(QEI0_BASE + QEI_O_MAXPOS) = maximum;
	QEIEnable(QEI0_BASE);
	QEIEnable(QEI1_BASE);
}
