我想要使用此代码打开和关闭arduino Uno,但启动过程需要3时间

问题描述 投票:0回答:1

我想在arduino uno中使用millis自动打开和关闭led,但不知何故我解决了问题,但启动分钟需要一些时间

const int ledPin = 13; // Pin to control the LED

unsigned long currentMillis;
unsigned long previousMillis = 0;
const unsigned long onInterval = 180000; // 3 Min in milliseconds
const unsigned long offInterval = 60000;  // 1 Min in milliseconds
bool isLedOn = false;

void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
digitalWrite(ledPin, HIGH);
}

void loop() {
currentMillis = millis();
if (isLedOn && (currentMillis - previousMillis \>= onInterval)) {
digitalWrite(ledPin, LOW); // Turn off the LED
isLedOn = false;
previousMillis = currentMillis; // Reset the timer
} else if (!isLedOn && (currentMillis - previousMillis \>= offInterval)) {
digitalWrite(ledPin, HIGH); // Turn on the LED
isLedOn = true;
previousMillis = currentMillis; // Reset the timer
}
}

我用这段代码解决了问题或更改编码,如果arduino板启动,我会想要吹气

c time arduino computer-science iot
1个回答
0
投票
  1. 第一次 LED 变化发生在启动后 60 秒,因为

    isLedOn
    已用
    false

    初始化

    但是您还可以在 setup() 函数中将 LED 的状态设置为高电平 与

    digitalWrite(ledPin, HIGH);

    所以你的loop()代码认为LED是关闭的,而实际上,它是关闭的 已开启。

    因此亮起4分钟

    (offInterval + onInterval)
    , 再次关闭之前。

    您可以通过使用

    isLedOn
    初始化
    true
    来解决此问题。


  1. 就像 @Sembei Norimaki 已经指出的那样,运算符 ">= 不存在,所以你应该只写 ">= 来代替
© www.soinside.com 2019 - 2024. All rights reserved.