You are on page 1of 2

6/3/2015

openlpc.com/4e26f1/example_data/pwm.lpc17xx/main.c

#include<stdio.h>
#include<math.h>
#include<lpc17xx/lpc17xx.h>
#include<lpc17xx/openlpc.h>

intmain()
{
//initializetheLEDpinsasoutputs
//LPC_GPIO1>FIODIR=1<<18|1<<27;

printf("WelcometoLPC17xxPWMdemo\n\r");

//ensurePWMperipheralispoweredon(itispoweredonbydefault)
LPC_SC>PCONP|=1<<6;

LPC_PWM1>TCR=2;//bringPWMmoduleintoreset
LPC_PWM1>IR=0xff;//clearanypendinginterrupts

//configureP2.0forPWM1.1OPulseWidthModulator1,channel1output.

LPC_PINCON>PINSEL4=(LPC_PINCON>PINSEL4&~(0x3<<0))|(0x1<<0);

//DisablepullupsforP2.0
LPC_PINCON>PINMODE4=(LPC_PINCON>PINMODE4&~0x3)|0x2;

//Setprescalesowehavearesolutionof1us
LPC_PWM1>PR=SystemCoreClock/(4*1000000)1;

LPC_PWM1>MR0=20000;//settheperiodinus.50Hzrate
LPC_PWM1>MR1=1500;//setdutyof1.5ms
LPC_PWM1>MR2=19000;//setamatchthatoccurs1ms

//beforetheTCresets.

LPC_PWM1>LER=0x7;

//setlatchenable
register

LPC_PWM1>MCR=0x2|(1<<6);//resetonMR0,interruptonMR2
LPC_PWM1>PCR=1<<9;//enablePWM1withsingleedgeoperation
LPC_PWM1>TCR=(1<<3)|1;//enablePWMmodeandcounting

//modulatethePWMsignalona0.5Hzsinwave
//updatethedutycyclesynchronouslywiththePWMperiod

//precomputedutycyclevaluesforonefullperiod

//duty(t)=sin(2pi*Fm*t)

//duty[n]=sin(2pi*Fm*n*Ts)

//N:=numberofsamplesin1fullperiod

//n=1:N

//Fs=1/Ts:=PWMfrequency

//M:=modulationdecimationfactor(thedutycyclewill

//beupdatedeveryMperiods).Thiseffectivelysetstheresolution

//ofthemodulatingwave

constdoubleFs=50.0;//PWMfrequencyis50Hz

constdoubleFm=0.5;//frequencyofmodulatingwaveis0.5Hz

constintM=1;//updatedutyeverycycle

constintN=Fs/(Fm*M);//howmanypwmcyclesfitintooneperiod
//ofthemodulatingwave,takinginto

//accountthesubsamplingrate?

//thisarraywillcontainonefullperiodofdutycyclevalues
intduty[N];

printf("Computingdutycyclevalues:\n\r");
for(intn=0;n<N;n++){
duty[n]=1500+(int)(500.0*sin(2.0*M_PI*Fm/Fs*n));

printf("duty[%d]=%d\n\r",n,duty[n]);
}

http://openlpc.com/4e26f1/example_data/pwm.lpc17xx/main.c

1/2

6/3/2015

openlpc.com/4e26f1/example_data/pwm.lpc17xx/main.c

printf("Donecomputingdutycyclevalues.\n\r");

intn=0;
while(1){

//waitforMR2interruptflagtoberaised

while((LPC_PWM1>IR&(1<<2))==0);

LPC_PWM1>IR=0xff;//clearinterruptflags

//writedutycyclevalueandsetLatchenableregister
LPC_PWM1>MR1=duty[n];
LPC_PWM1>LER=1<<1;

//incrementnandwrapifnecessary
n++;
if(n>=N)

n=0;

return0;
}

http://openlpc.com/4e26f1/example_data/pwm.lpc17xx/main.c

2/2

You might also like