所以我有一段代码每隔12秒做一次。
unsigned long currentMillis, previousMillis;
void loop()
{
unsigned long currentMillis = millis();
time = currentMillis - previousMillis;
if(time >= 0 && time <=40 ) //about this "40" I say below
{
do stuff;
}
if (time =="12 seconds"+/- 40 <- example) previousMillis = currentMillis; //reset
}
所以它是0,1,2,3,4 ...... 12.000,0,1,2,3 ......,12.000,0,1,2等等 (我知道它不完全是12.000,并不是每个数字都是连续的,但这只是一个例子)
我的问题是: 在这段时间0-12.000我想每隔x秒做一些其他事情(x不大于12秒) 我用串口监视器打印currentMillis,time,previousMillis,它看起来像这样:
currentMillis: 1 time: 1 previousMillis 0
currentMillis: 5 time: 5 previousMillis 0
currentMillis: 13 time: 13 previousMillis 0
currentMillis: 21 time: 21 previousMillis 0
currentMillis: 30 time: 30 previousMillis 0
currentMillis: 38 time: 38 previousMillis 0
currentMillis: 47 time: 47 previousMillis 0
currentMillis: 56 time: 56 previousMillis 0
.....................................................
.....................................................
.....................................................
.....................................................
currentMillis: 12536 time: 12536 previousMillis 0
currentMillis: 12547 time: 12547 previousMillis 0
currentMillis: 12556 time: 12556 previousMillis 0
currentMillis: 12565 time: 12565 previousMillis 12565
currentMillis: 12575 time: 10 previousMillis 12565
currentMillis: 12585 time: 20 previousMillis 12565
currentMillis: 12595 time: 30 previousMillis 12565
currentMillis: 12605 time: 40 previousMillis 12565
currentMillis: 12614 time: 49 previousMillis 12565
currentMillis: 12624 time: 59 previousMillis 12565
//当我想要捕获12.000ms时,我在IF语句中使用了一些像+/- 40这样的小间隔,以确保我能够捕获12秒的时间。
答案 0 :(得分:0)
我知道你需要一个解决方案,每12秒执行一次,你认为40毫秒是这个时间的限制。我认为下面的代码是一个解决方案。它使用Arduino环境函数setup()
和loop()
。
我已经使用了你的40毫秒的想法,但我认为最好避免使用这种修正,并且最好使用调整“下一个”循环时间的东西(参见评论)下面的代码。)
static unsigned long timer=0,msec=0;
void setup() {
msec=millis();
}
void loop(void)
{
timer-=msec;
msec=millis();
timer+=msec;
if (timer>=12000-40) {
//Do something
timer=0;
//To solve the time oscillation you might use the code below
//and you correct the if as if (timer>=12000)
//timer=timer-12000;
}
}
答案 1 :(得分:0)
您可以定义一些功能以提高可读性。 您下次存储时会执行操作 您可以为每个频率执行一项功能。例如DELAY1 12000和DELAY2 1234;
static void funct1(unsigned long now) {
static unsigned long next;
if (next > now)
return;
next = now + DELAY1;
/* here your code */
}
static void funct2(unsigned long now) {
static unsigned long next;
if (next > now)
return;
next = now + DELAY2;
/* here your code */
}
loop() {
unsigned long now = millis();
funct1(now);
funct2(now);
}