我有一个带有延迟的简单代码。 我想知道如何将这段代码转换为毫秒。有功能吗?
long revers = 1000;
void setup() {
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
}
void loop() {
digitalWrite(D1, LOW);
delay(revers);
digitalWrite(D2, HIGH);
delay(revers);
digitalWrite(D2, LOW);
delay(revers);
digitalWrite(D1, HIGH);
delay(revers);
}
答案 0 :(得分:0)
基本概念是:将给定时刻的millis()记录在变量中-说“开始时间”。现在,在每个loop()期间,通过从“ starttime”中减去millis()来检查所经过的时间。如果经过的时间大于您设置的延迟时间,请执行代码。重置开始时间以创建重复模式。
对于您来说,这可能太短了,因此在您深入研究代码之前,我强烈建议您阅读有关using millis() for timing的介绍。它很长,但是它广泛地解释了原理。这将帮助您理解下面的代码。
最后,编写了一些库来简化计时的使用。例如SimpleTimer库,但是您可以为其他人使用Google“ arduino计时器库”。我在下面提供了一个示例。
开启1秒,关闭3秒:
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000; //the value is a number of milliseconds
int fase; //value used to determine what action to perform
void setup() {
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
startMillis = millis(); //initial start time
fase = 0;
}
void loop() {
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
if (currentMillis - startMillis >= period) //test whether the period has elapsed
{
if (fase == 0)
{
digitalWrite(8, LOW);
startMillis = currentMillis; //IMPORTANT to save the start time of the current LED state.
fase = 1; //increment fase, so next action will be different
}
else if (fase == 1)
{
digitalWrite(7, HIGH);
startMillis = currentMillis;
fase = 2;
}
else if (fase == 2)
{
digitalWrite(7, LOW);
startMillis = currentMillis;
fase = 3;
}
else if (fase == 3)
{
digitalWrite(8, HIGH);
fase = 0;
startMillis = currentMillis;
}
}
}
使用SimpleTimer库的LED闪烁示例
#include <SimpleTimer.h>
// the timer object
SimpleTimer timer;
int ledPin = 13;
// a function to be executed periodically
void repeatMe() {
digitalWrite(ledPin, !digitalRead(ledPin));
}
void setup() {
pinMode(ledPin, OUTPUT);
timer.setInterval(1000, repeatMe);
}
void loop() {
timer.run();
}