/*
	BL17PWM1.C
	
	BL1700
		
	This program demonstrates how to use the DMA-driven PWM by directing
	pulse widths to the on-board LED.

	Instructions:
	Install jumper on J8, pins 4-6.
	Compile and run this program.
*/

#define RUNKERNEL 1
#define _PWMDMAPort _LED1
#use vdriver.lib
#use srtk.lib
#use eziobl17.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;

	//setup buffer for on/off information
	pBufStart = dmapwmBufBeg(PWMBuffer[0]);
	bufSw = 0;
	dim = 0;
	sign = 1;
	memset((char *)PWMBuffer,0,sizeof(PWMBuffer));
	VdInit();
	//initialize for DMA transfer
	dmapwmInit((unsigned)((xmadr(pBufStart)+255)>>8),PWMLEN,PWMOVR,_PWMDMAPort,4);
	init_srtkernel();
	while (inport(BCR0H)) {
		costate {
			bufSw = !bufSw;
			//setup starting point
			dmapwmSetBuf(dmapwmBufBeg(PWMBuffer[bufSw])+dim,
				PWMLEN+PWMOVR,PWMWVLEN,(sign>0)?1:0);
			//swap buffers
			dmapwmSwBuf((unsigned)((xmadr(PWMBuffer[bufSw])+255)>>8));
			dmapwmSetBuf(dmapwmBufBeg(PWMBuffer[!bufSw])+dim,
				PWMLEN+PWMOVR,PWMWVLEN,(sign>0)?1:0);
			//continually modifies pulse width
			dim += sign;
			if (dim == 0) sign = 1;
			else if (dim == PWMWVLEN) sign = -1;
			waitfor(DelayMs((PWMWVLEN-dim)));
		}
	}
}