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, offif pin(rotaryA)=0 then if pin(rotaryB)=0 then gosub moveup else gosub movedownendifpause debounceinterrupt rotaryA, rotationreturnmoveup:value = value + rateif value>100 then value=100 'refreshgosub changereturnmovedown:value = value - rateif value<0 then value=0 'refreshgosub changereturnchange:if active=1 then outputvalue=value else outputvalue=0pwm(ledpin)=outputvalue*10dimmer.brightness outputvaluereturnpressed:interrupt buttonpin, offpause debounceif pin(buttonpin)=0 then gosub toggleinterrupt buttonpin, pressedreturntoggle:active=1-activeif active=1 then outputvalue=value else outputvalue=0if active=1 then pwm(ledpin)=outputvalue*10 else pwm(ledpin)=0returnend '-----------end------------