I have been working on an application that requires reading an analog input and outputting a PWM with a duty cycle of 0-100% depending on the input. I tested the following code based on the mB PWM library:
Code: Select all
pwm1_period = Pwm_Init(3900, 1, 1, 2)
Pwm_Start(1)
l1:
v = adc_read(1)
Pwm_Set_Duty(v << 2, 1)
delay_ms(100)
goto l1
Excluding the code for the A/D and delays, the amount of ROM used was 502 for the above code. Since working with PWM's involves basically setting registers, I decided to look closely at the datasheet (PIC24FJ32GA002) and family reference manual to see if there was a more efficient method to do it. By setting the registers manually, this is the new code:
Code: Select all
' TIMER2 PERIOD FOR 3.9kHZ, PRESCALE 1:1-DEFAULT
PR2 = $FFF ' Timer2 Period for 3.9KHz
OC1RS = 0 ' Initial Duty Cycle
OC1R = 0 ' Set to 0
T2CON.15 = 1 ' Start Timer 2
OC1CON = %110 ' Start PWM
l1:
v = adc_read(1)
OC1RS = v << 2 ' Set Duty Cycle
delay_ms(100)
goto l1
Again, excluding the code for the A/D and delays, the amount of ROM required is now just 28. Almost a 95% reduction. BTW, both versions of code were tested on hardware and output verified on a scope.