如何获取变量输入并将其附加到另一个变量?

时间:2014-03-10 17:04:13

标签: c arduino

我很难找到答案,主要是因为我不知道如何将问题正确地表达为简单的谷歌查询。这就是我想要做的事情:

用户输入一个数字,该数字附加到变量名称的末尾(参见底部)。

int enablePin1 =1;
int revPin1 = 2;
 int fwdPin1 =3;
 int enablePin2 = 4;
 int revPin = 5;
 int fwdPin2 = 6;
 int enablePin3 = 7;
 int revPin3 = 8;
 int fwdPin3 = 9;

int ch = Serial.read();

if (isDigit(ch)){
int selection = (ch - '0');

 setMotor (selection, 255, 0);
}

//User inputs a motor number between 1 -3. Below, 255 and 0 are speed & direction
//For example (2 , 255, 0)

//////////////////////HERE'S WHERE I NEED HELP...
//////////I want each (motorSelection) variable to be replaced with whatever 
 the user inputs, in this case, with 2, so that it is enablePin2, revPin2, fwdPin2.

 void setMotor1(int motorSelection, int speed, boolean reverse)
{
  analogWrite(enablePin(motorSelection), speed);
  digitalWrite(revPin(motorSelection), ! reverse);
  digitalWrite(fwdPin(motorSelection), reverse);
}

1 个答案:

答案 0 :(得分:0)

不可能完全按照您的描述进行操作。但是,您可以使用数组而不是编号变量来实现更大的目标:

static const int enablePin[3] = { 1, 4, 7 };
static const int revPin[3]    = { 2, 5, 8 };
static const int fwdPin[3]    = { 3, 6, 9 };

// ...
int ch = Serial.read();
if (ch >= '0' && ch <= '3') {
    int selection = ch - '0';

    analogWrite(enablePin[selection], speed);
    digitalWrite(revPin[selection],   !reverse);
    digitalWrite(fwdPin[selection],   reverse);
}