Arduino - LED 漸變



此示例演示瞭如何使用 `analogWrite()` 函式實現 LED 漸變熄滅效果。`analogWrite()` 使用脈寬調製 (PWM),透過以不同的比例快速開關數字引腳,從而建立漸變效果。

所需元件

您將需要以下元件:

  • 1 個麵包板
  • 1 個 Arduino Uno R3
  • 1 個 LED
  • 1 個 330Ω 電阻
  • 2 根跳線

步驟

按照電路圖,將元件連線到麵包板,如下圖所示。

Components on Breadboard

注意 - 要確定 LED 的極性,仔細觀察它。較短的一端(靠近燈泡平面的那端)表示負極。

LED

電阻等元件需要將其引腳彎成 90° 角才能正確插入麵包板的插孔。您也可以將引腳剪短。

Resistors

程式碼

在您的電腦上開啟 Arduino IDE 軟體。使用 Arduino 語言編寫程式碼來控制您的電路。點選“新建”開啟新的程式碼檔案。

Sketch

Arduino 程式碼

/*
   Fade
   This example shows how to fade an LED on pin 9 using the analogWrite() function.

   The analogWrite() function uses PWM, so if you want to change the pin you're using, be
   sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with
   a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
*/

int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:

void setup() {
   // declare pin 9 to be an output:
   pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:

void loop() {
   // set the brightness of pin 9:
   analogWrite(led, brightness);
   // change the brightness for next time through the loop:
   brightness = brightness + fadeAmount;
   // reverse the direction of the fading at the ends of the fade:
   if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
   }
   // wait for 30 milliseconds to see the dimming effect
   delay(300);
}

程式碼註釋

在將 9 號引腳宣告為 LED 引腳後,在程式碼的 `setup()` 函式中無需執行任何操作。您將在程式碼主迴圈中使用的 `analogWrite()` 函式需要兩個引數:一個引數指示要寫入的引腳,另一個引數指示要寫入的 PWM 值。

為了使 LED 逐漸熄滅和點亮,我們將 PWM 值從 0(完全熄滅)逐漸增加到 255(完全點亮),然後再返回 0,以完成一個迴圈。在上圖所示的程式碼中,PWM 值使用名為 `brightness` 的變數設定。每次迴圈,它都會增加 `fadeAmount` 變數的值。

如果 `brightness` 的值達到任一極值(0 或 255),則 `fadeAmount` 將變為其相反數。換句話說,如果 `fadeAmount` 為 5,則將其設定為 -5。如果為 -5,則將其設定為 5。在下一次迴圈中,此更改也會導致 `brightness` 改變方向。

`analogWrite()` 可以非常快速地更改 PWM 值,因此程式碼末尾的 `delay()` 函式控制漸變的速度。嘗試更改 `delay()` 的值,看看它如何改變漸變效果。

結果

您應該看到 LED 亮度逐漸變化。

廣告