Hier mal ein Timer für 2 verschiedene PWMs (3 wären pro Timer möglich):
void PWM_init(unsigned int pwm0, unsigned int pwm1)
{
SYSAHBCLKCTRL_bit.IOCON = 1; // pins clock
// P0_8/CT16B0_MAT0
IOCON_PIO0_8_bit.FUNC = 0x2; // CT16B0_MAT0
IOCON_PIO0_8_bit.MODE = 0x0; // no pull
// P0_9/CT16B0_MAT1
IOCON_PIO0_9_bit.FUNC = 0x2; // CT16B0_MAT1
IOCON_PIO0_9_bit.MODE = 0x0; // no pull
// tick/sec->1sec, pwm0%, pwm1%
CT16B0_init(1, pwm0, pwm1);
}
void CT16B0_init(unsigned int ticks, unsigned int pwm0, unsigned int
pwm1)
{
SYSAHBCLKCTRL_bit.CT16B0 = 1; // CT16B0 clock
TMR16B0TCR_bit.CE = 0; // counting disable
TMR16B0TCR_bit.CR = 1; // timer: reset
TMR16B0TCR_bit.CR = 0; // timer: reset release
TMR16B0CTCR_bit.CTM = 0; // timer mode: rising PCLK edge
// prescale counter is used to scale match registers to 1 sec
TMR16B0PC = 0; // prescale counter:
reset
TMR16B0PR = (CLK/(SYSAHBCLKDIV))/(0xFFFF); // prescale value (timer
is 16-bit)
// timer period using MR3 (since there is no MAT3 pin)
TMR16B0MR3 = (0xFFFF)/(ticks); // MR3 (scaled to 16-bit)
TMR16B0MCR_bit.MR3R = 1; // MR3 reset enable
TMR16B0PWMC_bit.PWM3ENA = 1; // MR3 used for PWM period
// MAT0 pin duty cycle using MR0
TMR16B0MR0 = (0xFFFF)/(ticks)/(100/pwm0); // MR0 (scaled to
16-bit)
TMR16B0EMR_bit.EMC0 = 0x3; // MAT0 toggle
TMR16B0EMR_bit.EM0 = 1; // MAT0 start high
TMR16B0PWMC_bit.PWM0ENA = 1; // MR0 used for PWM duty
cycle
// MAT1 pin duty cycle using MR1
TMR16B0MR1 = (0xFFFF)/(ticks)/(100/pwm1); // MR1 (scaled to
16-bit)
TMR16B0EMR_bit.EMC1 = 0x3; // MAT1 toggle
TMR16B0EMR_bit.EM1 = 1; // MAT1 start high
TMR16B0PWMC_bit.PWM1ENA = 1; // MR1 used for PWM duty
cycle
TMR16B0TCR_bit.CE = 1; // timer start
}