#include "F28x_Project.h"
#include "cla_shared.h"


inline void toggle_LED1(void){
	GpioDataRegs.GPATOGGLE.bit.GPIO31 = 1;
}

inline void toggle_LED2(void){
	GpioDataRegs.GPBTOGGLE.bit.GPIO34 = 1;
}

__interrupt void cla_Task8finished(void){
	toggle_LED1();

	PieCtrlRegs.PIEACK.all = PIEACK_GROUP11; // CLA finished
}

/*__interrupt void int_500ms_task(void){
	toggle_LED1();
	Cla1ForceTask8andWait();

	PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; // ist das nötig??
}*/

int main(void) {
	InitSysCtrl();
	InitCLAvars();

	//-------------- GPIO ---------------------------
	GPIO_SetupPinOptions(31, GPIO_OUTPUT, GPIO_PUSHPULL);
	GPIO_SetupPinMux(31, GPIO_MUX_CPU1, 0);
	GPIO_SetupPinOptions(34, GPIO_OUTPUT, GPIO_PUSHPULL);
	GPIO_SetupPinMux(34, GPIO_MUX_CPU1, 0);
	GPIO_SetupPinOptions(40, GPIO_OUTPUT, GPIO_PUSHPULL);
	GPIO_SetupPinMux(40, GPIO_MUX_CPU1, 0);
	EALLOW;
	GpioCtrlRegs.GPADIR.bit.GPIO31 = 1;
	GpioCtrlRegs.GPBDIR.bit.GPIO34 = 1;
	//GpioCtrlRegs.GPBCSEL1.bit.GPIO34 = 1; //CPU1.CLA
	//GpioCtrlRegs.GPBCSEL2.bit.GPIO40 = 1; //CPU1.CLA
	EDIS;
	//-------------- GPIO ---------------------------
	
	//---------------- Timers --------------
	InitCpuTimers();
	ConfigCpuTimer(&CpuTimer0, 200, 500000); //200 Mhz, 500ms Zeit

	//---------------- Interrupts--------------
	// CPU Level
	DINT; // CPU Interrupts disabled
	IER=0x0000;
	IFR=0x0000;
	IER|=M_INT11; //CLA fertig

	// PIE Level
	InitPieCtrl();
	InitPieVectTable(); // setz auch ENPIE=1
	EALLOW;
	//PieCtrlRegs.PIEIER1.bit.INTx7=1; // Timer0 IRQ
	//PieVectTable.TIMER0_INT = &int_500ms_task; //WORK
	//PieVectTable.TIMER1_INT = &int_100ms_task;
	EDIS;

	in = 2.0;
	//---------- CLA
	// Initialize and wait for CLA1ToCPUMsgRAM
	EALLOW;
	MemCfgRegs.MSGxINIT.bit.INIT_CLA1TOCPU = 1;
	while(MemCfgRegs.MSGxINITDONE.bit.INITDONE_CLA1TOCPU != 1){};
	MemCfgRegs.LSxMSEL.bit.MSEL_LS0 = 1;
	MemCfgRegs.LSxCLAPGM.bit.CLAPGM_LS0 = 0; //Datenspeicher
	MemCfgRegs.LSxMSEL.bit.MSEL_LS5 = 1;    //LS5RAM is shared between CPU and CLA
	MemCfgRegs.LSxCLAPGM.bit.CLAPGM_LS5 = 1;    //LS5RAM laut Linkerfile als Programmspeicher definiert

	//DmaClaSrcSelRegs.CLA1TASKSRCSEL2.bit.TASK8 = CLA_TRIG_NOPERPH; //für manuellen Aufruf von CLA tasks
	DmaClaSrcSelRegs.CLA1TASKSRCSEL2.bit.TASK8 = CLA_TRIG_TINT0; //Timer0 Interrupt auf VERCT8
	Cla1Regs.MVECT8 = (uint16_t)(&cla_Task8); //VECT8 ruft cla_Task8 auf
	PieVectTable.CLA1_8_INT = &cla_Task8finished;
	PieCtrlRegs.PIEIER11.all = 0xFFFF; // finished CLA may trigger "CLA finished interrupt"
	Cla1Regs.MIER.all 	= 0x00FF; //all CLAs may be started
	Cla1Regs.MCTL.bit.IACKE = 1; //CLAs may be triggered manually
	EDIS;

	EINT; // CPU Interrupts enabled
	ERTM;

	CpuTimer0Regs.TCR.all = 0x4000; // Timer starten, IRQ enabled, TSS=0 (==timer starten)
	while(1){
		GPIO_WritePin(34, LEDstate); //LED2
		asm(" NOP");
	}

}
