PIC18F2x/4xJ13 - ECCPx PWM.

0.Contents

PIC18F4xJ/K : PIC18F47J13.

1..

// Configuration registers.
#pragma config WDTEN=OFF, PLLDIV=1, CFGPLLEN=OFF, STVREN=ON, XINST=OFF
#pragma config CP0=OFF, OSC=INTOSCO, SOSCSEL=HIGH, CLKOEC=OFF, FCMEN=OFF
#pragma config IESO=OFF, WDTPS=32768, DSWDTOSC=INTOSCREF, RTCOSC=T1OSCREF
#pragma config DSBOREN=ON, DSWDTEN=ON, DSWDTPS=G2
#pragma config IOL1WAY=ON, ADCSEL=BIT10, PLLSEL=PLL4X, MSSP7B_EN=MSK7
#pragma config WPFP=PAGE_63, WPCFG=OFF, WPDIS=OFF, WPEND=PAGE_WPFP

#include <xc.h>
#include <stdint.h>
#define _XTAL_FREQ 8000000
// PIC18FxxJ13 - Compile with XC8(v2.05).
// PIC18FxxJ13 - @8MHz Internal oscillator.

// ECCPx - PWM Steering mode.

// MCU.R - Probe A.
// MCU.R - Probe B.
// MCU.R - Probe C.
// MCU.R - Probe D.

// Definitions.
#define PWM_FREQUENCY	0x7F	// ~15.7kHz @8MHz.

// Main.
int main(void)
{
	// MCU Initialization.
	// Oscillator Settings.
	// Internal Oscillator 8MHz.
	OSCCONbits.IRCF = 0x7;
	OSCTUNEbits.PLLEN = 0;
	// Ports Initialization.
    // Open-drain Output Settings.
    ODCON3 = 0b00000000;
    ODCON2 = 0b00000000;
    ODCON1 = 0b00000000;
	// Analog Input Settings.
	ANCON1 = 0b00011111;
	//ANCON0 = 0b00011111;	// For PIC18F2xJ13.
	ANCON0 = 0b11111111;	// For PIC18F4xJ13.
	// Port A.
	PORTA = 0b00000000;
	TRISA = 0b00000000;
	// Port B.
	PORTB = 0b00000000;
	TRISB = 0b00000000;
	// Port C.
// RC7 - I - FLT0.
	PORTC = 0b00000000;
	TRISC = 0b10000000;
	// Port D.
	PORTD = 0b00000000;		// For PIC18F4xJ13.
	TRISD = 0b00000000;		// For PIC18F4xJ13.
	// Port E.
	PORTE = 0b00000000;		// For PIC18F4xJ13.
	TRISE = 0b00000000;		// For PIC18F4xJ13.
	// PPS Initialization.
	PPSCONbits.IOLOCK = 0;
	// PPS Inputs.
	RPINR24 = 0x12; // RC7/RP18 - ECCPx FLT0.
	// PPS Outputs.
	RPOR21 = 0xe;	// RD4/RP21 - ECCP1 P1A.
	RPOR22 = 0xf;	// RD5/RP22 - ECCP1 P1B.
	RPOR23 = 0x10;	// RD6/RP23 - ECCP1 P1C.
	RPOR24 = 0x11;	// RD7/RP24 - ECCP1 P1D.
	PPSCONbits.IOLOCK = 1;
	// Timer2 Initialization.
	T2CON = 0b00000000;
	// Timer2 PWM Period.
	PR2 = PWM_FREQUENCY;
	// ECCP1 Initialization.
	// ECCP1 PWM 4x Single output.
	CCP1CONbits.P1M = 0b00;
	// ECCP1 P1A, P1B, P1C & P1D Active-high.
	CCP1CONbits.CCP1M = 0b1100;
	// ECCP1 Auto-shutdown pin FLT0.
	ECCP1ASbits.ECCP1AS = 0b100;
	// ECCP1 Shutdown state HIGH for P1A & P1C.
	ECCP1ASbits.PSS1AC = 0b01;
	// ECCP1 Shutdown state LOW for P1B & P1D.
	ECCP1ASbits.PSS1BD = 0b00;
	// ECCP1 Auto-restart disable.
	ECCP1DELbits.P1RSEN = 0;
	// ECCP1 Steering Enable bit.
	// ECCP1 1A, P1B, P1C & P1D.
	PSTR1CONbits.STRD = 1;
	PSTR1CONbits.STRC = 1;
	PSTR1CONbits.STRB = 1;
	PSTR1CONbits.STRA = 1;

// PWM Select Timer 2 for ECCP1.
	CCPTMRS0bits.C1TSEL = 0b00;
	// Timer2 Start.
	T2CONbits.TMR2ON = 1;

// ECCP1
ECCP1ASbits.ECCP1ASE = 0;
	
	uint8_t i;
	while(1){
		for(i=0; i<PWM_FREQUENCY; i++){
			// Duty Cycle.
			CCPR1L = i;
			__delay_ms(100);
		}
	}
	return(0);
}

05.2019