Minor refactor I2C

This commit is contained in:
Theo Arends 2024-09-15 15:16:18 +02:00
parent a3892ecbc4
commit c61dd0fd2c
3 changed files with 14 additions and 23 deletions

View File

@ -20,36 +20,29 @@ uint32_t i2c_active[2][4] = { 0 };
#endif
uint32_t i2c_buffer = 0;
bool I2cBegin(int sda, int scl, uint32_t frequency = 100000);
bool I2cBegin(int sda, int scl, uint32_t frequency) {
bool I2cBegin(int sda, int scl, uint32_t bus = 0, uint32_t frequency = 100000);
bool I2cBegin(int sda, int scl, uint32_t bus, uint32_t frequency) {
bool result = true;
#ifdef ESP8266
Wire.begin(sda, scl);
Wire.setClock(frequency);
#endif
#ifdef ESP32
static bool reinit = false;
if (reinit) { Wire.end(); }
result = Wire.begin(sda, scl, frequency);
TwoWire& myWire = (0 == bus) ? Wire : Wire1;
if (reinit) { myWire.end(); }
result = myWire.begin(sda, scl, frequency);
reinit = result;
#endif
// AddLog(LOG_LEVEL_DEBUG, PSTR("I2C: Bus1 %d"), result);
// AddLog(LOG_LEVEL_DEBUG, PSTR("I2C: Bus%d %d"), bus +1, result);
return result;
}
#ifdef ESP32
bool I2c2Begin(int sda, int scl, uint32_t frequency = 100000);
bool I2c2Begin(int sda, int scl, uint32_t frequency) {
bool result = Wire1.begin(sda, scl, frequency);
// AddLog(LOG_LEVEL_DEBUG, PSTR("I2C: Bus2 %d"), result);
return result;
}
#endif
TwoWire& I2cGetWire(uint8_t bus = 0) {
if (!bus && TasmotaGlobal.i2c_enabled) {
if ((0 == bus) && TasmotaGlobal.i2c_enabled) {
return Wire;
#ifdef ESP32
} else if (bus && TasmotaGlobal.i2c_enabled_2) {
} else if ((1 == bus) && TasmotaGlobal.i2c_enabled_2) {
return Wire1;
#endif // ESP32
} else {

View File

@ -2232,8 +2232,7 @@ void GpioInit(void)
}
#ifdef USE_I2C
TasmotaGlobal.i2c_enabled = (PinUsed(GPIO_I2C_SCL) && PinUsed(GPIO_I2C_SDA));
if (TasmotaGlobal.i2c_enabled) {
if (PinUsed(GPIO_I2C_SCL) && PinUsed(GPIO_I2C_SDA)) {
TasmotaGlobal.i2c_enabled = I2cBegin(Pin(GPIO_I2C_SDA), Pin(GPIO_I2C_SCL));
#ifdef ESP32
if (TasmotaGlobal.i2c_enabled) {
@ -2242,9 +2241,8 @@ void GpioInit(void)
#endif
}
#ifdef ESP32
TasmotaGlobal.i2c_enabled_2 = (PinUsed(GPIO_I2C_SCL, 1) && PinUsed(GPIO_I2C_SDA, 1));
if (TasmotaGlobal.i2c_enabled_2) {
TasmotaGlobal.i2c_enabled_2 = I2c2Begin(Pin(GPIO_I2C_SDA, 1), Pin(GPIO_I2C_SCL, 1));
if (PinUsed(GPIO_I2C_SCL, 1) && PinUsed(GPIO_I2C_SDA, 1)) {
TasmotaGlobal.i2c_enabled_2 = I2cBegin(Pin(GPIO_I2C_SDA, 1), Pin(GPIO_I2C_SCL, 1), 1);
if (TasmotaGlobal.i2c_enabled_2) {
AddLog(LOG_LEVEL_INFO, PSTR("I2C: Bus2 using GPIO%02d(SCL) and GPIO%02d(SDA)"), Pin(GPIO_I2C_SCL, 1), Pin(GPIO_I2C_SDA, 1));
}

View File

@ -183,7 +183,7 @@ Renderer *Init_uDisplay(const char *desc) {
#ifdef ESP32
if (wire_n == 1) {
if (!TasmotaGlobal.i2c_enabled_2) {
I2c2Begin(sda, scl);
I2cBegin(sda, scl, 1);
}
}
#endif // ESP32
@ -377,7 +377,7 @@ Renderer *Init_uDisplay(const char *desc) {
#ifdef ESP32
if (wire_n == 1) {
if (!TasmotaGlobal.i2c_enabled_2) {
I2c2Begin(sda, scl, 400000);
I2cBegin(sda, scl, 1, 400000);
}
}
#endif // ESP32