How to build a function for driving multiple LCDs and using LCDs object name as argument?

Hi,

I'm trying to code a sketch to write data to four LCD screen using LiquidCrystal I2C. I want to have only one fucntion for the four LCD, so I need to find a way to pass lcd1.xxxx(xx,xx), lcd2.xxxx(xx.xx), etc. as arguments so data are printed to the selected screen.

That way I can switch easily data to be print from one LCD to another. I could write a function for each LCD, but I'm trying to simplify the process...

I'm not yet really familiar with pointers, I don't know if it would be the way to do it or somthing else. Is it possible to define a char pointer to define the LCD object name and using it in my function to complete the function call ? I mean its only in "lcdx.print()" or "lcdx.SetCursor(xx,xx)", its only the "lcdx" that need to be corrected in my function...

Any help or guidance would be welcome !

Here's a simple way

// https://wokwi.com/projects/359323056854506497

# include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
LiquidCrystal lcdToo(A0, A1, A2, A3, A4, A5);

void setup() {
  lcd.begin(16, 2);
  lcdToo.begin(16, 2);

// you can now interact with the LCDs, e.g.:
//  lcd.print("Hello World!");
//  lcdToo.print("GOOD BYE!");

  function(&lcd, "Hello There!");
  function(&lcdToo, "Goodbye.");  
}

void loop() {

}

void function(LiquidCrystal *theDevice, char *msg)
{
//  theDevice->print(msg); // or

  (*theDevice).print(msg);
}

See it in the simulator


Also in the simulator you will a few different versions of doing the same basic thing. You can make an array of LCDs which might work better, and eliminate the need for explicit use of pointers, as now each LCD would be reached by index from 0 to N - 1 rather than your idea of cobbling together the name. Which is harder to do in C/C++ than it would be worth in this case probably.

HTH

a7

1 Like

Here's one that only uses an array, then indexes. I gave the numbers 0 and 1 names to use in the code

// https://wokwi.com/projects/359324205057887233

# include <LiquidCrystal.h>

enum {A_DISPLAY = 0, B_DISPLAY};

LiquidCrystal lcdArray[2]  = {
  {12, 11, 10, 9, 8, 7},
  {A0, A1, A2, A3, A4, A5},
};

void setup() {
  lcdArray[A_DISPLAY].begin(16, 2);
  lcdArray[B_DISPLAY].begin(16, 2);

  // you can now interact with the LCD, e.g.:
//  lcd.print("Hello World!");
//  lcdToo.print("GOOD BYE!");

  function(A_DISPLAY, "Hello There!");
  function(B_DISPLAY, "Goodbye.");
  
}

void loop() {
}

void function(int displayNumber, char *msg)
{
  lcdArray[displayNumber].print(msg);
}

Name function() better. :expressionless:

a7

1 Like

Exactly what I was looking for ! Still learning every day! The array version is so simple. I think i've just unlock a lot of dead ends in my previous projects with that.

Thanks a lot !

Samuel

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.