Content originally posted in LPCWare by nsmith17044 on Wed Oct 15 07:10:47 MST 2014
Don't you love the 'community' atmosphere? This probably should be an LPCOpen questions but anywhere. In my project the system freq is 48MHz using the internal RC. For any many things the LPCOpen library does, it hasn't proven very useful in my applications. Most of the time I spend writing my own driver functions as the LPCOpen function interface doesn't seemed to have been designed for real applications, simply demonstrations of basic use of each peripheral.
The trick on the PWM is the stop and clear on match settings and the PWM mode setting.
// To have the timer tick run at 100,000 Hz, the prescaler is SYSTEM CLOCK / 100,000
#defineTMR16_PWM_FREQ_RESHZ(100000)//Divider to system clock to get PWM prescale value
#defineTMR16_PWM_PRESCALER((unsigned long)SYSTEM_FREQUENCY / (unsigned long)TMR16_PWM_FREQ_RESHZ )
#defineTMR16_PWM_PERIOD_HZ(1000)
#defineTMR16_PWM_PERIOD_COUNT(TMR16_PWM_FREQ_RESHZ / TMR16_PWM_PERIOD_HZ)
#define TMR16_PWM_DC_COUNT(a)( (((101-a) * TMR16_PWM_PERIOD_COUNT) / 100) )
//-------------------------------------------
// CT16B1 Setup as PWM for dimmer control. It is not enabled here as
// the Light output PWM code will control operation and duty cycle.
Chip_TIMER_Init( LPC_TIMER16_1 );//turn the power on, allow clocking
Chip_TIMER_Reset( LPC_TIMER16_1 );
//set the resolution of the ticks to the PWM timer (match register resolution)
Chip_TIMER_PrescaleSet( LPC_TIMER16_1 , (TMR16_PWM_PRESCALER-1) );
//Set duty cycle - MR0 default
Chip_TIMER_SetMatch( LPC_TIMER16_1 , 0 , TMR16_PWM_DC_COUNT(0) );
//MR0 should not stop or clear the timer
Chip_TIMER_ResetOnMatchDisable( LPC_TIMER16_1 , 0);
Chip_TIMER_StopOnMatchDisable( LPC_TIMER16_1 , 0);
//Set external match to connect MAT0 pin and set state to toggle on match
((LPC_TIMER_T *)LPC_TIMER16_1)->EMR = (((LPC_TIMER_T *)LPC_TIMER16_1)->EMR & ~0xFFFFF031) | 0x00000031;
//Set period - MR1
Chip_TIMER_SetMatch( LPC_TIMER16_1 , 1 , TMR16_PWM_PERIOD_COUNT );
//MR1 should reset the timer to restart the cycle
Chip_TIMER_ResetOnMatchEnable( LPC_TIMER16_1 , 1);
((LPC_TIMER_T *)LPC_TIMER16_1)->PWMC = 1;// PWM mode enabled on CT16B1_MAT0
Chip_TIMER_Enable( LPC_TIMER16_1 );
To set the % duty cycle...
void TIMER_PWMUpdate( unsigned char ucPercent )
{
//set match register that control duty cycle
Chip_TIMER_SetMatch( LPC_TIMER16_1 , 0 , TMR16_PWM_DC_COUNT(ucPercent) );
}
Hope that helps.
Nathan