How can I discover attached motor shields in code?
If you configure each I2C device to have a unique address, then it's easy to determine which ones are connected.

This sketch is derived from the I2C Scanner sketch found here: I2cScanner

// This sketch tests the standard 7-bit addresses.
// Devices with higher bit address might not be seen properly.
#include &lt;Wire.h&gt;
byte shieldOneAddress = 0x27;
byte shieldTwoAddress = 0x32;
byte error, address;

void setup(){

  Wire.begin();
  Serial.begin(9600);
  Serial.println("Scanning for shields...");

  for(address = 1; address &lt; 127; address++){

    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if(error == 0){
      if(address == shieldOneAddress){
        Serial.println("Shield One is connected.");
      }
      if(address == shieldTwoAddress){
        Serial.println("Shield Two is connected.");
      }
    }

  }
  Serial.println("Scan complete.\n");
}

void loop(){}