Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c++ - How can I use a changing int value to call different functions on an Arduino?

I am programming (kind of) a stopwatch with start buttons and a 4-digit seven-segment LED display on my Arduino Uno.

With functions like this one I can put numbers on the SevSeg without problems:

void Zahl_1()
{
  digitalWrite(6, LOW);
  digitalWrite(7, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
}

By clicking a button a can start the clock (numbers are stored in int sekunden) and Serialprint does give me the right numbers counting up.

My problem lies in between both; I cant link for example (sekunden == 1) to Zahl_1().

I tried it this way with no success:

void Sek()
{
  if (sekunden == 0)
  {
    Zahl_0;  //
  }
  if (sekunden == 1)
  {
    Zahl_1;
  }
  if (sekunden == 2)
  {
    Zahl_2;
  }
  if (sekunden == 3)
  {
    Zahl_3;
  }
  if (sekunden == 4)
  {
    Zahl_4;
  }
  if (sekunden == 5)
  {
    Zahl_5;
  }
  if (sekunden == 6)
  {
    Zahl_6;
  }
  if (sekunden == 7)
  {
    Zahl_7;
  }
  if (sekunden == 8)
  {
    Zahl_8;
  }
  if (sekunden == 9)
  {
    Zahl_9;
  }
}

Any ideas on how to get this working without having to rewrite the whole program?

Thanks in advance!

Best regards

bamm

question from:https://stackoverflow.com/questions/66050455/how-can-i-use-a-changing-int-value-to-call-different-functions-on-an-arduino

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem here is you're not calling any function. To call a function you do:

function();

In your example you are missing the parentheses.

Another thing I want to point out is your use of if statements. It's more efficient and a better practice to use switch statements when doing stuff depending on the value of a variable.

Example:

switch (sekunden) {
  case 0:
    Zahl_0();
    break;
  case 1:
    Zahl_1();
    break;
  case 2:
    Zahl_2();
    break;
  default:
    println("Nothing matches");
    break;
}

More info here: Switch case structure


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...