#-------------------------------------------------------------------------------# # Name: 23017-2port-io-s-v103.py # # Purpose: 23017 Input and Output Simple GUI V1.03 # # GPIO-Library: RPi.GPIO 0.5.3a # # # # Author: Pridopia, James Clarke # # Website: www.Pridopia.co.uk # # # # Created: 17/09/2013 # #-------------------------------------------------------------------------------# import smbus, sys, getopt, time, os Bus = smbus.SMBus(1) def Read(Addr, Reg): Ret = Bus.read_byte_data(Addr, Reg) Ret = str( '{:08b}'.format( Ret ) ) return Ret def Write(Addr, Reg, Data): Bus.write_byte_data(Addr, Reg, Data) return 1 def main(): Write(0x21, 0x12, 0x00) # Reset the GPIO Pins Write(0x21, 0x13, 0x00) Write(0x22, 0x12, 0x00) # On both chips. Write(0x22, 0x13, 0x00) #Write(0x21, 0x03, 0xFF) # Reset the IPOLB to invert the input ( Supposed to... ) Write(0x21, 0x00, 0x00) # Now reset all the IODIRA and IODIRB to 0x00 Write(0x21, 0x01, 0x00) Write(0x22, 0x00, 0x00) Write(0x22, 0x01, 0x00) try: while True: os.system("clear") Write(0x21, 0x13, 0xFF) A = Read(0x21, 0x13) # The Input Address of the buttons ( We read directly from here ) A = int(A, 2) ^ 0xFF A = '{:08b}'.format(A) Bin = Read(0x21, 0x13) # The Output LED Address and Register. Bin2 = Bin # Save a spare set of the data to be used later to write to the reg Bin = 255 - int(Bin, 2) # Nice trick to reverse the Binary data E.g 0011 goes in, 1100 comes out Bin = '{:08b}'.format(Bin) # Format the Binary so that it includes all leading zeros B1 = Bin[0] B2 = Bin[1] B3 = Bin[2] B4 = Bin[3] B5 = Bin[4] B6 = Bin[5] B7 = Bin[6] B8 = Bin[7] print("Input test for MCP23017") print("\nInput Address: 0x21, Register 0x13" ) print("Input : [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s]" % (A[7], A[6], A[5], A[4], A[3], A[2], A[1], A[0]) ) print("\nOutput Address: 0x22, Register 0x13" ) print("Output: [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s]" % (B8, B7, B6, B5, B4, B3, B2, B1) ) Bin2 = 255 - int(Bin2, 2) Write(0x22, 0x12, Bin2 ) time.sleep(0.12) except KeyboardInterrupt: sys.exit() if __name__ == '__main__': main()