Hi,
This works for me on 18F2431, should be the same. Don't forget to set the QEA, QEB & QEI pins to inputs.
Code:
QEICON = %00010100 'Setup QEI, 4X mode, reset on indexpulse.
PosHigh var BYTE
PosLow var BYTE
PosTemp var BYTE
Position var WORD 'Motor position in encoder counts.
Main:
Gosub GetPosition
HSEROUT [#Position,13,10]
Pause 100
Goto Main
GetPosition:
'Since the position counter isn't double buffered we can get to situations
'where the lowbyte overflows between readings of the high and low byte. This
'is prevented by reading the high byte two times and compare the two readings.
'If they are the same then we're fine, if not re-read the registers.
PosHigh = POSCNTH 'Get high byte of counter
PosLow = POSCNTL 'Get low byte of counter
PosTemp = POSCNTH 'Get high byte again
If PosHigh - PosTemp = 0 then Goto Done 'Compare, if equal we're done.
PosHigh = POSCNTH 'If not, get values again.
PosLow = POSCNTL
Done:
Position = PosHigh * 256 + PosLow 'Put high and lowbyte together.
RETURN
/Henrik Olsson.
Bookmarks