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

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

#define PERIOD	1024				// 10Bit

/*
 * The PWM0 pins (=P3.0/1) are used as variable PWM outputs
 * (PWM0H/L are the same signal but with reversed polarity).
 * View the signals with a scope or feed PWM0H/L into a low
 * pass filter and measure the voltage.
 *
 * Only the first half cycle of the PWM signal is specified
 * by the PWM parameters. The output is a symmetrical pulse,
 * composed of two mirrored half cycles.
 *
 * PWMDAT0 defines the cycle rate (period) for the two half
 * cycles (i.e., the period of the PWM signal is twice this
 * value). The PWMCHx register holds the duty cycle for the
 * channel, in the range -PWMDAT0/2 to +PWMDAT0/2.
 *
 * You are prompted for the high pulse width (HPW).
 */
int
main(void)
{
	unsigned hpw = PERIOD/2;		// initial HPW

	Intern_pwmdat0 = PERIOD;		// set period (rate)
	Intern_pwmcon  = 1;			// enable PWM
	Intern_gp3con |= 0x11;			//        PWM0 pins

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

		Intern_pwmch0 = hpw-PERIOD/2;	// set 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("?");
	}
}
