View previous topic :: View next topic |
Author |
Message |
S1gnature
Joined: 28 Apr 2020 Posts: 22
|
[SOLVED] Software method for low frequency PWM |
Posted: Mon Oct 26, 2020 11:01 am |
|
|
Hi everyone,
I would like to ask for your help on this problem. I am trying to generate 50Hz PWM pulse for controlling hobby servo.
I've already tried the method stated by Ttelmah and PCM Programmer in those topics:
http://www.ccsinfo.com/forum/viewtopic.php?t=17993
http://www.ccsinfo.com/forum/viewtopic.php?t=20050
The above method used timer0. I modify the code to see if we could use timer1 as an alternative but it doesn't work as expected. My idea is to preload timer1 value 65280 so that it would count to 65536 (256 times) like timer0. However, the output pulse is fluctuated at 0 and 1Hz.
My code is as follows:
Code: | #include <16F877A.H>
#fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP
#use delay(clock = 4000000)
#define PWM_PIN PIN_B1
#define LOOPCNT 78;
int8 width;
#INT_TIMER1
void tick(void);
void main(void){
width=20;
set_timer1(65280);
setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);
enable_interrupts(GLOBAL);
enable_interrupts(INT_TIMER1);
while(TRUE);
}
#INT_TIMER1
void tick(void){
static int8 loop = LOOPCNT;
static int8 pulse = width;
if(--loop == 0)
{
loop = LOOPCNT;
pulse = width;
}
if(pulse)
{
output_high(PWM_PIN);
pulse--;
}
else
{
output_low(PWM_PIN);
}
} |
Thank you very much for your time.
Last edited by S1gnature on Tue Oct 27, 2020 7:13 am; edited 1 time in total |
|
|
gaugeguy
Joined: 05 Apr 2011 Posts: 303
|
|
Posted: Mon Oct 26, 2020 11:33 am |
|
|
set_timer1(65280) does not set a preload value. It does a one time set of the timer value. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Oct 26, 2020 11:52 am |
|
|
Add this line at the start of your #int_timer1 isr:
Code: | set_timer1(PRELOAD + get_timer1()); |
Put this line above main():
Code: | #define PRELOAD 65280 |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19538
|
|
Posted: Mon Oct 26, 2020 12:10 pm |
|
|
Look at this approach instead, which uses the CCP:
<http://www.ccsinfo.com/forum/viewtopic.php?t=50914&highlight=servo>
This gives much less resources used and more accurate timings. |
|
|
S1gnature
Joined: 28 Apr 2020 Posts: 22
|
|
Posted: Tue Oct 27, 2020 7:13 am |
|
|
Thank you all!
I have tried both methods and they worked well. |
|
|
|