-1

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

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

}
4

1 回答 1

1

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

这对你来说可能解释得太少了,所以在你深入研究代码之前,我强烈建议你阅读这篇关于使用 millis() 进行计时的介绍。它很长,但它广泛地解释了这个原理。这将帮助您理解下面的代码。

最后,编写了几个库来简化时序的使用。例如SimpleTimer -library,但您可以为其他人搜索“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();
}
于 2019-01-25T13:13:05.103 回答