/*
	DMAPWM1.C

	This program demonstrates how to use the DMA-driven PWM.
*/

#define RUNKERNEL 1
#define _PWMDMAPort _TS_LED2
#use vdriver.lib
#use srtk.lib
#use eziopk23.lib

#define PWMLEN	16
#define PWMOVR	16

#define PWMWVLEN 64

char PWMBuffer[2][(PWMLEN+PWMOVR+1)*256];

#funcchain _srtk_hightask _eioBrdAORf

main() {
	auto char dim;
	auto char *pBufStart;
	auto int sign;
	auto bufSw;

//	_eioZ1SS = 2;
	pBufStart = dmapwmBufBeg(PWMBuffer[0]);
	bufSw = 0;
	dim = 0;
	sign = 1;
	memset(PWMBuffer,0,sizeof(PWMBuffer));

	VdInit();

	dmapwmInit((unsigned)((xmadr(pBufStart)+255)>>8),PWMLEN,PWMOVR,_TS_LED2,4);

	init_srtkernel();

	while (inport(BCR0H)) {
		costate {
			bufSw = !bufSw;
			dmapwmSetBuf(dmapwmBufBeg(PWMBuffer[bufSw])+dim,
				PWMLEN+PWMOVR,PWMWVLEN,(sign>0)?1:0);
			dmapwmSwBuf((unsigned)((xmadr(PWMBuffer[bufSw])+255)>>8));
			dmapwmSetBuf(dmapwmBufBeg(PWMBuffer[!bufSw])+dim,
				PWMLEN+PWMOVR,PWMWVLEN,(sign>0)?1:0);
			dim += sign;
			if (dim == 0) sign = 1;
			else if (dim == PWMWVLEN) sign = -1;
			waitfor(DelayMs((PWMWVLEN-dim)));
		}
	}
}