/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... produce a single edge controlled PWM signal.
 */

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

#define PERIOD	1024				// 10Bit

/*
 * The PWM5 pin (=P0.21) is used as variable PWM output.
 * View the signal with a scope or feed PWM5 into a low
 * pass filter and measure the voltage.
 *
 * MR0 defines the cycle rate (period) of the PWM signal.
 * The signal starts with high, MR5 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_pwmmr0   = PERIOD;		// set MR0 (rate)
	Intern_pwmmcr  |= 2;			// reset on MR0
	Intern_pwmpcr  |= 0x2000;		// PWM5 output
	Intern_pinsel1 |= 0x400;		//      enable
	Intern_pwmtcr   = 9;			// PWM mode, go...

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

		Intern_pwmmr5  = hpw;		// set HPW
		Intern_pwmler |= 0x20;		// activate update
		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("?");
	}
}
