如何将延迟转换为毫秒

How to convert delay to millis

我有一个带有延迟的简单代码。 我想知道如何将此代码转换为毫秒?有这样做的功能吗?

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);

}

基本概念是这样的:在变量中记录给定时刻的 millis() - 比如 'starttime'。现在,在每个 loop() 期间,通过从 'starttime' 中减去 millis() 来检查已经过去的时间。如果经过的时间大于您设置的延迟时间,则执行代码。重置开始时间以创建重复模式。

这对您来说可能太简短了,所以在您深入研究代码之前,我强烈建议您阅读这篇关于 using millis() for timing 的介绍。它很长,但它广泛地解释了原理。这将帮助您理解下面的代码。

最后,编写了几个库来简化计时的使用。例如 SimpleTimer-library,但您可以 google "arduino timer library" 用于其他人。我在下面包含了一个示例。

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();
}