我們可以透過Arduino 的數位輸出脈波讓LED的明滅受到控制,心情燈就是這類控制的實現
Jason Chin 2019/9/22
這個範例是利用類比輸出 PWM (Pulse Width Modulation) 脈碼調變, 也就是輸出方波,調整高電位(on time)和低電位(off time)的輸出時間比例(即 ON/OFF 比例),達到LED亮度可變可調整的效果
正常方波 on time 和 off time 比例是相同的,所以亮度會維持一定,但 PWM 讓輸出給 LED 的脈波變得可以調整on time 和 off time 的時間比例,而達到亮度調整的效果
硬體需求
- Arduino 電路板
- LED 發光二極體
- 220 ohm 電阻
- 連接電線
- 麵包板
電路連接
LED 長腳端(正電端) 連接220 ohms 電阻後,電阻另一端再連到 Pin 9 (PWM 輸出端)
電路圖
程式碼
In this example two loops are executed one after the other to increase and then decrease the value of the output on pin 9.
/*
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);
}
}