0

I wonder how I can address a variable by putting together a string and an int in Arduino. I´m using many variables of the same type and with almost the same name. I´m just append a number to each variable. The names of the variables are e.g. int sensorValue_1; int sensorValue_2; and so on. I´d like to write less because my code is becoming too long. When addressing the variables, I´d like to write something like this: sensorValue_[+ intVariable];

Here is an example of what I mean:

int sensorIndex_1 = 1;
int sensorIndex_2 = 2;
int sensorIndex_3 = 3;

int sensorValue_1;
int sensorValue_2;
int sensorValue_3;


void setup()
{
  Serial.begin(9600);
}

void loop()
{
  doSomething(sensorIndex_1);
//doSomething(sensorIndex_2);
//doSomething(sensorIndex_3);
}

void doSomething(int sensorIndex)
{
  if(sensorIndex == 1)
  {
    Serial.print("Sensor 1: ");
    sensorValue_1 = analogRead(A1);
    Serial.println(sensorValue_1);
  }

  if(sensorIndex == 2)
  {
    Serial.print("Sensor 2: ");
    sensorValue_2 = analogRead(A2);
    Serial.println(sensorValue_2);
  }

  if(sensorIndex == 3)
  {
    Serial.print("Sensor 3: ");
    sensorValue_3 = analogRead(A3);
    Serial.println(sensorValue_3);
  }

  delay(1000);
}  

And I want to shorten the code in the doSomething() method. I want to have something like this: Notice the "[+ sensorIndex]"

void doSomething(int sensorIndex)
{
  Serial.print("Sensor [+ sensorIndex]: ");
  sensorValue_[+ sensorIndex] = analogRead(A[+ sensorIndex]);
  Serial.println(sensorValue_[+ sensorIndex]);

  delay(1000);
}  

By the way: I´d like to avoid for-loops, if possible. In my case, the code would become too complicated.
How do I manage this?

2 Answers 2

2

User2461391 has a great start but the rest of the puzzle I think you want is:

int array1[3];
int array2[3];
int arrayx[3];


void setup()
{
}

void loop()
{
   int index=1;

   array1[2]=doSomething(2);
   arrayx[index]=doSomething(index);
   Serial.print("Sensor ");
   Serial.print(index);
   Serial.print(": ");
   Serial.println(arrayx[index]);         

   while(1);
}

int doSomething(int sensorIndex) // It probably makes more sense to return the value
{         
      return  (analogRead(sensorIndex));
}  
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use A1 and A2 and the likes to define the analog pin you want to read. Just 1 or 2 will do.

void doSomething(int sensorIndex)
{
      Serial.print("Sensor ");
      Serial.print(sensorIndex);
      Serial.print(": ");
      sensorValue = analogRead(sensorIndex);
      Serial.println(sensorValue);

      delay(1000);
}  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.