SPI GPIO Expander MCP23S08 Question

Hello,

I'm looking for some example code on how to get the MCP23S08 working on an Arduino. I know about the SPI library, but it seams there's a lot to setup prior to even starting to address the GPIO part of it. Like I/O direction, the pullup resistor states and so on.

I have the data sheet, but it's too confusing to me to figure this out.

If someone could share some example code of a simple blink example, where a pin is setup to be output and then switched high and low repeatedly, I'm sure I could figure out the rest from there.

I feel like this is something very basic and it should be easy, but I can't find anything on it when I search the web.

Thanks Rick

quick google and what you know... there's a library on github!

https://github.com/sumotoy/gpio_expander/tree/master/examples/_SPI/mcp23s08

Thank you! What did you search for? I searched for everything I could think of, and got nothing! I ended up figuring it out myself, at least on a really basic level using this code.

#include <SPI.h>

#define SS 10
#define CHIP 0x40
#define IO_DIR_REG 0x00
#define GPIO_REG 0x09

void SPIWrite(byte address, byte data){
  digitalWrite(SS,LOW);
  SPI.transfer(CHIP);
  SPI.transfer(address);
  SPI.transfer(data);
  digitalWrite(SS,HIGH);

}
void setup() {
  pinMode(SS,OUTPUT);
  digitalWrite(SS,HIGH);
  delay(100);
  SPI.begin();
  SPIWrite(IO_DIR_REG,0x00);
  SPIWrite(GPIO_REG,0x00);
 }

void loop() {
  // put your main code here, to run repeatedly:
  SPIWrite(GPIO_REG,0x02);
  delay(500);
  SPIWrite(GPIO_REG,0x00);
  delay(500);
}

Turns out that reading isn’t too bad either It is a little different from writing.

First off, the address you use is 1 higher. In the example above, it would be 0x41.

Second, you write the address of the chip, the address of the register, and then you write some dummy data. But you return that write statement. Something like this:

#include <SPI.h>

#define SS 10
#define CHIP 0x40
#define CHIP_READ 0x41
#define IO_DIR_REG 0x00
#define GPIO_REG 0x09

void SPIWrite(byte address, byte data){
 digitalWrite(SS,LOW);
 SPI.transfer(CHIP);
 SPI.transfer(address);
 SPI.transfer(data);
 digitalWrite(SS,HIGH);

}

byte SPIRead(byte address){
 digitalWrite(SS,LOW);
 SPI.transfer(CHIP_READ);
 SPI.transfer(address);
 byte retVal=SPI.transfer(0x00);
 digitalWrite(SS,HIGH);
 return retVal;
}

void setup() {
 Serial.begin();
 while (!Serial){}
 pinMode(SS,OUTPUT);
 digitalWrite(SS,HIGH);
 delay(100);
 SPI.begin();
 SPIWrite(IO_DIR_REG,0x00);
 SPIWrite(GPIO_REG,0x00);
}

void loop() {
 // put your main code here, to run repeatedly:
 SPIWrite(GPIO_REG,0x02);
 delay(500);
 SPIWrite(GPIO_REG,0x00);
 delay(500);

 Serial.println(SPIRead(GPIO_REG));
}