Code of pic16f785 for PWM duty cycle control from a potentiometer

Thread Starter

hunterage2000

Joined May 2, 2010
487
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:
#include <stdio.h>
#include <xc.h>
#include <func.h>
#pragma config FOSC = INTOSCIO
#include <pic16f785.h>
#include <stdlib.h>

struct mybitfields
{
    unsigned a : 1;
    unsigned b : 5;
    unsigned  c : 2;
}test;

int main()
{
    init_osc();
    init_adc();
    init_PWM();
    init_portc();
   
    delay_1ms();
    ADCON0bits.GO_nDONE = 1;
    while(ADCON0bits.GO_nDONE);
    CCPR1L = ADRESL;
    char reg = ADRESH;   
    test.c = reg >> 6;
    CCP1CONbits.DCB = test.c;
       
    while(1)
    {
    PIR1bits.TMR2IF = 0;
    while(!PIR1bits.TMR2IF);
    }
   
   
}
 

dannyf

Joined Sep 13, 2015
2,197
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.
 

Thread Starter

hunterage2000

Joined May 2, 2010
487
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.
 
Top