Subversion Repositories Code-Repo

Rev

Rev 283 | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include "defines.h"
#include "PWM.h"

void PWM_1_Init(void) {
    // Output pin initially blocked
    CCP_1_TRIS = 1;

    /* Initialize PWM module */
    // PWM period = (PRx + 1] * 4 * 1/FOSC * TMRx_prescale
    PR2 = 255; // 2ms @ 32MHz
    CCP1CONbits.P1M = 0b00; // Single output, P1A modulated only
    CCP1CONbits.CCP1M = 0b1100; // PWM mode, P1A active-high, P1B active-high
    CCPTMRSbits.C1TSEL = 0b00;  // CCP1 timer based off Timer2

    // Idle the output till width is specified
    // Pulse width = (CCPRxL:CCPxCON) * 1/FOSC * TMRx_prescale
    CCPR1L = 0x00;
    CCP1CONbits.DC1B = 0b00;

    /* Initialize Timer 2 */
    PIR1bits.TMR2IF = 0; // Clear the interrupt flag for Timer 2
    T2CONbits.T2CKPS = 0b11; // Set a prescaler of 64
    T2CONbits.TMR2ON = 1; // Enable the timer

    // Wait for the timer to overflow before enabling output
    while (!PIR1bits.TMR2IF);
    CCP_1_TRIS = 0;
}

void PWM_2_Init(void) {
    // Output pin initially blocked
    CCP_2_TRIS = 1;

    /* Initialize PWM module */
    PR4 = 255; // 2ms @ 32MHz
    // PWM period = (PRx + 1] * 4 * 1/FOSC * TMRx_prescale
    CCP2CONbits.P2M = 0b00; // Single output, P2A modulated only
    CCP2CONbits.CCP2M = 0b1100; // PWM mode, P2A active-high, P2B active-high
    CCPTMRSbits.C2TSEL = 0b01;  // CCP2 timer based off Timer4

    // Idle the output till width is specified
    // Pulse width = (CCPRxL:CCPxCON) * 1/FOSC * TMRx_prescale
    CCPR2L = 0x00;
    CCP2CONbits.DC2B = 0b00;

    /* Initialize Timer 2 */
    PIR3bits.TMR4IF = 0; // Clear the interrupt flag for Timer 2
    T4CONbits.T4CKPS = 0b11; // Set a prescaler of 64
    T4CONbits.TMR4ON = 1; // Enable the timer

    // Wait for the timer to overflow before enabling output
    while (!PIR3bits.TMR4IF);
    CCP_2_TRIS = 0;
}

void PWM_1_Set(uint16_t width_us) {
    // Set the pulse duration to the requested width
    int value = width_us / 2;
    CCPR1L = value >> 2;
    CCP1CONbits.DC1B = value;
}

void PWM_2_Set(uint16_t width_us) {
    // Set the pulse duration to the requested width
    int value = width_us / 2;
    CCPR2L = value >> 2;
    CCP2CONbits.DC2B = value;
}