Introduction
The MCP23S17 is a SPI Based Port Expander which can add 16 more digital I/O pins to your Arduino or Raspberry Pi. Thanks to the wide operating voltage of 1.8 – 5.5V, you can add 5V I/O pins to the Raspberry Pi or 3.3V based Arduino thereby avoiding a level shifter and simplifying connections.
Hardware Required:
Board Overview
The board consists of 2 Port Banks (A and B), a 3-way switch, power and SPI headers
3-Way switch is used to set the address of the Port Expander, the switch positioned towards ON sets the address as ‘0’. The image above sets the address as ‘7’
INT B Interrupt output for PortB
B.0 – B.7 Bidirectional I/O
INT A Interrupt output for PortA
A.0 – A.7 Bidirectional I/O
VCC Power supply pin for the MCP23S17, connect to a voltage source between 1.8V -5V
GND connect to ground of power supply
SO, SI, SCK & CS SPI Pins
RESET connect to ground to reset the port expander
Note: The silkscreen on Port A is reversed, meaning INT A actually is A.7 and A.7 actually is INT A
Enabling SPI on the Raspberry Pi
By default the SPI peripheral is not enabled, we cannot continue unless this is done first. Have a look at the tutorial by SparkFun on how to do this.
Interfacing the MCP23S17 Port Expander with the Raspberry Pi
Connections from Raspberry Pi to MCP23S17 Port Expander
MCP23S17 Pin | Raspberry Pi GPIO Pin |
---|---|
VCC | 5V/3.3V |
GND | GND |
SO | SPI_MISO / GPIO9 / Pin 21 |
SI | SPI_MOSI / GPIO10 / Pin 19 |
SCK | SPI_CLK / GPIO11 / Pin 23 |
CS | SPI_CE0_N / GPIO8 / Pin 24 |
Installing the Python Library
In order to get started the python library needs to be installed first. Run the following command in terminal to install the library
sudo pip install RPiMCP23S17
Sample Code
The below code will turn ON and OFF all the pins at an interval of 1 second.
from RPiMCP23S17.MCP23S17 import MCP23S17 import time mcp = MCP23S17(bus=0x00, ce=0x00, deviceID=0x00) mcp.open() for x in range(0, 16): mcp.setDirection(x, mcp.DIR_OUTPUT) print "Starting blinky on all pins (CTRL+C to quit)" while (True): for x in range(0, 16): mcp.digitalWrite(x, MCP23S17.LEVEL_HIGH) time.sleep(1) for x in range(0, 16): mcp.digitalWrite(x, MCP23S17.LEVEL_LOW) time.sleep(1)