[Arduino] Sample Code–Fading

[Arduino] Sample Code–Fading

上一篇介紹了Arduino的基本測試 — Blink,這篇就來進階一下一樣來個IO,不過是漸強漸弱的的表現唷~

我們先來看個程式碼吧!以下的程式碼是可以在Arduino的程式裡面開啟的 ( 開啟 >> 03.Analog >> Fading )

 

/*
 Fading
 This example shows how to fade an LED using the analogWrite() function.
 The circuit:
 * LED attached from digital pin 9 to ground.
 Created 1 Nov 2008
 By David A. Mellis
 modified 30 Aug 2011
 By Tom Igoe
 http://www.arduino.cc/en/Tutorial/Fading
 This example code is in the public domain.
 */
int ledPin = 9;    // LED connected to digital pin 9
void setup() {
  // nothing happens in setup
}
void loop() {
  // fade in from min to max in increments of 5 points:
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);
    // wait for 30 milliseconds to see the dimming effect
    delay(30);
  }
  // fade out from max to min in increments of 5 points:
  for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);
    // wait for 30 milliseconds to see the dimming effect
    delay(30);
  }
}

在上面的程式碼可以看到呼叫了一個Analog的參數,是指將全輸出的電壓視為255的值,全滅則為0 ( 用8bit表示,即有256階的變化),但由於1階的變化太少了,所以每跳一次為5階。

BUT,一切都有個BUT!!!!!!大家在撰寫程式時需要注意到的是腳位輸出是否支援PWM。為什麼要注意是否支援PWM呢?主要是因為Arduino的輸出入腳分為兩種,一種是數位的,另外一種是類比的。類比的只能作為輸入,不能輸出,一般我們使用的溫度計、溼度計等傳感器就是用這些腳位作為輸入使用的。另外數位的腳位可作為輸入或輸出使用,若為輸出時,有些腳位還支援PWM訊號,而這個Fading的程式就是利用PWM的方式使得亮光明滅有所變化,下一篇我們再來好好地說說PWM的訊號。

下面的影片就是使用這˙個程式碼所達到的LED亮滅效果,有沒有很像外面賣的呼吸燈的感覺壓,使用這段程式碼就可以拿來當呼吸燈囉!!!!!

(影片一:呼吸燈實況 )

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料