/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... use TPU channel 2 to produce a PWM signal.
 */

#include <stdio.h>
#include <target.h>

#define PERIOD	1024				/* 10Bit */

/*
 * The TP2 pin is used as variable PWM output. View the signal
 * with a scope or feed TP2 into a low pass filter and measure
 * the voltage.
 *
 * PWMPER =Parameter RAM[3] defines the cycle rate (period) of
 * the PWM signal. The signal starts with high, PWMHI =RAM[2]
 * defines the duration of the high pulse (or the beginning of
 * the low pulse).
 *
 * You are prompted for the high pulse width (HPW).
 */
int
main(void)
{
	unsigned hpw = PERIOD/2;		/* initial HPW */

	INTERN.tpu.tmcr	     = 0;		/* enable TPU */
	INTERN.tpu.c[2].p[0] = 0x80;		/* TP2 output channel */
	INTERN.tpu.c[2].p[3] = PERIOD;		/*     set PWMPER (rate) */
	INTERN.tpu.cfsr3    |= 0x900;		/*     PWM function  (CFS =  9) */
	INTERN.tpu.hsrr1    |= 0x20;		/*     initialize    (HSR =%10) */
	INTERN.tpu.cpr1	    |= 0x30;		/*     high priority (CPR =%11) */

	while (1) {
		char line[10];			/* input buffer */
		unsigned new;			/* new HPW */

		INTERN.tpu.c[2].p[2] = hpw;	/* set PWMHI (hpw) */
		printf("Current HPW: %d\n"
		       "New HPW (0.. %d): ", hpw, PERIOD-1);
		fgets(line, sizeof(line), stdin);
		if (sscanf(line, "%d", &new) == 1 && new < PERIOD) hpw = new;
		else puts("?");
	}
}

