I2C and Arduino IoT Cloud

It took me several days and lots of experimentation to successfully communicate using I2C between devices while connected to the cloud. Maybe this will help someone else. This isn't an original idea since the code was copied from other posts, but I didn't see this information in the documentation.

void setup() {
//other code

  //callback to delay I2C initalization until after the connected to ArduinoCloud
  ArduinoCloud.addCallback(ArduinoIoTCloudEvent::CONNECT, onIoTConnect);
  ArduinoCloud.addCallback(ArduinoIoTCloudEvent::DISCONNECT, onIoTDisconnect);

}

Functions:

void onIoTConnect() {
  // enable i2c devices
  Serial.println(">>> connected to Arduino IoT Cloud");
  Wire.begin(9); 
  Wire.onReceive(receiveEvent);
}

void onIoTDisconnect() {
  // disable i2c devices
  Serial.println(">>> DISCONNECTED from Arduino IoT Cloud");
  Wire.end();
}

I too am having difficulties using I2C devices with Arduino cloud. I see you added the callbacks as others have stated, but what I am not seeing is how, or if "wire.h" is being included or used. Does the Arduino cloud use a different library? When I try to include wire.h I get errors.

I was able to compile without using wire.begin(), but there is no communication with the Cloud after the initial connection.

Thank you for any info you (or anyone else) can provide. :wink:

Thank you jcgam for the consolidation of information. I've found that your solution works but I'd like to add some clarification and expansion.

When IOT connects, the callback is fired and Wire is initialized. That is great. The clarification is that after Wire is initialized, we just need to do whatever it is that needs to be done to initialized I2C. In my case, I just need to initialize a library that does the I2C work for me.

A stripped down example using the Adafruit_PCF8575 library (the PCF8575 uses I2C) is as follows:

#include <Adafruit_PCF8575.h>
Adafruit_PCF8575 pcf;
volatile bool pcfInitialized = false;
void setup() {
  ArduinoCloud.addCallback(ArduinoIoTCloudEvent::CONNECT, onIoTConnect);
  ArduinoCloud.addCallback(ArduinoIoTCloudEvent::DISCONNECT, onIoTDisconnect);
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  ArduinoCloud.printDebugInfo();
}
void onIoTConnect() {
  // enable i2c devices
  Serial.println(">>> connected to Arduino IoT Cloud");
  Wire.begin(); 
  if (!pcf.begin(0x20, &Wire)) {
    Serial.println("Couldn't find PCF8575");
  } else {
    pcfInitialized = true;
  }
  pcf.pinMode(0, INPUT_PULLUP);
}

void onIoTDisconnect() {
  // disable i2c devices
  Serial.println(">>> DISCONNECTED from Arduino IoT Cloud");
  Wire.end();
  pcfInitialized = false;
}

loop() {
  ArduinoCloud.update();
  if (pcfInitialized) {
    if (! pcf.digitalRead(0)) {
        Serial.print("Button on GPIO 0 pressed");
    }
    delay(10); // a short debounce delay
  }
}