Esp32 zwei i2c Schnittstellen nutzen

Vielleicht ist es ja von allgemeinen Interesse, der Umgang mit 2 I2C Kanälen......
1/2 aus dem Beispiel und 1/2 aus meiner Wühlkiste

#include <Streaming.h> // die Lib findest du selber ;-)
Stream &cout = Serial; // cout Emulation für "Arme"
#include <Wire.h>

constexpr byte SDA_1 = 21;
constexpr byte SCL_1 = 22;
constexpr byte SDA_2 = 17;
constexpr byte SCL_2 = 16;
constexpr byte SDA_3 = 4;
constexpr byte SCL_3 = 3;
//constexpr unsigned long I2C_FREQ = 400000UL; // 5V fast
constexpr unsigned long I2C_FREQ = 100000UL; // 3.3V z.B. AT24C32

#if defined(ARDUINO_AVR_UNO)
  #include <SoftWire.h> // https://github.com/stevemarple/SoftWire
  TwoWire &wire0 = Wire;
  SoftWire wire1 {SDA_3, SCL_3};
#elif defined(ARDUINO_SAM_DUE)
  TwoWire &wire0 = Wire;
  TwoWire &wire1 = Wire1;
#elif defined(ARDUINO_ARCH_ESP32)
  TwoWire wire0 {0};
  TwoWire wire1 {1};
#else
 #error "Board unbekannt"  
#endif


template<class WireType >void scan(WireType &wire, Print &print)
{
  print << F("Scanning I2C Addresses") << endl;
  uint8_t cnt = 0;
  for(uint8_t i = 0; i < 128; i++)
  {
    wire.beginTransmission(i);
    uint8_t result = wire.endTransmission(true);
    // print << endl << result << endl;
    if(result) 
    {
      print << F("..");
    }
    else 
    {
      if(i < 16)  print << '0';
      print << _HEX(i) ;
      cnt++;
    }
    print << F(" ");
    if ((i & 0x0f) == 0x0f) print << endl;
  }
  print << F("Scan Completed, ") << cnt << F(" I2C Devices found.") << endl;
}

void setup()
{
  Serial.begin(9600);
#if defined(ARDUINO_AVR_UNO)
  Wire.begin();
  Wire.setClock(I2C_FREQ);
  wire1.setTimeout_ms(200);
  wire1.begin();
#elif defined(ARDUINO_SAM_DUE)
  Wire.begin();
  Wire.setClock(I2C_FREQ);
  Wire1.begin();
  Wire1.setClock(I2C_FREQ);
#elif defined(ARDUINO_ARCH_ESP32) 
  wire0.begin(SDA_1, SCL_1, I2C_FREQ);
  wire1.begin(SDA_2, SCL_2, I2C_FREQ);
#else
 #error "Board unbekannt"  
#endif
}

void loop()
{
    cout << endl << F(" -> scan wire0 ") << endl << endl;
    scan(wire0,Serial);
  
    cout << F(" -> scan wire1 ") << endl;
    scan(wire1,Serial);
  
  delay(2000);
}
1 Like