Module CCP1 as PWM signal generator
This example illustrates the use of CCP1 module in PWM mode. To make things more interesting, the duration of the P1A output pulses (PORTC,2) may be changed using pushbuttons symbolically marked as ‘DARK’ and ‘BRIGHT’, while the set duration is seen as binary combination on port B. The operation of this module is under control of the functions belonging to the specialized PWM Library. Three of them are used here:void Pwm1_Init(long freq);
Parameter freq sets the frequency of PWM signal expressed in herz. In this example it amounts to 5kHz.void Pwm1_Start(void);
void Pwm1_Set_Duty(unsigned short duty_ratio);
Parameter duty_ratio sets pulse duration in pulse sequence.void Pwm1_Stop(void);
/*Header******************************************************/ unsigned short current_duty, old_duty; // Define variables // current_duty and old_duty void initMain() { ANSEL = 0; // All I/O pins are configured as digital ANSELH = 0; PORTA = 255; // Port A initial state TRISA = 255; // All port A pins are configured as inputs PORTB = 0; // Initial state of port B TRISB = 0; // All port B pins are configured as outputs PORTC = 0; // Port C initial state TRISC = 0; // All port C pins are configured as outputs PWM1_Init(5000); // PWM module initialization (5KHz) } void main() { initMain(); current_duty = 16; // Initial value of variable current_duty old_duty = 0; // Reset variable old_duty PWM1_Start(); // Start PWM1 module while (1) { // Endless loop if (Button(&PORTA, 0,1,1)) // If the button connected to RA0 is pressed current_duty++ ; // increment variable current_duty if (Button(&PORTA, 1,1,1)) // If the pressed button is connected to RA1 current_duty-- ; // decrement value current_duty if (old_duty != current_duty) { // If current_duty and old_duty are not PWM1_Set_Duty(current_duty); // equal set PWM to a new value, old_duty = current_duty; // save the new value PORTB = old_duty; // and show it on port B } Delay_ms(200); // 200mS delay } }In order to make this example work properly, it is necessary to tick off the following libraries in the Library Manager prior to compiling: