Tonight I was wondering why my PWM wasn’t working. It took me a while to figure it out, but I have it working.
Start with your C file with your normal #include and #fuses. Inside your main function you’ll use 4 built in functions and the super loop While statement. That is it! I wired a high brightness LED to pin 5 of the PIC16F690 on the Pickit 2.
setup_timer_2(t2_div_by_16,0xff,16); The timing works like this. 1/clock frequency gives you your period (4/4000000=1us) . Then, I have a pre-scale of 16 (.000001*16=16us) Then I have a post-scale of 16 (.000016*16=256us). The period is 0xff or 255. This is how many times the timer can loop before an overflow (.000256*255=65.28ms or 65,280us). 1/.06528=15.32Hz. This is the slowest we can make this timer.
set_pwm1_duty(512); The duty is the ratio of high to low. A duty of 1 is about 1% high and 99% low. This makes an LED very dim. 512 is 50% high and 50% low. It’s the equivalent of this:
output_high(LED); delay_ms(8); output_low(LED); delay_ms(8); //loop this forever
A duty cycle of 1023 is 1% high and 99% low. The LED is very bright!
set_timer_2(0); This is to start the timer, and where to start it.
As you can see, there’s a lot of math thinking to PWM. The timers can be fun, and in the next installment I’ll demonstrate how to use them to count seconds and make a somewhat accurate timekeeper (yep, without my favorite DS1305 chip).
#include <16f690.h>
#fuses intrc_io, nowdt, nobrownout, put
void main(void)
{
setup_ccp1(ccp_pwm); //this turns the pwm on
setup_timer_2(t2_div_by_16,0xff,16); // see above for help on this
set_timer2(0); //start the counter at zero
set_pwm1_duty(512); //50% duty cycle (hi) equal on/off time
while (1); //stay in this loop until reset – PWM runs all by itself with no help
}