Electrical – PIC18F2550 PWM Square wave generator

cmicrocontrollermplabxpic

I am trying to generate a square wave on 50% Duty Cycle using my PIC18F2550. The signal is to be outputted through a loudspeaker. The frequency does not really matter, as long as it is in the hearing range (a few Khz should do).

This is my rather simplistic code;

#include "xc.h"

void PWM_init(void);
void Chip_init(void);

void main(void){

Chip_init();
PWM_init();
while(1);
}
void PWM_init(void) {

/****Set All PWM Registers*****/
PR2 = 0b11111111;
T2CON = 0b00000111;
CCPR2L = 0b01111111;
CCP2CON = 0b00111100;  
}

void Chip_init(void){

/** Initialize all outputs ****/
LATCbits.LATC1 = 0;
TRISCbits.TRISC1 = 0;
LATBbits.LATB3 = 0;
TRISBbits.TRISB3 = 0;
}      

This should give me a PWM signal of about 3Khz on either C1 or B3, atleast to my understanding. But i am getting nothing, unfortunately. Can anyone tell me where I went wrong?

Best Answer

I ended up changing my code to this. Now I am getting a 3khz PWM signal of square pulses.

The prescaler was increased from 4 to 16 and I assigned most bits individually. Im not 100 % sure yet what the mistakes were in my earlier code.

#include <xc.h>

/*Function prototypes*/
void initChip(void);
void initPWM(void);

void main(void) {
initChip();
initPWM();
while(1);
}

void initChip(void)
{
PORTB = 0x00; //Initial PORTB
TRISB = 0x00; //Define PORTB as output
PORTC = 0x00; //Initial PORTC
TRISC = 0x00; //Define PORTC as output
INTCONbits.GIE = 0; // Turn Off global interrupt
}

void initPWM(void)
{
PR2 = 0xFF;
CCPR2L = 0x7F; // 
CCP2CONbits.DC2B0 = 0;
CCP2CONbits.DC2B1 = 0;
TRISB = 0x00; // Clear Tris registers
TRISC = 0x00;
T2CONbits.T2CKPS1 = 1; // Timer 2 Prescaler = 16
T2CONbits.T2CKPS0 = 1;
T2CONbits.TMR2ON = 1; // Enable Timer 2
CCP2CONbits.CCP2M3 = 1; // Set CCP as PWM
CCP2CONbits.CCP2M2 = 1;
}