Dir PORTB.0 Out
Dir PORTB.3 Out
Dir PORTA.0 In
Brightness = 255
Set PORTB.0 On
Set PORTB.3 On
Do Forever
HPWM 1, 40, Brightness
Brightness = Brightness-10
If Brightness < 0 Then
Brightness = 0
End If
Wait 500 ms
Loop
When run the code is fine - the LED starts on and gradually dims. But instead of stopping at 0 and the LED staying off, the brightness variable seems to start up to 255 again and the LED turns on and gradually dims again. Possibly something to do with the PWM behaviour?
Can anyone suggest a cause?
Thanks,
D.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
You will also have to look at the math of the variable. 'Brightness' starts at 255 and decreases by 10 each loop. That brings it through 15, 5, -5 (invalid). You can use gcha44's suggestion, but only of the value reaches 0. Decrease by 5 each loop and wait 250 mS. I think that will work better.
-Bert
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Simple piece of code to dim an LED:
;Chip Settings
#chip 16F628A,4
#config OSC=INTOSC_OSC_CLKOUT
;Defines (Constants)
#define LCD_IO 0
#define LCD_RW PORTA.0
;Variables
Dim Brightness As byte
Dir PORTB.0 Out
Dir PORTB.3 Out
Dir PORTA.0 In
Brightness = 255
Set PORTB.0 On
Set PORTB.3 On
Do Forever
HPWM 1, 40, Brightness
Brightness = Brightness-10
If Brightness < 0 Then
Brightness = 0
End If
Wait 500 ms
Loop
When run the code is fine - the LED starts on and gradually dims. But instead of stopping at 0 and the LED staying off, the brightness variable seems to start up to 255 again and the LED turns on and gradually dims again. Possibly something to do with the PWM behaviour?
Can anyone suggest a cause?
Thanks,
D.
Hi ,
Brightness is a byte variable . It can't be <0 ! Try "If Brightnes < 1 then Brightness=0 and the result will be correct
Regards
You will also have to look at the math of the variable. 'Brightness' starts at 255 and decreases by 10 each loop. That brings it through 15, 5, -5 (invalid). You can use gcha44's suggestion, but only of the value reaches 0. Decrease by 5 each loop and wait 250 mS. I think that will work better.
-Bert
Yes , Bert490 is right .
My example was usable only with -1
If you want to use any decrementation (1,2,3,4,…. ) , you ca also do
Dim decrement as byte
decrement=10
Brightness=255
Do forever
HPWM 1, 40, Brightness
If decrement < = Brigthness then
Brightness=brigthness-decrement
else
Brightness=0
end if
wait 500mS
Loop
You'll can use that each time you'll want to reach 0 when decreasing any number .
GC
Thanks chaps. Great help.
It just didn't click that I was out of bounds for a byte!
That last snippet of code worked a treat.