delay()

描述

将程式暂停一段由参数指定的时间 (单位是毫秒,1000 毫秒 = 1 秒)

语法


delay(ms)

参数

ms: 暂停多少毫秒 (unsigned long)

回传

无回传值

范例

int ledPin = 13;                // LED 灯连接到 pin 脚 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // 将数位 pin 脚设定为输出
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // 点亮 LED 灯
  delay(1000);                  // 等待一秒
  digitalWrite(ledPin, LOW);    // 熄灭 LED 灯
  delay(1000);                  // 等待一秒
}

警告

虽然用 delay() 很容易能制作出闪烁的 LED 灯,也可以用来去除外部开关的瞬间抖动,不过,太常使用 delay() 也有一些显著的缺点;例如:在延迟的这段时间里,不能读取感测器、不能做数学运算、不能处理 pin 脚信号,也就是说它会让大部分的动作都停摆;作为控制时间的替代方案可以参考使用 millis() 函式还有程式码范例,许多有经验的程式设计师会避免使用 delay() 超过十毫秒,除非程式码本身相当简单。

然而,在 delay() 的这段延迟期间里,CPU 还是可以做某些事情的:由于这段时间里没有关闭中断,所以从序列埠的 RX pin 脚进来的资料都会被纪录下来,PWM (analogWrite) 的数值和 pin 脚状态也会被保存,中断事件也会照常运作。

See also

millis()
micros()
delayMicroseconds()
Blink Without Delay example


语法参考主页面

本页由热血青年 LBU 译自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.