MCP23S17 Raspberry Pi Port Expender

Sometimes, we required to use a lot of I/O for our application.

MCP23S17 is a great choice since it have 16 I/O (16 bits) can be configured as input or output. It also have interrupt function for checking the triggered input.

In this tutorial, I am going to show the step on how to install library for MCP23S17. The program on read input and write outputs also will be presented.

Installed Library

  • Open the terminal and type:
sudo apt-get install python-dev python-pip
sudo pip3 install RPiMCP23S17
  • Enable the SPI interface from raspberry pi configuration.
  • Set the SPI clock of raspberry pi to 10Mhz. This can be done by modify the library MCP23S17.py that located in /usr/local/lib/python3.7/dist-packages/RPiMCP23S17. Add a line :  in function “def open(self):”    “self._spi.max_speed_hz = 10000000 # 10Mhz”. But before that you need to enable the files so that you can write/edit on it.
  • Cd to that files and run this command:
    sudo chmod 777 RPiMCP23S17.py

  • Install the libray of bitstring by type :
sudo pip3 install bitstring

Program for Read Input

#!/usr/bin/env python3
from RPiMCP23S17.MCP23S17 import MCP23S17
import time
from bitstring import BitArray

mcp = MCP23S17(bus=0x00, pin_cs=0x00, device_id=0x00)
mcp.open()
mcp._writeRegister(0x0A,0x68)
mcp._writeRegister(0x04,0xFF)
mcp._writeRegister(0x05,0xFF)

def ZeroPad(array):
for x in range(array.len,8):
array.prepend(‘0b0’)
return array

def ReadGPIO():
BankA = ZeroPad(BitArray(bin(mcp._readRegister(0x12))))
BankB = ZeroPad(BitArray(bin(mcp._readRegister(0x13))))
print(BankA.bin) # show read pins for GPA0 until GPA7
print(BankB.bin) # show read pins for GPB0 until GPB7
BankB.append(BankA)
print(BankB.bin)

ReadGPIO()

 

Program for Write Output

#!/usr/bin/env python3
from RPiMCP23S17.MCP23S17 import MCP23S17
import time
from bitstring import BitArray

mcp = MCP23S17(bus=0x00, pin_cs=0x00, device_id=0x00)
mcp.open()
mcp._writeRegister(0x0A,0x68)
mcp._writeRegister(0x04,0xFF)
mcp._writeRegister(0x05,0xFF)

def ZeroPad(array):
for x in range(array.len,8):
array.prepend(‘0b0’)
return array

def ReadGPIO():
BankA = ZeroPad(BitArray(bin(mcp._readRegister(0x12))))
BankB = ZeroPad(BitArray(bin(mcp._readRegister(0x13))))
print(BankA.bin) # show read pins for GPA0 until GPA7
print(BankB.bin) # show read pins for GPB0 until GPB7
BankB.append(BankA)
print(BankB.bin)

ReadGPIO()

for x in range(0, 16):
mcp.setDirection(x,mcp.DIR_OUTPUT)

while (True):
mcp.digitalWrite(14, 0) # GBP6 (bit 14) is LOW
mcp.digitalWrite(15, 1) # GBP7 (bit 15) is HIGH
time.sleep(1)
mcp.digitalWrite(14, 1) # GBP6 (bit 14) is HIGH
mcp.digitalWrite(15, 0) # GBP7 (bit 15) is LOW
time.sleep(1)