Project - Rotary Encoder


Mains Dimmer/Speed Controller using a rotary encoder.
See the  demo video
Optionally, if the rotary encoder includes a push switch (or one is added separately) it can be used to toggle the Mains output On or Off.

An optional LED can be used as an output indicator.

The variable rate=10 sets the rate of change per rotational 'click', a lower value offers finer control, a higher value offers quicker change.

Basic:
'Rotary Encoder Dimmer/Speed Controller - Electroguard - developed on Annex 1,41 beta 3
dimmer.setup 4,5,0,1                       'configure dimmer module, 4 and 13 = zero crossing,  5 = pwm
dimmer.limits 0, 9500                       'actual min/max delay in triac firing
value=0                                           'initial startup value
active=1                                          'dimmer output On=1, Off=0
if active=1 then outputvalue=value else outputvalue=0
option.pwmfreq 100                          'reduce pwm frequency to reduce cpu load
ledpin=15                                        'optional pwm led power indicator
pwm(ledpin)=outputvalue      
rotaryA=12                                      'Rotary encoder pulse A output pin
rotaryB=14                                      'Rotary encoder pulse B output pin
pin.mode rotaryA, input, pullup
pin.mode rotaryB, input, pullup
interrupt rotaryA, rotation
rate=10                                           'rotary encoder rate of change
debounce=50                                   'debounce duration for button and rotary encoder contacts
buttonpin=0                                     'optional gpio0 button to toggle output On/Off
pin.mode buttonpin, input, pullup
interrupt buttonpin, pressed
wait

rotation:
interrupt rotaryA, off
if pin(rotaryA)=0 then
 if pin(rotaryB)=0 then gosub moveup else gosub movedown
endif
pause debounce
interrupt rotaryA, rotation
return

moveup:
value = value + rate
if value>100 then value=100
'refresh
gosub change
return

movedown:
value = value - rate
if value<0 then value=0
'refresh
gosub change
return

change:
if active=1 then outputvalue=value else outputvalue=0
pwm(ledpin)=outputvalue*10
dimmer.brightness outputvalue
return

pressed:
interrupt buttonpin, off
pause debounce
if pin(buttonpin)=0 then gosub toggle
interrupt buttonpin, pressed
return

toggle:
active=1-active
if active=1 then outputvalue=value else outputvalue=0
if active=1 then pwm(ledpin)=outputvalue*10 else pwm(ledpin)=0
return

end  '-----------end------------