$regfile = "2313def.dat" $crystal = 4000000 Config Sda = Portd.5 Config Scl = Portd.4 'default I2C speed Config I2cdelay = 5 'LED on this pin Config Pind.6 = Output 'Int from PCF8574 to Int0 pin Config Pind.2 = Input Config Int0 = Falling Config Lcd = 16 * 2 Config Lcdpin = Pin , Db4 = Portb.4 , Db5 = Portb.5 , Db6 = Portb.6 , Db7 = Portb.7 , E = Portb.3 , Rs = Portb.2 Config Lcdmode = Port Const Pcf8574write = &H40 Const Pcf8574read = &H41 'Optical encoder AB is on two low bits Const Optencmask = &B00000011 'Need to keep the B-bit Const Optencbmask = &B000000001 Dim Pcf8574input As Byte Dim Encoderval As Byte Dim Encounter As Integer Dim Oldbval As Byte Encounter = 0 Oldbval = 0 Cls Lcd "encounter:" On Int0 Pcfint 'Set PCF8574 to input, masked pins high (pull-up) I2cstart I2cwbyte Pcf8574write I2cwbyte Optencmask I2cstop Enable Interrupts Enable Int0 'Report encoder counter value in an otherwise 'empty main loop. 'Observe LED on Portd.6 : if it goes off or stays on, 'probably too many interrupts arrive Do Set Portd.6 Waitms 5 Locate 1 , 12 Lcd Encounter ; " " Reset Portd.6 Waitms 5 Loop 'PCF8574 interrupt routine Pcfint: 'read the input pins I2cstart I2cwbyte Pcf8574read I2crbyte Pcf8574input , Nack I2cstop 'mask to keep only encoder AB value Encoderval = Pcf8574input And Optencmask 'add old B value if it is 1 If Oldbval = 1 Then Encoderval = Encoderval + 4 End If '<2 or >5 means up, remainder means down If Encoderval < 2 Then Decr Encounter Elseif Encoderval > 5 Then Decr Encounter Else Incr Encounter End If 'keep value of B for next interrupt Oldbval = Pcf8574input And Optencbmask Return End