Subversion Repositories Code-Repo

Rev

Rev 163 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include <xc.h>
#include "defines.h"
#include "base_PWM.h"

void PWM_Init() {
    // Output pin initially blocked
    PWM_TRIS = 1;

    /* Initialize PWM module */
    PR2 = 0xF9; // 4ms @ 16MHz
    CCP1CONbits.P1M = 0b00; // Single output, P1A modulated only
    CCP1CONbits.CCP1M = 0b1100; // PWM mode, P1A active-high, P1B active-high

    // Idle the output till width is specified
    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);
    PWM_TRIS = 0;
}

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