Subversion Repositories Code-Repo

Rev

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

Rev Author Line No. Line
283 Kevin 1
#include "defines.h"
2
#include "PWM.h"
3
 
4
void PWM_1_Init(void) {
5
    // Output pin initially blocked
6
    CCP_1_TRIS = 1;
7
 
8
    /* Initialize PWM module */
9
    // PWM period = (PRx + 1] * 4 * 1/FOSC * TMRx_prescale
10
    PR2 = 255; // 2ms @ 32MHz
11
    CCP1CONbits.P1M = 0b00; // Single output, P1A modulated only
12
    CCP1CONbits.CCP1M = 0b1100; // PWM mode, P1A active-high, P1B active-high
13
    CCPTMRSbits.C1TSEL = 0b00;  // CCP1 timer based off Timer2
14
 
15
    // Idle the output till width is specified
16
    // Pulse width = (CCPRxL:CCPxCON) * 1/FOSC * TMRx_prescale
17
    CCPR1L = 0x00;
18
    CCP1CONbits.DC1B = 0b00;
19
 
20
    /* Initialize Timer 2 */
21
    PIR1bits.TMR2IF = 0; // Clear the interrupt flag for Timer 2
22
    T2CONbits.T2CKPS = 0b11; // Set a prescaler of 64
23
    T2CONbits.TMR2ON = 1; // Enable the timer
24
 
25
    // Wait for the timer to overflow before enabling output
26
    while (!PIR1bits.TMR2IF);
27
    CCP_1_TRIS = 0;
28
}
29
 
30
void PWM_2_Init(void) {
31
    // Output pin initially blocked
32
    CCP_2_TRIS = 1;
33
 
34
    /* Initialize PWM module */
35
    PR4 = 255; // 2ms @ 32MHz
36
    // PWM period = (PRx + 1] * 4 * 1/FOSC * TMRx_prescale
37
    CCP2CONbits.P2M = 0b00; // Single output, P2A modulated only
38
    CCP2CONbits.CCP2M = 0b1100; // PWM mode, P2A active-high, P2B active-high
39
    CCPTMRSbits.C2TSEL = 0b01;  // CCP2 timer based off Timer4
40
 
41
    // Idle the output till width is specified
42
    // Pulse width = (CCPRxL:CCPxCON) * 1/FOSC * TMRx_prescale
43
    CCPR2L = 0x00;
44
    CCP2CONbits.DC2B = 0b00;
45
 
46
    /* Initialize Timer 2 */
47
    PIR3bits.TMR4IF = 0; // Clear the interrupt flag for Timer 2
48
    T4CONbits.T4CKPS = 0b11; // Set a prescaler of 64
49
    T4CONbits.TMR4ON = 1; // Enable the timer
50
 
51
    // Wait for the timer to overflow before enabling output
52
    while (!PIR3bits.TMR4IF);
53
    CCP_2_TRIS = 0;
54
}
55
 
56
void PWM_1_Set(uint16_t width_us) {
57
    // Set the pulse duration to the requested width
58
    int value = width_us / 2;
59
    CCPR1L = value >> 2;
60
    CCP1CONbits.DC1B = value;
61
}
62
 
63
void PWM_2_Set(uint16_t width_us) {
64
    // Set the pulse duration to the requested width
65
    int value = width_us / 2;
66
    CCPR2L = value >> 2;
67
    CCP2CONbits.DC2B = value;
68
}