I2C LCD Address Auto detect


#1

I love using I2C LCD display on projects - they are pretty cheap and are useful for debugging or end user info and only use 2 I/O’s.
Typically I use something like this with a I2C backpack (https://www.dfrobot.com/product-135.html) or depending on the deals out there, get a basic LCD module and a separate I2C backpack and solder them together. The backpacks are often based on a PCF8574 or PCF8574A I2C to GPIO expander - and each has a different address range - PCF8574 (0x20-0x27), PCF8574A (0x38-0x3F). So I use this code to auto check which I have installed so I don’t have to edit code each time I get a new batch of LCDs

Add the LiquidCrystal_I2C_Spark library to your project

#include <LiquidCrystal_I2C_Spark.h>

define your display size

const int numLcdCols = 16;
const int numLcdrows = 2;
LiquidCrystal_I2C lcd(0x20,numLcdCols,numLcdrows);
void setup() {

    Wire.begin();
    Wire.beginTransmission(0x38);       // check for alternate address here
    if (Wire.endTransmission() == 0) {  // alt LCD found
        lcd = LiquidCrystal_I2C(0x38, numLcdCols, numLcdrows); // reinitialise lcd with new address
    }
    // if not found use lcd parameters defined in the constructor above
    
    lcd.init();                      // initialise the newly found lcd
    lcd.backlight();
    lcd.clear();
    lcd.print("Hello World!");

}

#2

Nice attempt :+1:

I’d just suggest some alternative solution that doesn’t already instantiate an object that may well become redundant soon after.

How about something like this

const uint8_t addresses[] = { 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,   
                              0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f };
LiquidCrystal_I2C *lcd;

void setup() {
  int i;
  Wire.begin();
  for(i = 0; i < sizeof(addresses); i++) {
    Wire.beginTransmission(addresses[i]);
    if (Wire.endTransmission() == 0) {
      lcd = new LiquidCrystal_I2C(addresses[i], numLcdCols, numLcdRows);
      lcd->init();                      // initialise the newly found lcd
      lcd->backlight();
      lcd->clear();
      lcd->print("Hello World!");
      break;
    }
  }
  if (i >= sizeof(addresses)) {
    Log.error("No display found");
  }
}

#3

@ScruffR - love your work! :joy: