// PIC18 in C - Versione 0.1a - Luglio 2014 // Copyright (c) 2014, Vincenzo Villa // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/PIC18/pwm.htm // Reference: PIC18F14K50 data sheet #define _XTAL_FREQ 16000000 // Default PIC18F14K50 clock #define PWM_T 199u // See text - 20 kHz @ Fclk = 16 MHz (199 = 200 - 1) #define PWM_DC 320u // See text - 40% => 320 / 200 / 4 #include "configurationsbits.h" void main(void) { OSCCONbits.IRCF = 7; // Set internal clock to 16 MHz T2CONbits.T2OUTPS = 0; // Timer2 1:1 Postscaler T2CONbits.T2CKPS = 0; // Timer2 1:1 Prescaler PR2 = PWM_T; // Timer2 Period Register (last count) CCP1CONbits.CCP1M = 0b1100; //PWM mode; P1x active-high CCP1CONbits.P1M = 0b00; // Single output: P1x controlled by steering PSTRCONbits.STRSYNC = 1; // Output steering update occurs on next PWM period PSTRCONbits.STRA = 0; // P1A pin is assigned to port pin PSTRCONbits.STRB = 0; // P1B pin is assigned to port pin PSTRCONbits.STRC = 0; // P1C pin is assigned to port pin PSTRCONbits.STRD = 1; // P1D pin has the PWM waveform with polarity control from CCP1M<1:0> TRISCbits.RC2 = 0; // Set P1D (aka RC2) as output CCPR1L = PWM_DC >> 2; // Set PWM Ton - 8 MSB bits CCP1CONbits.DC1B = PWM_DC & 0x03; // Set PWM Ton - 2 LSB bits T2CONbits.TMR2ON = 1; // Timer2 on while (1); }