Pass a variable name to use in a function?

I want to use one function to display a time on one of multiple seven segment displays but i'm not sure how to specify which display..

something like (not real code):

displayTime(sevenSegOne, 1234);

void displayTime( displayName , displayTime ) {
 displayName.writeDigitNum(0, displayTime);

How should I be going about this?

With a pointer or a reference.

Welcome to the forum

You cannot pass the name of a variable to a function because after the code is compiled the names have to meaning

What you do is to pass the value of a variable to a function and use the value in the function

Try this example

void setup()

void loop()

void action(char *name)
  if (strcmp(name, "displayA") == 0)
    Serial.println("do something with displayA");
  else if (strcmp(name, "displayB") == 0)
    Serial.println("do something with displayB");
    Serial.println(" not recognised");

thanks - ok.. so if I have a lot (but identical) for each to do, i would have to copy and paste for each display.. if I had 100 for example - perhaps there is a more sensible way to do what i want?

In reality I only have 2 so not a huge deal to do it like that, but it doesn't feel right..

for context, I am making a chess clock, so I want to say "write this time to display 1 and write this other time to display 2"

You should post some information how the two displays are connected to the microcontroller.

How an elegant to use code will look like depends on that.

For example if you have two displays connected by I2C-bus. The two displays would be configured to use different I2C-bus-adresses and then selecting the display is reduced to select the I2C-adress.

If all elements of each display are connected through singular wires using arrays for all the IO-pins would be effective.

best regards Stefan

If you had hundreds of displays then you would put the data about each of them in an array and iterate through that array rather than having hundreds of if statements to determine which one you are dealing with

ah ok - yes it's using I2C

Like this:

#include <Foo.h>
Foo sevenSegOne;
Foo sevenSegTwo;
Foo sevenSegThree;

displayTime(sevenSegOne, 1234);
displayTime(sevenSegTwo, 1234);
displayTime(sevenSegThree, 1234);

void displayTime( Foo display , int displayTime ) 
  display.writeDigitNum(0, (displayTime / 1000) % 10);
  display.writeDigitNum(1, (displayTime / 100) % 10);
  display.writeDigitNum(2, (displayTime / 10) % 10);
  display.writeDigitNum(3, displayTime % 10);

It's probably better to pass a reference:

void displayTime( Foo &display , int displayTime ) 

hey, thanks!

works great.

Can't say I'm 100% on the mechanics at play but I think I have enough to make it work.

thanks all!

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