View previous topic :: View next topic |
Author |
Message |
40inD
Joined: 30 Jul 2007 Posts: 112 Location: Moscow, Russia
|
12F683 PWM does not work! |
Posted: Fri May 16, 2014 1:29 am |
|
|
Why the PWM function does not work? No output impulses - just logic 1 always:
Code: |
#include <12F683.h>
#device adc=8
#FUSES NOWDT //No Watch Dog Timer
#FUSES INTRC_IO //Internal RC Osc, no CLKOUT
#FUSES NOCPD //No EE protection
#FUSES NOPROTECT //Code not protected from reading
#FUSES NOMCLR //Master Clear pin used for I/O
#FUSES NOPUT //No Power Up Timer
#FUSES BROWNOUT //Reset when brownout detected
#FUSES NOIESO //Internal External Switch Over mode disabled
#FUSES NOFCMEN //Fail-safe clock monitor disabled
#use delay(clock=4000000)
void main()
{ int16 adcval;
int16 rawadc;
setup_oscillator(OSC_4MHZ);
setup_adc_ports(sAN3|VSS_VDD);
setup_adc(ADC_CLOCK_DIV_64);
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
setup_timer_1(T1_DISABLED);
setup_timer_2(T2_DIV_BY_1,32,1); // PWM 30.3 kHz <=== correct?
setup_ccp1(CCP_PWM);
setup_comparator(NC_NC);
setup_vref(FALSE);
set_adc_channel(3);
while (true)
{adcval=read_adc();
rawadc=adcval*132/255;
//set_pwm1_duty(adcval);
set_pwm1_duty(412); // for test - not working too
delay_ms(1);
}
} |
|
|
|
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
|
Posted: Fri May 16, 2014 5:03 am |
|
|
setup_timer_2(T2_DIV_BY_1,32,1);
32 means perod ((4/4000 000)*32=32uS) of the timer_2 overflow. So your PWM's frequency would be 1/(32*10^-6) or 31250Hz.
So the timer_2 register value is compared (each incrementation) to the period specified inside setup_timer_2, if match occurs, the pwm output goes low.
Since the PWM duty register is 10 bits long, only the 8 MSb are compared to the TMR2 register, wich means 255_TMR2 corespond to 1020_DUTY.
So try with set_pwm1_duty(64); // for test _________________ A person who never made a mistake never tried anything new. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19587
|
|
Posted: Fri May 16, 2014 10:32 am |
|
|
Not quite...
Need to use:
set_pwm1_duty(64L);
Note the 'L'.
Some more comments.
The count on the PWM, is from 0, to PR2. So is PR2+1. So the timing is actually 4000000/(4*33) Hz. 30303Hz.
The point being made is that the maximum value you can use in the period is always ((PR2+1)*4)-1 - using a long for the value.
So with 32 selected the PWM range is 0 to 131. Half scale is then 66. |
|
|
|