Friday, 17 July 2015

Lesson 4 PWM to Control Brightness of an LED (MikroC)

In Lesson 3, we made mention of how PWM can be used to control LED brightness and motor speed control. In this tutorial we'll see how we can use it to Control the brightness of an LED. We advice that you check out Lesson 3(MikroC) before going through this tutorial in order to have an understanding of PWM. So let's get over to the program.

MikroC Code:
 
     /**********************************
Project Name :
   Using PWM to control LED brightness
Author : Promise
Description :
   This project demonstrate how to use PWM to control the brightness of an LED
Test configuration:
   MCU:  PIC 16F877A
   Oscillator: XT 8.0000 MHz, 8.0000 MHz Crystal
***********************************/


int i;
unsigned short duty_cycle;

void main() {

TRISC = 0x00;                       // PORTC set as output
PORTC.F2 = 0;                      // Set PORTC to Zero(low)
 PWM1_Init(5000);                  // PWM1 Initalized to 5KHz
PWM1_Start();                      // Start PWM1

while(1)  {                       // endless Loop

for(i=0;i<255;i++){               // loop to increase LED brightness

duty_cycle = i;                   // Assign Counter(i) to the duty_cycle
PWM1_Set_Duty(duty_cycle);        // Set duty Cycle
delay_ms(5);
}                                 // end of for-loop
delay_ms(5);                      // delay

for(;i>0;i--){                    // loop to decrease LED brightness

duty_cycle = i;
PWM1_Set_Duty(duty_cycle);
delay_ms(5);
}                                 // end of for-loop
delay_ms(10);
}
}



Proteus Schematic:

     
When Duty Cycle is Almost 0%

When Duty Cycle is Almost 100%

No comments:

Post a Comment