c++ - 在 Arduino UNO 编程中,当您希望同时执行不同的功能时,使用什么代码/语句?

标签 c++ arduino arduino-uno arduino-c++

我想同时在 Arduino UNO 中执行一个简单的循环,但我不知道使用什么语句/代码可以同时执行它。

我已经尝试了 while 循环并且有时间包括开始。但是由于函数在循环中是相互分离的。 led的执行是不同方向的第一个功能和第二个功能。但我希望它们同时执行。


void loop() {
  // loop from the highest pin to the lowest:
  for (int thisPin = 2; thisPin >= 0; thisPin--) {
    // turn the pin on:
    digitalWrite(ledPins[thisPin], HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(ledPins[thisPin], LOW);
  }


  // loop from the lowest pin to the highest:
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    // turn the pin on:
    digitalWrite(ledPins[thisPin], HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(ledPins[thisPin], LOW);

  }


}

原来是在function中从最高pin到最低pin执行的。然后,最低引脚到最高引脚。而不是同时执行。

最佳答案

Arduino 没有通常的并行运行任务的能力(它没有多线程)。但是,有一些解决方法。参见 https://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads了解更多详情。

幸运的是,在您的情况下,您不需要并行运行循环。您可以通过同时转动相对侧的引脚来在一个循环中重新考虑您的算法。像这样:

for (int i = 0; i < pinCount; ++i) {
    // turn the pins on:
    digitalWrite(ledPins[i], HIGH);
    digitalWrite(ledPins[pinCount - i - 1], HIGH);

    delay(timer);

    // turn the pins off:
    digitalWrite(ledPins[i], HIGH);
    digitalWrite(ledPins[pinCount - i - 1], LOW);
}

关于c++ - 在 Arduino UNO 编程中,当您希望同时执行不同的功能时,使用什么代码/语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300672/

相关文章:

c - x 秒后返回 void

c - 一键老虎机 - int 函数

python - 通过串口发送和接收

c++ - std::chrono 不同的结果 - 固定时间步长循环

c++ - 是否有与 addressof 相反的标准库函数?

c++ - 如何从指向指针数组的指针中删除对象?

audio - 带有 Arduino 的声音传感器始终在串行监视器中显示 1023

java - 如何使用 ardulink 映射 Arduino 引脚?

c++ - imshow 不工作

c++ - 基于OpenCV图像的光流场