【发布时间】:2021-04-02 16:38:26
【问题描述】:
我正在构建一个带有各种必须闪烁的 LED 的 arduino 项目。我决定使用 [arduino-timer.h] (https://www.arduino.cc/reference/en/libraries/arduino-timer/)。我不懂C++。我知道 javascript。
arduino-timer.h 函数(.in、.at、.every)允许将第三个参数传递给正在调用的定时器函数。我希望这第三个参数是一个结构,以获得更大的灵活性。
请参阅下面的代码,该代码显示了我正在尝试的基本示例。然而,变量 colourCount 并没有改变。根据我收集到的信息,为了能够做到这一点,我应该通过引用或指针传递结构变量。
在函数调用中,我尝试过类似
bool genericOn(TimerStruct &obj) {
但这会引发错误:
In function 'void setup()':
timer_struct_test:27:58: error: no matching function for
call to 'Timer<3u, millis, TimerStruct>::every(const int&, bool (&)(TimerStruct&), TimerStruct*)'
repeatTask = u_timer.every(Interval, genericOn, &timerC);
那么....有人可以帮忙吗?
以下是正常工作的代码,除了 colorCount 保持不变。
#include <arduino-timer.h>
Timer<>::Task repeatTask;
Timer<>::Task blinkTask;
const int DIO_GREEN = 17;
const int Interval = 1000;
struct TimerStruct
{
int total;
int color;
int colorCount;
int inBetween;
};
Timer<3, millis, struct TimerStruct> u_timer;
Timer<10, millis, struct TimerStruct> b_timer;
void setup (){
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
pinMode (DIO_GREEN, OUTPUT);
struct TimerStruct timerC;
timerC.total = 10;
timerC.color = DIO_GREEN;
timerC.colorCount = 0;
timerC.inBetween = 500;
repeatTask = u_timer.every(Interval, genericOn, timerC);
}
void loop() {
u_timer.tick();
b_timer.tick();
}
bool genericOn(TimerStruct obj) {
digitalWrite(obj.color, LOW);
Serial.print(obj.colorCount);
Serial.print(" - color ");
Serial.print(obj.color);
Serial.print(" - total ");
Serial.print(obj.total);
Serial.print("- inbetween");
Serial.println(obj.inBetween);
blinkTask = b_timer.in(obj.inBetween, genericOff, obj);
if (obj.colorCount< obj.total){
obj.colorCount++;
return true;
}
return false;
}
bool genericOff(TimerStruct obj) {
digitalWrite(obj.color, HIGH);
return true;
}
【问题讨论】:
-
Timer<3, millis, struct TimerStruct>->Timer<3, millis, struct TimerStruct&>? -
@KamilCuk 这似乎是一种非法格式。
timer_struct_test:16:39: error: use of deleted function 'Timer<3u, millis, TimerStruct&>::Timer()' Timer<3, millis, struct TimerStruct&> u_timer; ^ In file included from /arduino-timer.h:53:7: note: 'Timer<3u, millis, TimerStruct&>::Timer()' is implicitly deleted because the default definition would be ill-formed: class Timer { -
当然 - 所以你必须有默认的可构造参考。它被称为指针。或者
std::reference_wrapper我想。