Home Code Generating a PWM signal with PIC16F877 using CCP Module

Generating a PWM signal with PIC16F877 using CCP Module

by shedboy71

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

led-and-pic16f877_schem

 

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

 

PIC Board PIC18F4520-I/P PIC18F4520 8-bit RISC PIC Development Board +11 Accessory Kits =Waveshare Open18F4520 Package A

Share

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More