I'm working on an arduino project that reads in data from different sensors. I take the values and store them in an array. The problem is that I'd like to update the sensor values at different rates. For example, I wan't to update one every 250ms but another every 50ms. But I'd like it to the loop running in between sensor updates. The only way I can think of getting it to kind of work is with delays but that stops the loop.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use the millis() function with intervals set for each of the sensors you want to read. Have a look at the Blink Without Delay example on the Arduino website
http://arduino.cc/en/Tutorial/BlinkWithoutDelay
回答2:
If you've got a bunch of sensors to check, you may save a bit of coding by using the Metro library. Same general concept as BRM's answer. You can also use timer interrupts as well. For information with links to a number of articles on timer interrupts, see my Move now, don’t delay() blog post.
回答3:
If you don not want to use a library you could implement it like that:
typedef void (*command)();
template <unsigned long wait_ms, command c>
void repeat() {
static unsigned long start = millis();
if (millis()-start >= wait_ms) {
start += wait_ms;
c();
}
}
void task1() {
// every 50ms
}
void task2() {
// every 250ms
}
void setup() {
}
void loop() {
repeat< 50, task1>();
repeat<250, task2>();
}
This will work as long as there is nothing that "blocks" inside the loop.