kbruin79
Joined: 02 Aug 2010 Posts: 30
|
Hardware PWM on Pic16f727 |
Posted: Wed Jul 20, 2011 11:53 pm |
|
|
Hello,
I am trying to setup a Harware PWM on Pic16f727. So I followed the steps listed on page 143 of the datasheet for setting up the PWM output on PortC pin2 and I couldn't get the port to output anything. Here is the code any help is highly appreciated:
Code: |
#include <16F727.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
//#fuses INTRC_IO,NOWDT,NOPROTECT,NOMCLR,VCAP_A6
//#use delay (internal=4000000) //(clock=4M)
#fuses INTRC_IO, NOWDT, NOPROTECT, NOMCLR
#use delay(clock = 4000000)
#include <flex_lcd.c>
#use fast_io (A)
// setting up PWM parameters
#byte PR2=0x92
#byte T2CON=0x12
#byte CCP1CON=0x17
#bit CCP1CON_4=CCP1CON.4
#bit CCP1CON_5=CCP1CON.5
#byte CCPR1L=0x15
#byte PIR1=0x0C
#bit PIR1_1=PIR1.1
//interrupt variables
#byte TMR0=1
#bit TMR0_0=TMR0.0
#bit TMR0_1=TMR0.1
int16 duty=0;
#bit duty_0=duty.0
#bit duty_1=duty.1
void main()
{
//Disable the PWM pin (CCPx) output driver(s) by
//setting the associated TRIS bit(s).
TRISIOC_2=1;
//Load the PR2 register with the PWM period value.
PR2=249; // 1 khz
//Configure the CCP module for the PWM mode
//by loading the CCPxCON register with the
//appropriate values.
CCP1CON=0b00001100; // Set CCP1 PWM active high
//Load the CCPRxL register and the DCxBx bits of
//the CCPxCON register, with the PWM duty cycle
//value.
duty = 0; // set duty cycle to 0
CCP1CON_4 = duty_0; // Store duty to registers as
CCP1CON_5 = duty_1; // a 10-bit word
//store the eight MSbs in CCPR1L.
CCPR1L = duty >> 2; // store the remaining low byte
//clear the TMR21F interrupt flag bit of PIR1 register
PIR1_1=0;
//Configure the T2CKPS bits of the T2CON
//register with the Timer2 prescale value.
//and
//Enable Timer2 by setting the TMR2ON bit of
//the T2CON register.
/*
T2CON: TIMER2 CONTROL REGISTER
TMR2ON: Timer2 On
1 = Timer2 is on
0 = Timer2 is off
T2CKPS<1:0>: Timer2
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16
*/
T2CON=0b00000111;
//Wait until Timer2 overflows, TMR2IF bit of the
//PIR1 register is set.
wait_for_TMR2IF:
if (PIR1_1 == 0)
{
goto wait_for_TMR2IF;
}
//enable PWM by setting pin to output
TRISIOC_2=0;
//make portA pin 7 an output
TRISIOA_7=0;
while(1)
{
pwm(1000);
}
}
void pwm(int16 a2d)
{
CCP1CON_4 = duty_0; // Store duty to registers as
CCP1CON_5 = duty_1; // a 10-bit word
CCPR1L = duty >> 2; // store the remaining low byte}
//GIE re-enable the global interrupts
//INTCON_7=1;
}
|
|
|