Dynamic Variable Names Through Function

Hi All,

I have some code below that reads a push switch and registers the change.

I have the appropriate variables set up for 16 switches:

lastState_fs1, lastState_fs2 etc
outgoingTransmissionData.loopState_1, outgoingTransmissionData.loopState_2 and so on.

Obviously I can just copy and paste the code and change the switch number on each variable.

However it would be nice if I could wrap that up as a function rather than repeat it over and over for each of the 16 switches. eg

void readFootswitch(int switchNumber) {...........}

Is it possible to append a variable name?

eg lastState_fs(switchNumber)
&
bool fs(switchNumber)Read = digitalRead(footswitch_(switchNumber)_pin);

Cheers
Steve

bool fs1Read = digitalRead(footswitch_1_pin);

if (fs1Read == LOW) {lastState_fs1 = LOW; }

//filter out any noise by setting a time buffer
if ( (millis() - lastDebounceTime) > debounceDelay ) {

//if the button has been pressed
if ( fs1Read == HIGH && lastState_fs1 == LOW) {

  lastState_fs1 = HIGH;

  if (outgoingTransmissionData.loopState_1 == true) { 
    
      outgoingTransmissionData.loopState_1 = false;
      
      } else if (outgoingTransmissionData.loopState_1 == false) { 

          outgoingTransmissionData.loopState_1 = true;
  }

  dataChanged = true;

  lastDebounceTime = millis(); //set the current time
}

}

Variable names don't exit after you program is compiled. This sounds like a job for an array.

Something like this:

void readFootswitch(int switchNumber)
{
  bool fsRead = digitalRead(FootSwitchPins[switchNumber]);

  if (fsRead == LOW)
  {
    LastState_fs[switchNumber] = LOW;
  }

  //filter out any noise by setting a time buffer
  if ( (millis() - LastDebounceTime) > debounceDelay )
  {

    //if the button has been pressed
    if (fsRead == HIGH && LastState_fs[switchNumber] == LOW)
    {

      LastState_fs[switchNumber] = HIGH;

      if (outgoingTransmissionData.loopState[switchNumber] == true)
      {
        outgoingTransmissionData.loopState[switchNumber] = false;
      }
      else
      {
        outgoingTransmissionData.loopState[switchNumber] = true;
      }

      dataChanged = true;

      LastDebounceTime = millis(); //set the current time
    }
  }
}

Many thanks.
Steve

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