// PIC18F14K50 in C - Versione 0.2 - Novembre 2010 // Copyright (c) 2010 VincenzoV.net // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/elettronica-di-base/PIC18F14K50 // Hardware PWM #include #include #include #include #pragma config FOSC = IRCCLKOUT // Internal RC oscillator (F/4 to OSC2 - pin 3) #pragma config WDTEN = OFF // Watchdog disabled #pragma config LVP = OFF // Disable Low Voltage Programming #pragma config MCLRE = OFF // Disable MCLR #define CLOCK 16 // Main clock [MHz] #define PWM_T 50 // PWM period [us] #define DC 40 // PWM DC% (0-100) void main (void) {unsigned int period; // PWM period unsigned int Ton; // PWM Ton if (CLOCK == 16) OSCCON = 0x70; // Set internal clock to 16 MHz - test other frequancy required... OpenTimer2( TIMER_INT_OFF & T2_PS_1_1 & T2_POST_1_1); period = ((unsigned int)CLOCK * PWM_T) / 4 - 1; // Only if T2_PS_1_1 (prescaler2 = 1) - 16 bit integer, unsigned if (period > 255) period = 255; // Timer2 is has only 8 bit OpenPWM1(period); // Set PWM period SetOutputPWM1 (SINGLE_OUT, PWM_MODE_1); Ton = (unsigned long)CLOCK * PWM_T * DC / 100; // 32 bit integer, unsigned if (Ton > 1023) Ton = 1023; // Only 10 bit allowed SetDCPWM1 (Ton); while (1); // Endless loop }