阿杜诺。在无限循环中使用计时器循环
Arduino. While loop with a timer inside an infinite loop
我有一个arduino leonardo,我想在一个无限循环内用给定的工作边界做一个while循环。即,无限循环重复十分钟的 while 循环。可以吗?
#include <Mouse.h>
#include <Keyboard.h>
#define timer 5 // running time of the while loop in minutes
void setup(){
Mouse.begin();
randomSeed(analogRead(0) + analogRead(1));
pinMode(3, INPUT_PULLUP);
}
void loop(){
if(!digitalRead(3)){ // starting work through the button click on pin 3
delay(200);
doAction();
}
}
void doAction () {
int last_keyboard = millis();
int start_time = millis();
while(millis()-start_time<=timer*60000){
// action here
}
delay(100);
}
}
根据 Arduino API 参考 millis() function, it returns an unsigned long which is necessary to hold "the number of milliseconds passed since the Arduino board began running the current program". The ATmega boards have 16-bit integers 所以你的问题是整数溢出。你的整数太小了。请改用 unsigned long。可能将 UL 添加到 60000,以指定无符号长数。
我有一个arduino leonardo,我想在一个无限循环内用给定的工作边界做一个while循环。即,无限循环重复十分钟的 while 循环。可以吗?
#include <Mouse.h>
#include <Keyboard.h>
#define timer 5 // running time of the while loop in minutes
void setup(){
Mouse.begin();
randomSeed(analogRead(0) + analogRead(1));
pinMode(3, INPUT_PULLUP);
}
void loop(){
if(!digitalRead(3)){ // starting work through the button click on pin 3
delay(200);
doAction();
}
}
void doAction () {
int last_keyboard = millis();
int start_time = millis();
while(millis()-start_time<=timer*60000){
// action here
}
delay(100);
}
}
根据 Arduino API 参考 millis() function, it returns an unsigned long which is necessary to hold "the number of milliseconds passed since the Arduino board began running the current program". The ATmega boards have 16-bit integers 所以你的问题是整数溢出。你的整数太小了。请改用 unsigned long。可能将 UL 添加到 60000,以指定无符号长数。