材料
LED x3 (以上)
Resistor 330Ω x3 (搭配LED數量)
製作
< 參考「Arduino互動設 計入門2」- p4-19 ~ p4-21 >
紅色線: 高電位/電源輸出
黑色線: 低電位/電源回流
分兩種接法: 左圖為源流(source current) 與 右圖潛流(sink current)
電路圖如下:
程式如下:
const byte LEDs[] = {4 ,7, 10};
const byte LEDs_SIZE = sizeof(LEDs);
const byte INIT_VALUE = LOW; // LOW/HIGH when using source-/sink-current circuit
byte count = 0;
void setup() {
for (byte i=0; i< LEDs_SIZE; i++) {
pinMode(LEDs[i], OUTPUT);
}
}
void loop() {
for (byte i=0; i< LEDs_SIZE; i++) {
digitalWrite(LEDs[i], INIT_VALUE);
}
count = count % 3;
digitalWrite(LEDs[count], ! INIT_VALUE);
count++;
delay(200);
}
上述, 使用了廻圈(loop)與陣列(array)的寫法; 源流接法時, 將
const byte INIT_VALUE = LOW;
潛流接法時, 將
const byte INIT_VALUE = HIGH;
另外, 可使用 DDRx (Data Direction Register)來控制 pin 的輸出入, 並使用 shift 的程式技巧來達成:
<以DDRD/PortD為例>
// for sink-current circuit
const byte INIT_VALUE = 0b00001000;
const byte LED_SHIFT = 2;
byte count = 0;
void setup() {
DDRD = 0b10101000; // OFF for pull-down circuit
}
void loop() {
count = count % 3;
if (count == 0) {
PORTD = INIT_VALUE;
} else {
PORTD <<= LED_SHIFT;
}
count++;
delay(200);
}
上述為潛流接法的寫作, 源流的寫法得花點時間想想。
ps.
上述二例寫法與「Arduino互動設 計入門2」- p4-28, p4-31有點不同



沒有留言:
張貼留言