program encoder_A
' MCU: PIC16F877A
' Dev.Board: Myboard
' Oscillator: HS, 20.000 MHz
' Ext. Modules: trigger with CD4093, Lcd_2x16
'PROGRAM TO DETERMINE DIRECTION OF QUADRATURE ENCODER
DIM PORTB_OLD AS BYTE
DIM PORTB_NEW AS BYTE
dim count as byte
dim txt as string[3]
'USING A 2 BIT (QUADRATURE SYSTEM) THIS IS THE RULE:
'LOW BIT OF OLD VALUE IS ALWAYS EQUAL TO HIGH BIT OF NEW VALUE
'IF MOVING CLOCKWISE
'LOW BIT OF OLD VALUE DOES NOT EQUAL HIGH BIT OF NEW VALUE
'IF MOVING COUNTERCLOCKWISE
main:
'TRISA = 0 'RA0 LED WILL INDICATE CW; RA1 LED WILL INDICATE CCW
TRISB = %00000011 'RB0 and RB1 Inputs
TRISC = 0
PORTA = 0
PORTB = 0
LCD_init(PORTD) 'LCD su portD
LCD_out(1,1,"Numero impulsi:")
LCD_out(2,1,"Dir:")
PORTB_OLD = PORTB
my_direction:
PORTB_NEW = PORTB
IF PORTB_NEW XOR PORTB_OLD <> 0 THEN 'test for encoder change
IF (PORTB_NEW >> 1) = (PORTB_OLD AND 1) THEN
PORTC = 1 'CW DIRECTION
LCD_out(2,6,"I")
count = count-1
ELSE
PORTC = 0 'CCW DIRECTION
count = count+1
LCD_out(2,6,"A")
END IF
END IF
bytetostr(count,txt)
LCD_out(1,18,txt)
PORTB_OLD = PORTB_NEW
GOTO my_direction
end.