Search code examples
cpicmplabxc8

How to pass a 10 bit value to two registers?


I'm trying to pass the value of DC to both CCPR1L, DC1B1, and DC1B0, right now I am doing it manually, but is there a way of using the value of DC directly?

void SetDCPWM1(unsigned int DC){
    CCPR1L = 0b01011010;
    DC1B1 = 0;
    DC1B0 = 0;
}

Right now Im not using DC , because I dont know how to correctly pass the value to the registers. DC is a 10 bit value , DC1B1 and DC1B0 must have bits 1 and 2 and CCPR1L must have bits 3 - 10.


Solution

  • Assuming that the 10-bits of the PWM duty cycle are the low 10-bits of the function parameter then this should do what you have asked for.

    void SetDCPWM1(unsigned int DC){
        CCPR1L = (DC >> 2);
        DC1B1 = 0;
        DC1B0 = 0;
        if (DC & 2) DC1B1 = 1;
        if (DC & 1) DC1B0 = 1;
    }
    

    This code should address the comment from Mike :

    void SetDCPWM1(unsigned int DC){
        CCP1CONbits.DC1B = (unsigned char)(DC) & 0x03;
        CCPR1L = (unsigned char)(DC>>2);
    }
    

    Further the two LSBs of the PWM duty cycle are now updated in the same instruction cycle.