I am trying to create a crude DAC by using PWM on the PIC18F47J53.
The datasheet says the following:
The PWM duty cycle is specified by writing to the
CCPR4L register and to the CCP4CON<5:4> bits. Up
to 10-bit resolution is available. The CCPR4L contains
the eight MSbs and the CCP4CON<5:4> contains the
two LSbs. This 10-bit value is represented by
CCPR4L:CCP4CON<5:4>. The following equation is
used to calculate the PWM duty cycle in time:
But then goes on to say:
PWM Duty Cycle = (CCPR4L:CCP4CON<5:4>) •
TOSC • (TMR2 Prescale Value)
I am really confused at how to generate say 10%, 20, % 30%, 40%, 50% etc etc duty cycle.
Do I also need to manipulate the prescaler?
Currently all I am doing is to manipulate CCPR4L and CCP4CONbits.DC4B to change my duty cycle.
Below is my code.. I am using Timer4. Changing the period on Timer 2 seems to be affect the baudrate of my EUSART for some reason but the datasheet does not seem to mention T2 is used for baudrate and least not from what I am understanding.
I am getting PWM out but I can't seem to make sense of how to control my duty cycle.
My chip is currently running ant 8MHZ on the internal oscillator.
The datasheet says the following:
The PWM duty cycle is specified by writing to the
CCPR4L register and to the CCP4CON<5:4> bits. Up
to 10-bit resolution is available. The CCPR4L contains
the eight MSbs and the CCP4CON<5:4> contains the
two LSbs. This 10-bit value is represented by
CCPR4L:CCP4CON<5:4>. The following equation is
used to calculate the PWM duty cycle in time:
But then goes on to say:
PWM Duty Cycle = (CCPR4L:CCP4CON<5:4>) •
TOSC • (TMR2 Prescale Value)
I am really confused at how to generate say 10%, 20, % 30%, 40%, 50% etc etc duty cycle.
Do I also need to manipulate the prescaler?
Currently all I am doing is to manipulate CCPR4L and CCP4CONbits.DC4B to change my duty cycle.
Below is my code.. I am using Timer4. Changing the period on Timer 2 seems to be affect the baudrate of my EUSART for some reason but the datasheet does not seem to mention T2 is used for baudrate and least not from what I am understanding.
I am getting PWM out but I can't seem to make sense of how to control my duty cycle.
My chip is currently running ant 8MHZ on the internal oscillator.
Code:
void pwm_init()
{
T4CONbits.TMR4ON = 0; // STOP TIMER2 registers to POR state
PR4 = 0; // Set period
// Set prescaler
T4CONbits.T4CKPS0 = 0;
T4CONbits.T4CKPS1 = 0;
TRISBbits.TRISB4 = 0; // Set B4 to output
TRISBbits.TRISB5 = 0; // Set B5 to output
TRISBbits.TRISB6 = 0; // Set B6 to output
CCP4CON = 0b0111100; // Set CCP4 to PWM
CCP5CON = 0b0001100; // Set CCP5 to PWM
CCP6CON = 0b0001100; // Set CCP6 to PWM
CCPR4L = 0;
CCPR5L = 0;
CCPR6L = 0;
CCPTMRS1 = 1; //Set clock to T4 for all CCP registers
T4CONbits.TMR4ON = 1; // Turn on T2
}
void pwm_setDuty4(unsigned duty)
{
CCPR4L = (unsigned char)duty & 0x00ff;
CCP4CONbits.DC4B = ((duty & 0xff00) >> 8);
}