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

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

#define FREQUENCY	1000			// f in Hz
#define PERIOD		(_PCLK/FREQUENCY)

/*
 * 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).
 * The ratio of the high pulse duration to the period is
 * called "duty cycle".
 *
 * You are prompted for the duty cycle in %.
 */
int
main(void)
{
	unsigned cur = 50;			// current duty cycle

	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 duty cycle

		Intern_pwmmr5  = PERIOD*cur/100;	// set PW
		Intern_pwmler |= 0x20;			// activate update
		printf("Current duty cycle : %d%%\n"
		       "    New duty cycle : ", cur);
		fgets(line, sizeof(line), stdin);
		if (sscanf(line, "%d", &new) == 1 && new <= 100) cur = new;
		else puts("?");
	}
}
