PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sun Jul 25, 2010 4:31 pm |
|
|
Here's an example program. When I turn the trimpot from 0 to +5v,
the PWM duty cycle goes from 0 to 100%.
This line calculates the duty cycle value for the set_pwm1_duty() function:
Quote: |
duty = (adc_result / 255.0) * (PR2_VALUE +1);
|
The expression shown in bold changes from 0 to 1.0, when I turn the
knob on the trimpot. In terms of a percentage, that's from 0 to 100%.
If you want to use a percentage number (1 to 100), you will need
to divide it by 100 (to get 0 to 1.0) so it would be the same range as
the expression shown in bold above.
Code: |
#include <16F877.H>
#device adc=8
#fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
#define PR2_VALUE 254
//==========================================
void main()
{
int8 adc_result;
int8 duty;
setup_adc_ports(AN0);
setup_adc(ADC_CLOCK_DIV_8);
set_adc_channel(0);
delay_us(20);
setup_ccp1(CCP_PWM);
setup_timer_2(T2_DIV_BY_1, PR2_VALUE, 1);
set_pwm1_duty(0);
while(1)
{
adc_result = read_adc();
duty = (adc_result / 255.0) * (PR2_VALUE +1);
set_pwm1_duty(duty);
}
} |
|
|