Software PWM, Led fade-in fade-out
When I had a shortage of ccp pins I wrote this simple software pwm for MikroC:
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 unsigned int PWM_fade=200; void Delay(int num){ // De delay functie while(num>0) num--;} void main() { while(1){ for (i = 0; i <= PWM_fade; i++){ //Led1 van aan naar uit; Led2 van uit naar aan; Led1 = 1; Led2 = 0; Delay(PWM_fade - i); Led1 = 0; Led2 = 1; Delay(i); } for (i = 0; i <= PWM_fade; i++){ //Led2 van aan naar uit; Led1 van uit naar aan; Led1 = 0; Led2 = 1; Delay(PWM_fade - i); Led1 = 1; Led2 = 0; Delay(i); } } }
The puls width frequency is always at maximum depending on your clock frequency. If you want a lower frequency for your pwm then you have to add an extra delay to Delay(). For example add Delay_us(20); between line 5 and 6.
Led2 always has the opposite duty cycle of led1 as you can see when you study the code. The value of PWM_fade determines how fast the leds are fading. This is how it looks like:
It works best when you set the value of PWM_fade via a potentiometer. All you need is an analog pin on your pic. The ADC library of MikroC makes the rest very easy.
Play with it and let me know what you find 🙂