software pwm

General discussion relating to the library modules supplied with the compiler

Moderators: David Barker, Jerry Messina

Post Reply
Horace
Posts: 12
Joined: Fri Apr 04, 2008 5:50 am
Location: South London

software pwm

Post by Horace » Tue Jun 10, 2008 3:07 pm

I have a code snippet to share with anyone who is interested, it cycles a RBG led such as the "piranha" super flux RBG through the colours. It is a much simplified version of microchip app AN1074. The microchip data sheet explains how it works far better than I can.

Code: Select all

'software pwm fades RGB led out of phase, taken from microchip app AN1074
'cutting the interrupt down from 320 to 100us seems to stop it hiccuping
'colour change slightly smoother maybe my imagination.
Device = 18f4420
Clock = 20
Dim IntCount, Dutycycle0, Dutycycle1, Dutycycle2, phase0, phase1, phase2 As Byte
   
Dim RED As PORTB.0
Dim GREEN As PORTB.1
Dim BLUE As PORTB.2
Dim BeginPWM As Bit

Const Array_A(128) As Byte = (16,17,17,18,19,20,20,21,22,22,23,24,24,25,26
,26,27,27,28,28,28,29,29,30,30,30,30,31,31,31,31,31,31,31,31,31,31,31,30,30
,30,30,29,29,28,28,28,27,27,26,26,25,24,24,23,22,22,21,20,20,19,18,17,17,16
,15,15,14,13,12,12,11,10,10,09,08,08,07,06,06,05,05,04,04,04,03,03,02,02,02
,02,01,01,01,01,01,01,01,01,01,01,01,02,02,02,02,03,03,04,04,04,05,05,06,06
,07,08,08,09,10,10,11,12,12,13,14,15,15)
Interrupt CLK() 
	TMR0L = 9 'reload the trm0 count @100us
       
Inc(IntCount)	
If IntCount= 32 Then
    IntCount = 0	
    RED = 1  'these are for common anode led
    GREEN = 1
    BLUE = 1
    BeginPWM = 1' Set flag for main software loop 
End If

If  (Dutycycle0 = IntCount )
Then RED = 0
End If 	  	
If  (Dutycycle1 = IntCount ) 
Then GREEN = 0
End If 	    
If  (Dutycycle2 = IntCount ) 
Then BLUE = 0	    
End If 
INTCON.2 = 0
End Interrupt
'program starts here
   TRISB = 0
   ADCON1 = 15
   INTCON = %11100000  ' enable GIE & PEIE
   T0CON = %11000000   'Timer0 is 8bit and on 
   Enable(CLK)         'enable jump to ISR   

While true
    If BeginPWM = 1 Then
    BeginPWM = 0
    
    Inc	(phase0)
    phase0 = (phase0 And %01111111)
    Dutycycle0 = Array_A(phase0)
    phase1 = ((phase0+85) And %01111111)
    Dutycycle1 = Array_A(phase1)
    phase2 = ((phase0+170) And %01111111)
    Dutycycle2 = Array_A(phase2)
    End If 
    DelayMS(4)'this alters the cycle speed 2 is fast 300  slow cycle
Wend 
End

User avatar
Steven
BETA Tester
Posts: 406
Joined: Tue Oct 03, 2006 8:32 pm
Location: Cumbria, UK

Post by Steven » Tue Jun 10, 2008 4:59 pm

Thanks for the code snippet. I have some RGB leds that I got a while ago - I must try this code with them. Thanks for sharing.

Post Reply