Action
Reads pulses from a rotary encoder.
Syntax
Var = ENCODER( pin1, pin2, LeftLabel, RightLabel , wait)
Remarks
Var |
The target variable that is assigned with the result |
Pin1 and pin2 |
These are the names of the PIN registers to which the output of the encoder is connected. Both pins must be on the same PIN register. So Pinb.0 and Pinb.7 is valid while PinB.0 and PinA.0 is not. |
LeftLabel |
The name of the label that will be called/executed when a transition to the left is encoded. |
RightLabel |
The name of the label that will be called/executed when a transition to the right is encountered. |
wait |
A value of 0 will only check for a rotation/pulse. While a value of 1 will wait until a user actual turns the encoder. A value of 1 will thus halt your program. |
There are some conditions you need to fulfill :
| • | The label that is called by the encoder must be terminated by a RETURN statement. |
| • | The pin must work in the input mode. By default all pins work in input mode. |
| • | The pull up resistors must be activated by writing a logic 1 to the port registers as the examples shows. |
Rotary encoders come in many flavors. Some encoders also have a build in switch.
A sample of an encoder


Since the microprocessor has internal pull up resistors, you do not need external pull up resistors for most encoders.
Example
'-----------------------------------------------------------------------------------------
'name : encoder.bas
'copyright : (c) 1995-2005, MCS Electronics
'purpose : demonstration of encoder function
'micro : Mega128
'suited for demo : yes
'commercial addon needed : no
'An encoder has 2 outputs and a ground
'We connect the outputs to pinb.0 and pinb.1
'You may choose different pins as long as they are at the same PORT
'The pins must be configured to work as input pins
'This function works for all PIN registers
'-----------------------------------------------------------------------------------------
$regfile = "m128def.dat" ' specify the used micro
$crystal = 4000000 ' used crystal frequency
$baud = 19200 ' use baud rate
$hwstack = 32 ' default use 32 for the hardware stack
$swstack = 10 ' default use 10 for the SW stack
$framesize = 40 ' default use 40 for the frame space
Print "Encoder test"
Dim B As Byte
'we have dimmed a byte because we need to maintain the state of the encoder
Portb = &B11 ' activate pull up registers
Do
B = Encoder(pinb.0 , Pinb.1 , Links , Rechts , 1)
' ^--- 1 means wait for change which blocks programflow
' ^--------^---------- labels which are called
' ^-------^---------------------------- port PINs
Print B
Waitms 10
Loop
End
'so while you can choose PINB0 and PINB7,they must be both member of PINB
'this works on all PIN registers
Links:
Print "left rotation"
Return
Rechts:
Print "right rotation"
Return
End