Rotary Encoder Interface Code

sleazyd

New Member
Just wanted to share my admittedly garbage rotary encoder code. If someone has anything better, please feel free to share:

Code:
Symbol ENC_A = Input7
Symbol ENC_B = Input6
Symbol ENC_INT_PIN = %10000000
Symbol ENC_INT_PASK = ENC_INT_PIN ^ $FF
Symbol Val = b1
Symbol ENC_UP = 2
Symbol ENC_DOWN = 1
Symbol ENC_OOPS = 0
Symbol LED = 0

Start:
    Val = 127
    SetFreq m8
    ' Chosen because 0-100% = 0 - 1023
    pwmout 3 , 255, 512
   
    ' Set the interrupt for the oposite edge
    b0 = ENC_A * ENC_INT_PIN
    b0 = b0 ^ ENC_INT_PIN
    SetInt b0, ENC_INT_PIN
   
MainLoop:
    Pause 50
    GoTo MainLoop

interrupt:   
    High LED
    If ENC_A = 1 Then
        if ENC_B = 1 Then
            Val = Val - 1
        Else
            Val = Val + 1
        EndIf
        SetInt 0, ENC_INT_PIN
    Else
        if ENC_B = 0 Then
            Val = Val - 1
        Else
            Val = Val + 1
        EndIf
        SetInt ENC_INT_PIN, ENC_INT_PIN
    EndIf
    W1 = 0
    b2 = Val
    W1 = W1 * 4
    pwmout 3 , 255, W1
    Low LED
    Return
I'm using an encoder that has a common and 2 pins that use a Gray code to pulse out the direction. Sparkfun has a similar one at http://www.sparkfun.com/commerce/product_info.php?products_id=9117. It's expecting the A/B inputs of the encoder on Input6 and Input7. This uses the pseudo Interrupts to get the data, setting them to goff a change on the 'A' pin. This means you're only getting 1/4 the resolution available, but the Picaxe was having a hell of a time keeping up when I tried a full quadrature decode.
 

westaust55

Moderator
Welcome to the PICAXE forum.

I assume that you have an 18X or 18M PICAXE chip ? :confused:

Others with a different PICAXE chip will need to change the pin used for the PWMOUT command.
 

sleazyd

New Member
Yes, it's an 18x. The PWMOut command was just so that I had some feedback that it was working. The general principle should work fine for anything that supports the StInt command.
 

boriz

Senior Member
This was my first attempt. Seems to work ok, but I can't help thinking there is a better way. (I seem to remember reading something about XOR).

Code:
#picaxe 14m
'quadrature encoding on pin0 and pin1
do
	do
		bit2=bit0:bit3=bit1
		bit0=pin0:bit1=pin1		
	loop until bit0<>bit2
	if b0=11 or b0=4 then
		inc b1
	elseif b0=1 or b0=14 then
		dec b1
	endif
	gosub update_display
loop
 
Top