接線圖
X1 Arduino Uno R3
X1 單色LED
X1 220~10k Ω 電阻
LED燈需要接上電阻 避免電流過大燒壞
LED正極需插入有 PWM 功能之 pin腳(有~符號就是PWM)
有關PWM可參考這裡
Arduino IDE code
以下提供三種程式碼
第一種
int YellowLED = 6; //定義 pin6為 YellowLED
int intensity = 0; //定義 光強度為intensity
int rate = 5; //定義 光強度的變化率
void setup()
{
pinMode(YellowLED,OUTPUT); //輸出
Serial.begin(9600); //開啟串列監視器
}
void loop()
{
analogWrite(YellowLED,intensity);
intensity = intensity + rate;
if (intensity ==0){
rate = 5;
}
if (intensity ==255){
rate=-5;
delay(30);
}
Serial.println(intensity);
delay(1000);
}
第二種
int ledPin = 6;
void setup() {
// initialize ledPin (pin 6) as an output.
pinMode(ledPin, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(ledPin, brightness);
delay(10);
}
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(ledPin, brightness);
delay(10);
}
}
第三種 Arduino IDE 內建的 fading
int led = 6; // 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 6 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 >= 200) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
沒有留言:
張貼留言