In this example we are using a PIC16F877 to generate a PWM signal, this particular chip has 2 Capture/Compare/PWM Peripherals
The following MikroC Pro for Pic functions will be used
PWMx_Init
Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM frequency in Hz (refer to device data sheet for correct values in respect with Fosc).
timer_prescaler parameter represents the timer prescaler and can have following values: 1, 4, 16 and 64.
This routine needs to be called before using other functions from PWM Library.
PWMx_Set_Duty
Sets PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 is 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100.
Requires MCU must have CCP module. PWMx_Init must be called before using this routine.
PWMx_Start
Starts PWM.
Requires MCU must have CCP module. PWMx_Init must be called before using this routine.
PWMx_Stop
Stops PWM.
Requires MCU must have CCP module. PWMx_Init must be called before using this routine. PWMx_Start should be called before using this routine, otherwise it will have no effect as the PWM module is not running.
Schematic
In this example we connect an LED to Pin 16 of the PIC16F877 – CCP2
Code
MIkroC Pro for Pic example
We are using Pin16 which is CCP2 so we use the PWM2 functions
[codesyntax lang=”cpp”]
void main() { PORTC = 0; // set PORTC to 0 TRISC = 0; // designate PORTC pins as output PWM2_Init(1000); // Initialize PWM2 module at 1KHz PWM2_Start(); // start PWM2 PWM2_Set_Duty(255); // Set current duty cycle to 100% while (1) { // endless loop // 100% duty cycle: duty ratio can be calculated as (Percent*255)/100. PWM2_Set_Duty(255); // Change the duty cycle delay_ms(1000); //3 seconds delay // 10% duty cycle PWM2_Set_Duty(25); // Change the duty cycle delay_ms(1000); //3 seconds delay } }
[/codesyntax]
Links