Interfacing with a PCF8574 8-bit I/O Expander (I2C)


' PCF8574.Bas (BASICX)
'
' Illustrates control of a Phillips 8574 I2C 8-Bit I/O Expander.  This
' is useful in expanding the IO capability of the BasicX-1 or BX24. 
'
' Flashes LED on Pin4 (P0) of the 8574 if the switch at pin 12 (P7) of 
' 8574 is at zero.
'
' SCL_PIN (term 2 on BASICX) ----------- SCL (term 14) ----- To Other
' SDA_PIN (term 3 on BASICX)------------ SDA (term 15) ----- I2C Devices
'
' The manufacturer's device code for this device is 0100.
'
' Note that the secondary address is determined by the strapping of A2 
' (term 3), A1 (term2) and A0 (term 1) on the 8574. In this example, 
' A2, A1 and A0 are strapped to ground.  
'
' The above SCL and SDA leads may be multipled to eight PCF8574 devices, 
' each strapped for a unique A2, A1, A0.
'
' Pullup resistors to +5VDC are required on both SDA and SCL
' signal leads.
'
' Note that LED on P0 of the 8574 is turned on when P0 is at a logic zero.
'
' Compile with I2C.BAS and SerialPort.BAS.
'
' copyright, Peter H. Anderson and David Seebold, Baltimore, MD, Oct, '99

Sub Main()

   Dim y as byte

   Call out_patt(&H40, &H00, &H80, &H7f)
   ' dev_code = &H40, address = 0, dirs = &H80, patt = &H7f

   Do
      Call in_patt(&H41, &H00, y) 	' read inputs

      If (y AND &H80 = 0) Then          ' if switch at pin 12(P7)==0
					' ie, the switch is closed to
                                        ' ground, then turn off LED
					' on P0
         Call out_patt(&H40, &H00, &H80, &H7f)  
    
      Else	  		      		' flash the LED on time
         Call out_patt(&H40, &H00, &H80, &H7e)  ' turn the LED on
         Call Sleep(0.5)
         Call out_patt(&H40, &H00, &H80, &H7f)  ' turn it off
         Call Sleep(0.5)
      End If
   Loop

End Sub

'---------

Sub in_patt(ByVal dev_code as Byte, _
            ByVal adr as Byte, byRef y as byte)
' reads a byte from the PCF8574 into y

   Call i2c_start()
   Call i2c_out_byte(dev_code + (adr * 2))
   Call i2c_nack()
   Call i2c_in_byte(y)
   Call i2c_stop()
   
End Sub

'---------

Sub out_patt(ByVal dev_code as Byte, ByVal adr as Byte, _
  	     ByVal dirs as Byte, ByVal patt as Byte)
' writes patt to PCF8574
   Call i2c_start()
   Call i2c_out_byte(dev_code + (adr * 2))
   Call i2c_nack()
   Call i2c_out_byte(dirs OR patt)	' keep inputs defined by dirs
					' at one
   Call i2c_nack()
   Call i2c_stop()

End Sub