PWM Fader

marzan

Senior Member
Happy new year everyone !!

I am converting a kids battery operated nightlight to fade out after a specified time. can anyone see where I have gone wrong in the following code.
I am using an 08M2

Code:
symbol val = b0 
symbol pwmPin = c.2     			;led array
symbol led = c.1  				;standby led

init:
pwmout pwmdiv4, pwmPin, 249, 500    	;set PWM

main: 						;loop to fade led array using PWM
val = 255
	do
		pwmduty pwmPin, val  ; set pwm duty
		val = val -1
			for b1 = 1 to 6   	;loop to slow down fader
				pause 1000
			next
		if val = 0 then goto standby  ;when PWM at 0 then activate standby LED
	loop
standby:
	do
		high led
		pause 300
		low led 
		pause 2000
	loop
Thanks for looking.

Marz
 

marzan

Senior Member
False alarm of sorts - too many zeroes n the loop. :eek: I have noticed one issue though. The leds stay on slightly at the end. Do I need to turn off the PWM or is it a hardware issue?
Schematic: 1k from picaxe pin to 2222 NPN transistor with a 10k tied low. 330r to leds and normal 22k/10k to picaxe socket:

nightlight.jpg

Thanks.

Marz.
 

Dippy

Moderator
A real schematic would help, especially as that image is such low resolution. Then people can see if there is a design flaw.
It's always best to switch port.pin completely off. I would have thought that was easier to try than ask? ;)
 

marzan

Senior Member
A real schematic would help, especially as that image is such low resolution. Then people can see if there is a design flaw.
It's always best to switch port.pin completely off. I would have thought that was easier to try than ask? ;)
I did try with a low c.1 but didnt work. I have been hunting around the forum to see if there is a command to turn PWM off.

Marz.
 

hippy

Technical Support
Staff member
I have noticed one issue though. The leds stay on slightly at the end. Do I need to turn off the PWM or is it a hardware issue?
It's an algorithm design issue. In your code you have ...

Code:
do
		pwmduty pwmPin, val  ; set pwm duty
		val = val -1
So when exiting on 'val = 0' you are leaving with the PWM duty having last been set to 1. This is the residual brightness seen on leaving the loop.

You either need to turn the PWM off or set its duty to zero after exiting the loop or recode your loop so that does not exit until after PWM duty has been set to zero. Turning it off after the loop is easiest.
 

marzan

Senior Member
Thanks for all the comments everyone. All good points. I wish there was more time to spend on picaxe. I tend to forget stuff learned along the way because I dont do it often enough.

Marz.
 
Top