Code of pic16f785 for PWM duty cycle control from a potentiometer

Discussion in 'Embedded Systems and Microcontrollers' started by hunterage2000, May 8, 2016.

  1. hunterage2000

    Thread Starter Active Member

    May 2, 2010
    400
    0
    Hi I am trying to control a PWM duty cycle from a potentiometer but its not working as expected.

    I have created a bit field for storing the upper 2 bits of the ADRESH register (i.e. left aligned adc) into the 2 bits of c which is put into bits 5:4 of the CCP1CONbits.DC1B. These bits form part of the 10 bit resolution of the CCP module. The other 8 bits come from ADRESL which is put directly into CCPR1L.

    bits 7:6 is shifted right by 6 to bits1:0 and put into CCP1CONbits.DC1B.

    On my oscilloscope, as the pot is adjusted from left to right, the duty cycle go's from 1% to about 98% then goes to about 25% to 98% again. I'm assuming the ADRESH bits are not being put into CCP1CONbits.DC1B but I dont know why. Can anyone see why and is there a way to directly access the 2 upper bits of ADRESH?

    Code (Text):
    1. #include <stdio.h>
    2. #include <xc.h>
    3. #include <func.h>
    4. #pragma config FOSC = INTOSCIO
    5. #include <pic16f785.h>
    6. #include <stdlib.h>
    7.  
    8. struct mybitfields
    9. {
    10.     unsigned a : 1;
    11.     unsigned b : 5;
    12.     unsigned  c : 2;
    13. }test;
    14.  
    15. int main()
    16. {
    17.     init_osc();
    18.     init_adc();
    19.     init_PWM();
    20.     init_portc();
    21.    
    22.     delay_1ms();
    23.     ADCON0bits.GO_nDONE = 1;
    24.     while(ADCON0bits.GO_nDONE);
    25.     CCPR1L = ADRESL;
    26.     char reg = ADRESH;  
    27.     test.c = reg >> 6;
    28.     CCP1CONbits.DCB = test.c;
    29.        
    30.     while(1)
    31.     {
    32.     PIR1bits.TMR2IF = 0;
    33.     while(!PIR1bits.TMR2IF);
    34.     }
    35.    
    36.    
    37. }
     
  2. dannyf

    Well-Known Member

    Sep 13, 2015
    1,781
    360
    Give a known value to ADRESH and see if it flows through correctly to CCP1CONbits.DCB. After that, you will know precisely why your code doesn't work.
     
  3. hunterage2000

    Thread Starter Active Member

    May 2, 2010
    400
    0
    Looks like ADRESH cant be given a value and the input of the pot on RA2 doesnt show a value when running debug. I had PR2(period) set to 255 so I changed it to 1023 thinking this may work but it didn't.
     
  4. hunterage2000

    Thread Starter Active Member

    May 2, 2010
    400
    0
    Its ok I've done it. I put both ADRESL and ADRESH into an a 16 bit int and scaled the 10bit value down to 8.
     
Loading...