Here I have a sample code for rotary encoder using two Timer modules in counter mode.
Reference Signal of encoder is connected to Timer0, and one of pulse signals is connected to Timer1.
Code:
'Edit: the code is for 16F877-20Mhz.
@ DEVICE PIC16F877, HS_OSC
@ DEVICE PIC16F877, WDT_ON
@ DEVICE PIC16F877, PROTECT_OFF
@ DEVICE PIC16F877, CPD_OFF
@ DEVICE PIC16F877, PWRT_ON
@ DEVICE PIC16F877, BOD_ON
DEFINE OSC 20
'=======Add tris registers here... =========
'I skipped the part where you need to set your registers.....
'..
'...
'....
'========Timer0 Settings - 8bit===================
OPTION_REG = %00111000
' Set 1:1 prescaler & assign to WDT
' Set TMR0 clock to external input on RA4/T0CKI.
' Connect Rerefence signal of encoder to this pin.
' Increment on high-to-low transition on RA4/T0CKI pin
'=====Timer1 settings - 16Bit ====================
T1CON = %00000111 ' 1:1 in counter mode.
'RC0 = Encoder input (RC0/T1OSO/T1CKI (on rising edge).
'Connect One of the pulse signals of encoder to this pin.)
INTCON.7 = 0 ' Disable interrupts
Encoder var word
RefPoint var word
RefBit var word
TourNo var word
Encoder = 0
TMR1L = 0 ' Clear TMR counter
TMR1H = 0
Refpoint = 0
Refbit = 0
TMR0 = 0
Tourno = 0
Start:
LCDOUT $fe,1,"Encoder:",DEC4 Encoder
LCDOUT $fe,$c0,"Tour :",DEC4 Tourno
Encoder.highbyte = TMR1H 'Load Lower byte of Timer1.
Encoder.lowbyte = TMR1L 'Load Higher byte of Timer1.
Refpoint = TMR0 'Load TMRO value.
if Refbit + 1 = Refpoint then ' Check: Do we have an increment?If yes, then
Tourno = Tourno + 1 ' Add up tour numbers.
TMR1H = 0 ' Since the encoder completed one tour, clear timer1 Lower byte.
TMR1L = 0 ' Since the encoder completed one tour, clear timer1 Higher byte.
Encoder = 0 ' Since the encoder completed one tour, clear timer1 holder, too.
endif
RefBit = Refpoint ' Make eqaul before the next TMR0 assignment
Goto start
Bookmarks