我想使用 millis() 函数让 LED 闪烁,但我的 LED 一直亮着,我的代码有什么问题?
I want to get an LED to blink using the millis() function but my LED stays constantly on, what's wrong with my code?
我知道还有其他方法,但我想知道我的代码有什么问题以及为什么它不起作用。尽管有 'else if' 声明,但 Pin 2 似乎一直保持 'HIGH'。
const int led = 2;
int ledState = digitalRead(led);
const unsigned long interval = 1000;
unsigned long previousTime = 0;
void setup()
{
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop()
{
unsigned long current = millis();
if((current - previousTime >= interval) && (ledState == LOW))
{
digitalWrite(led,HIGH);
previousTime = current;
}
else if((current - previousTime >= interval) && (ledState == HIGH))
{
digitalWrite(led,LOW);
previousTime = current;
}
}
第一条评论说你没有更新ledState。这就是问题。我相信更好的解决方案如下:
const int led = 2;
const unsigned long interval = 1000;
unsigned long previousTime = 0;
void setup()
{
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop()
{
unsigned long current = millis();
if(current - previousTime >= interval)
{
digitalWrite(led,!digitalRead(led));
previousTime = current;
}
}
这会读取当前的 LED 状态并使用 !digitalRead(led)
反转它而不需要 if () else {}
我知道还有其他方法,但我想知道我的代码有什么问题以及为什么它不起作用。尽管有 'else if' 声明,但 Pin 2 似乎一直保持 'HIGH'。
const int led = 2;
int ledState = digitalRead(led);
const unsigned long interval = 1000;
unsigned long previousTime = 0;
void setup()
{
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop()
{
unsigned long current = millis();
if((current - previousTime >= interval) && (ledState == LOW))
{
digitalWrite(led,HIGH);
previousTime = current;
}
else if((current - previousTime >= interval) && (ledState == HIGH))
{
digitalWrite(led,LOW);
previousTime = current;
}
}
第一条评论说你没有更新ledState。这就是问题。我相信更好的解决方案如下:
const int led = 2;
const unsigned long interval = 1000;
unsigned long previousTime = 0;
void setup()
{
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop()
{
unsigned long current = millis();
if(current - previousTime >= interval)
{
digitalWrite(led,!digitalRead(led));
previousTime = current;
}
}
这会读取当前的 LED 状态并使用 !digitalRead(led)
反转它而不需要 if () else {}