Arduino 漸變LED

2018-11-20 15:29 更新

這個(gè)例子演示了使用analogWrite()函數(shù)來(lái)漸變LED的功能。AnalogWrite使用脈沖寬度調(diào)制(PWM),以開(kāi)和關(guān)之間的不同比率非常快速地打開(kāi)和關(guān)閉數(shù)字引腳,以產(chǎn)生漸變效應(yīng)。

必需的組件

你將需要以下組件:

  • 1 × Breadboard 面包板
  • 1 × Arduino Uno R3
  • 1 × LED
  • 1 × 330Ω 電阻
  • 2 × 跳線

程序

按照電路圖連接面包板上的組件,如下圖所示。

電路圖

注意 ? 要了解LED的極性,請(qǐng)仔細(xì)查看。兩個(gè)腿中較短的,朝向燈泡的平坦邊緣表示負(fù)極端子。


LED

像電阻器這樣的組件需要將其端子彎曲成90°角,以便恰當(dāng)?shù)倪m配面包板插座。你也可以將端子切短。


電阻

草圖

在計(jì)算機(jī)上打開(kāi)Arduino IDE軟件。使用Arduino語(yǔ)言進(jìn)行編碼控制你的電路。通過(guò)單擊“New”打開(kāi)新的草圖文件。

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

代碼說(shuō)明

將引腳9聲明為L(zhǎng)ED引腳之后,在代碼的setup()函數(shù)中沒(méi)有任何操作。你將在代碼的主循環(huán)中使用的analogWrite()函數(shù)會(huì)需要兩個(gè)參數(shù):一個(gè)告訴函數(shù)要寫(xiě)入哪個(gè)引腳,另一個(gè)表示要寫(xiě)入的PWM值。

為了使LED漸變熄滅和亮起,將PWM值從0(一直關(guān)閉)逐漸增加到255(一直開(kāi)啟),然后回到0,以完成循環(huán)。在上面給出的草圖中,PWM值使用稱(chēng)為brightness的變量設(shè)置。每次通過(guò)循環(huán)時(shí),它增加變量fadeAmount的值。

如果brightness處于其值的任一極值(0或255),則fadeAmount變?yōu)樨?fù)值。換句話說(shuō),如果fadeAmount是5,那么它被設(shè)置為-5。如果它是-5,那么它被設(shè)置為5。下一次通過(guò)循環(huán),這個(gè)改變也將導(dǎo)致brightness改變方向。

analogWrite()可以非常快速地改變PWM值,因此草圖結(jié)束時(shí)的delay控制了漸變的速度。嘗試改變delay的值,看看它如何改變漸變效果。

結(jié)果

你應(yīng)該看到你的LED亮度逐漸變化。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)