這個例子演示了使用analogWrite()函數(shù)來漸變LED的功能。AnalogWrite使用脈沖寬度調(diào)制(PWM),以開和關(guān)之間的不同比率非??焖俚卮蜷_和關(guān)閉數(shù)字引腳,以產(chǎn)生漸變效應(yīng)。
你將需要以下組件:
按照電路圖連接面包板上的組件,如下圖所示。
注意 ? 要了解LED的極性,請仔細查看。兩個腿中較短的,朝向燈泡的平坦邊緣表示負極端子。
像電阻器這樣的組件需要將其端子彎曲成90°角,以便恰當?shù)倪m配面包板插座。你也可以將端子切短。
在計算機上打開Arduino IDE軟件。使用Arduino語言進行編碼控制你的電路。通過單擊“New”打開新的草圖文件。
/* 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()函數(shù)中沒有任何操作。你將在代碼的主循環(huán)中使用的analogWrite()函數(shù)會需要兩個參數(shù):一個告訴函數(shù)要寫入哪個引腳,另一個表示要寫入的PWM值。
為了使LED漸變熄滅和亮起,將PWM值從0(一直關(guān)閉)逐漸增加到255(一直開啟),然后回到0,以完成循環(huán)。在上面給出的草圖中,PWM值使用稱為brightness的變量設(shè)置。每次通過循環(huán)時,它增加變量fadeAmount的值。
如果brightness處于其值的任一極值(0或255),則fadeAmount變?yōu)樨撝怠Q句話說,如果fadeAmount是5,那么它被設(shè)置為-5。如果它是-5,那么它被設(shè)置為5。下一次通過循環(huán),這個改變也將導致brightness改變方向。
analogWrite()可以非常快速地改變PWM值,因此草圖結(jié)束時的delay控制了漸變的速度。嘗試改變delay的值,看看它如何改變漸變效果。
你應(yīng)該看到你的LED亮度逐漸變化。
更多建議: