View previous topic :: View next topic |
Author |
Message |
mike1234
Joined: 06 Dec 2007 Posts: 6 Location: Chicago, IL
|
variable timer2 / PWM frequency? |
Posted: Thu Jan 24, 2008 11:11 am |
|
|
I have a PIC 18F4520. I am looking to output a PWM signal whose frequency varies (which will be read by a data acquisition card and used in DasyLab).
Is this possible? Can you set the timer2 frequency (which drives the PWM output) multiple times in a single program? I tried it and it didn't work, but maybe I'm missing something. Any ideas?
So far, this DOES NOT work:
Code: | void main()
{
setup_ccp1(CCP_PWM);
while(1){
setup_timer_2(T2_DIV_BY_1, prescale, 1);
//etc... |
This DOES work:
Code: | void main()
{
setup_ccp1(CCP_PWM);
setup_timer_2(T2_DIV_BY_1, prescale, 1);
while(1){
//etc... |
Thanks,
Mike |
|
|
RLScott
Joined: 10 Jul 2007 Posts: 465
|
Re: variable timer2 / PWM frequency? |
Posted: Thu Jan 24, 2008 1:44 pm |
|
|
The setup_timer_2() function probably clears Timer 2 as well. If this is done repeatedly, then Timer 2 is not allowed to count through its entire cycle, and of course the PWM would be affected.
There is justification for clearing Timer 2 when setting a divide-by ratio. If the divide-by is ever set to a smaller number, then it is possible that the Timer value was already past that point. In that case the Timer will not cycle to zero until it has counted all the way to its maximum value and wrapped around to zero. This could result in an anomalously-long PWM pulse being generated. By clearing Timer 2 you are assured that the next PWM pulse will be of a reasonable length.
Robert Scott
Real-Time Specialties |
|
|
mike1234
Joined: 06 Dec 2007 Posts: 6 Location: Chicago, IL
|
|
Posted: Thu Jan 24, 2008 2:07 pm |
|
|
So are you saying my current setup should work but with irregular pulses each time I switch frequencies? Or do I need to change anything? |
|
|
mike1234
Joined: 06 Dec 2007 Posts: 6 Location: Chicago, IL
|
|
Posted: Thu Jan 24, 2008 2:21 pm |
|
|
To clarify, "prescale" is a variable that I want to change each time the loop executes, changing the frequency of timer2.
At this point, I am guessing it has to be a constant since it's not working.
Is there any way around it?
Is there some way to do frequency output besides PWM? |
|
|
mike1234
Joined: 06 Dec 2007 Posts: 6 Location: Chicago, IL
|
|
Posted: Thu Jan 24, 2008 3:48 pm |
|
|
I also now realize that the variable I named "prescale" is really modulating the PR2 parameter. I'm renaming it "PR2" so its not misleading. Sorry. |
|
|
|