Setup of multiple MCP23017

Dear community,

I am new to the world of programing Arduino and connected two MCP23017 to my microcontroller using the slightly ameded interupt example code from the Adafruit MCP23xxx library which works perfectly fine. But I want to use 8 MCP23017 in the final project and am wondering if there is a way to put the following part into an array to use a loop for seting up each chip:

Adafruit_MCP23X17 mcp1;
Adafruit_MCP23X17 mcp2;

Using the wire.h library I used a for loop like this:

const uint8_t MCP_ADDRESSES[]={0x20, 0x21};

// set I/O pins to outputs
  for (int i=0; i<=sizeof MCP_ADDRESSES; i++) {
    MCP_CHIP = MCP_ADDRESSES[i];
    writeRegister(MCP_CHIP, MCP_IODIRA, 0b00000000);
    writeRegister(MCP_CHIP, MCP_IODIRB, 0b11111111);
    writeRegister(MCP_CHIP, MCP_GPPUB, 0b11111111);
  }

I would like to do the same with the Adafruit_MCP23017 library. Do you have a idea how to do it?

Thanks a lot in advance!

Best regards
BrainPaiN

I'm not sure if this is what you're looking for. I haven't studied those port expanders.

You can make use of structs or classes to combine related info. So you can combine an MCP object with an I2C address. Below to give you the idea.

#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))

#include <Adafruit_MCP23X08.h>
#include <Adafruit_MCP23X17.h>
//#include <Adafruit_MCP23XXX.h>

struct MCPINFO
{
  Adafruit_MCP23X17 mcp;
  uint8_t address;
};

MCPINFO mcps[]
{
  {Adafruit_MCP23X17(), 0x20},
  {Adafruit_MCP23X17(), 0x21},
};

void setup()
{
  for (uint8_t cnt = 0; cnt < NUMELEMENTS(mcps); cnt++)
  {
    mcps[cnt].mcp.begin_I2C();
    mcps[cnt].mcp.pinMode(somePin, OUTPUT);
  }
}

void loop()
{
}

I did not study the library to see if one can set a complete port in one go.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.