16-Bit SPI I/O Expander
Hardware
If you need a fast and cheap way to add more (much more!) I/Os to your controller, here it is. For this little project I used the Microchip MCP23S17 SPI I/O-Expander on the hardware side of things.
The chip is available as PDIP, SOIC and SSOP package. I chose the SOIC version and designed a simple (one sided) PCB with EAGLE (download here).
The circuit diagram for this PCB


The etched, drilled and assembled board, but without mounted DIL-Switches for selecting the device adress (didn't have one).

With the MCP23S17 you can cascade up to eight of these devives on one SPI-CS line, you just have to set different device adresses for each MCP23S17 via the dip switch, in this way you can get up to 8*16 = 128 additional I/Os for your controller!

Makingthings software
We need two main functions to talk to the MCP23S17, one for writing values (MCP23S17_Write()) and one to read data from the chip via SPI (MCP23S17_Read()). But first we need to initialize the SPI subsystem (setting the SPI-Clock speed). After that we can start with setting up the MCP23S17 (define which IOs are inputs/ outputs and if and under what conditions to trigger a interrupt) this is done in SPI_portexpanderinit() ).
In case you want to use the interrupt functionality of the MCP23S17, keep in mind that you need to connect the interrupt output pin(s) to your controller and write a interrupt service routine. This is not implemented in this demo project (download here or below).
Now we can start using the I/O-Expander by reading values:
1
2
|
gpioa_value = MCP23S17_Read(MCP23S17, GPIOA); // or
gpiob_value = MCP23S17_Read(MCP23S17, GPIOB);
|
Or by writing values:
1
2
|
MCP23S17_Write(MCP23S17,GPIOA,0x00); // clear all outputs of GPIOA
MCP23S17_Write(MCP23S17,GPIOB,0xff); // set all outputs of GPIOB
|
Or if you want to set or reset only one specific GPIO pin:
1
2
|
setMCP23S17_GPIO(GPIOA, CMG_BKLGHT, 1, MCP23S17, &portA_status); // set
setMCP23S17_GPIO(GPIOA, CMG_BKLGHT, 0, MCP23S17, &portA_status); // reset
|
Reading a specific portpin:
1
|
getMCP23S17_GPIO(GPIOA, CMG_BKLGHT, MCP23S17);
|
The makingthings mcbuilder example project can be downloaded below.
Links:
MCP23S17 Datasheet
MCP23S17 Eagle Project Files
MCP23S17 Makingthings Project Files
|