Controlling two LED brightnesses with one PWM

hippy

Technical Support
Staff member
This code demonstrates controlling the brightness of two LED's independently with one PWMOUT pin. It multiplexes the LED's, in this case a three-leg LED, tri-colour common cathode. PWM the cathode, raise one of the LED anodes high, repeat for next. Should also work for RGB.

This is for the 20M2, coded so I could plug the LED R-0V-G straight into the socket of an AXE091 alongside the C.1-C.2-C.3 pins with no resistors. Note that because it's PWM'ing the 0V, duty of 0 is full on, 255 is off.

Code:
#Picaxe 20M2
#No_Data

Symbol redLevel     = w0
Symbol redLevel.msb = b1
Symbol redFadeUp    = b11

Symbol grnLevel     = w1
Symbol grnLevel.msb = b3
Symbol grnFadeUp    = b13

SetFreq M16

Low C.1 ; LED Red - Anode 
Low C.2 ; LED 0V  - Cathode (PWM'd)
Low C.3 ; LED Grn - Anode

redLevel = $FFFF : redFadeUp = 0
grnLevel = $FFFF : grnFadeUp = 0

PwmOut  C.2, 63, 0

Do

  PwmDuty C.2, redLevel.msb : PulsOut C.1, 100

  PwmDuty C.2, grnLevel.msb : PulsOut C.3, 100

  If redFadeUp = 1 Then
    redLevel = redLevel + $10 : If redLevel.msb = $FF Then : redFadeUp = 0 : End If
  Else
    redLevel = redLevel - $10 : If redLevel.msb = $00 Then : redFadeUp = 1 : End If
  End If

  If grnFadeUp = 1 Then
    grnLevel = grnLevel + $18 : If grnLevel.msb = $FF Then : grnFadeUp = 0 : End If
  Else
    grnLevel = grnLevel - $18 : If grnLevel.msb = $00 Then : grnFadeUp = 1 : End If
  End If

Loop
 

nick12ab

Senior Member
Since you're only lighting one LED at once, would it not be better just to use the pwm command on each LED in turn, eliminating the need for a third pin?
 

hippy

Technical Support
Staff member
With cost of Picaxe chips being so low, use a 14M2 with 4 PWM outputs.
The inspiration for this was to double up on all PWMOUT so could control eight or more LED's from a 14M2. For fewer LED's one per PWM would be best.
 

nick12ab

Senior Member
So what was wrong with using pwm?

Example to fade two LEDs 180 degrees out of phase:
Code:
#picaxe 08m
symbol loopcounter = b4
symbol pwm1 = b5
symbol pwm2 = b6

main:
	inc loopcounter
	if loopcounter < 128 then
		pwm1 = loopcounter * 2
	else
		pwm1 = 255 - loopcounter * 2
	end if
	pwm2 = 255 - pwm1
	pwm 1,pwm1,1
	pwm 2,pwm2,1
	goto main
Is there some serious problem with using the pwm command that I'm missing?
 

hippy

Technical Support
Staff member
So what was wrong with using pwm? ... Is there some serious problem with using the pwm command that I'm missing?
Probably not; having suggested multiplexing PWMOUT I thought I'd best try it!

Using PWMOUT gives a brightness resolution of up to 1024 steps and in a short enough time to allow the LED to not need a current limiting resistors. I have no idea how PWM or other techniques would compare.

There's the multiple PULSOUT trick and PAUSE to provide multiple LED control ( often RGB on an 08M2 ) so we have three alternatives now.
 
Top