View previous topic :: View next topic |
Author |
Message |
Stuffed-Bit
Joined: 07 Jul 2006 Posts: 9 Location: US
|
What is the proper way to turn PWM pin on and off? |
Posted: Tue Mar 13, 2007 8:11 am |
|
|
Chip = 16F877A
Compiler = 3.155
Say I want to beep out some Morse code using the PWM pin C2. I set the PWM to 50% at 1KHz. Now what is the proper way to toggle the PWM on and off?
I "thought" I used to simply set pin_c2 high or low but that don't seem to work. Now I'm sending a setup_ccp1(CCP_PWM) to turn it on and a setup_ccp1(CCP_OFF) to turn it off. Is this the best way to do this or is there some thing better. I guess I could set the duty to all or none but then I have to remember where to go back to. What is you thoughts? |
|
|
treitmey
Joined: 23 Jan 2004 Posts: 1094 Location: Appleton,WI USA
|
|
Posted: Tue Mar 13, 2007 8:14 am |
|
|
That is the correct way. |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1909
|
|
Posted: Tue Mar 13, 2007 11:30 am |
|
|
You could leave the PWM on but switch the PIC's pin from being an output to an input and vice versa to toggle the PWM on/off. Just set/clear the appropriate bit in the PIC's TRIS register. I use this approach to burst/silence an IR LED to send command codes to A/V equipment with great success. |
|
|
Stuffed-Bit
Joined: 07 Jul 2006 Posts: 9 Location: US
|
|
Posted: Tue Mar 13, 2007 9:18 pm |
|
|
Version 1 uses a few less commands than version 2 and produces the same results. Any reason not to use version 1 as long as the pin is pulled high or low and not left floating?
Also, is there a easier/quicker way to toggle tris for just pin_c2 with the set_tris_c(x) command without affecting other pins on port C? Or in other words is there a way to set a single bit using the set_tris_c(x) command?
Code: |
//Version 1
output_high(pin_c2); //enable PWM
delay_ms(duration); //wait
output_float(pin_c2); //disable PWM
|
Code: |
//Version 2
setup_ccp1(CCP_PWM); //enable PWM
delay_ms(duration); //wait
setup_ccp1(CCP_off); //disable PWM
|
|
|
|
newguy
Joined: 24 Jun 2004 Posts: 1909
|
|
Posted: Tue Mar 13, 2007 11:24 pm |
|
|
Code: | #bit pwm_out_enable = 0xf94.2 |
[Of course, check your PIC's data sheet to ensure you're correctly mapping this bit.]
To enable PWM:
Code: | pwm_out_enable = 1; |
To disable it:
Code: | pwm_out_enable = 0; |
Also be sure to use the fast_io directive with the port you're using (probably port c):
|
|
|
Charlie U
Joined: 09 Sep 2003 Posts: 183 Location: Somewhere under water in the Great Lakes
|
|
Posted: Wed Mar 14, 2007 6:28 am |
|
|
Another way would be to change the duty cycle to 0%. This way, a pulse in progress would not be cut short. The PWM will continue to run, but with 0 on time. Then to start it up again, just set the duty cycle to 50%.
Charlie |
|
|
|