Hi,
This is cut and pasted from a larger program I have and this digested version is not tested so take it for what it is please. It's written for the 18F2431 so double check the pin assignments for the QEI module.
Again, no guarantees but I hope it serves as a starting point for you.Code:DEFINE HSER_RCSTA 90h 'USART receive status init. DEFINE HSER_TXSTA 24h 'USART transmit status init. DEFINE HSER_BAUD 57600 'Baudrate is 57600. ANSEL0 = 0 'All inputs as digital PortA = 0 PortB = 0 PortC = 0 TRISA = %11000 'QEI pins as inputs. TRISB = %00000000 TRISC = %10000000 'USART RX pin as input. QEICON = %00010100 'Setup QEI, 4X mode, reset on index. PosLow VAR BYTE 'Storage for the low byte of encoder count PosHigh VAR BYTE 'Storage for the high byte of encoder count PosTemp VAR BYTE 'Temporary storage for low byte of encder count Position VAR WORD 'Actual encoder position, 16bit word. CLEAR Main: Gosub GetPosition HSEROUT ["QEI Count: " , #Position, 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 the low byte. This 'is prevented by reading the low 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 = POSCNTL 'Get low byte again If PosLow - 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 END
/Henrik.




Bookmarks