Thursday, August 25, 2011

PIC18F2550 and PWM Experiment, using MikroC Pro for PIC

As the title suggest this experiment tests Microchips PIC18F2550 Microcontroller and its PWM Peripheral. The Code presented here turns on led connected at pin 13 (RC2/CCP1) of the PIC18F4550 with 0% brightness and then gradually increases the brightness upto 100% with change in the duty cycle by calling PWM1_Set_Duty (duty) function by increasing duty variable after every 10 mili sec.

Schematics:


PWM Library Functions Description:
There are following 4 functions provided by MikroC Compiler which lets you control PIC microcontroller's PWM Channel.

1. PWM1_Init (const long freq)
This routine needs to be called before using other functions from PWM Library.
Takes "freq" parameter as frequency in hertz, and initializes the PIC microcontroller's PWM channel.
All PWM modules use Timer2 for its operation, so you can not set different frequencies for different PWM modules.

2. void PWM1_Set_Duty(unsigned short duty_ratio)
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.

3. void PWM1_Start(void)
The function returns nothing and takes no input parameter. This function starts PWM.
4. void PWM1_Stop(void)
The function returns nothing and takes no input parameter. This function stops PWM.

The source code presented here runs on internal 8.000Mhz built-in oscillator.

Configuration:

Source Code:

void main()
{
unsigned char duty = 0;
OSCCON = 0x70; // configures oscillator divider for 8MHz int. oscillator
PORTC = 0; // sets port c to all 0
TRISC = 0; //configures port c as output port
PWM1_Init (5000); // sets pwm frequency to 5000Hz
PWM1_Start(); // starts pwm1 peripheral

while (1)
{
PWM1_Set_Duty(duty); // sets duty cycle
duty++; // increments duty cycle by 1
Delay_ms(10); // adds 10 msec delay
}
}

Video 1: Showing signal observed at pin 13 (RC2/CCP1) changing duty cycle from 0% to 100% in a loop.




Video 2: Showing LED changing its brightness from 0% to 100% in a loop




Conclusion: PIC microcontroller's PWM peripheral is very easy to program using MikroC Library.


No comments:

Post a Comment