定義 Arduino 5~12 分別對應到數碼管的 DP, A, B, C, D, E, F, G 等腳位
int pin_DP = 5;
int pin_A = 6;
int pin_B = 7;
int pin_C = 8;
int pin_D = 9;
int pin_E = 10;
int pin_F = 11;
int pin_G = 12;
定義要顯示數碼的陣列, 顯示數碼是以二進位的位元組儲存, 每個位元對應一個LED的顯示段, 0 表不亮, 1 表亮
byte words[ ] = {
// .ABCDEFG
B00110111, // H
B01001111, // E
B00001110, // L
B00001110, // L
B01111110, // O
B10000000, // .
B01111110, // 0
B00110000, // 1
B01101101, // 2
B01111001, // 3
B00110011, // 4
B01011011, // 5
B01011111, // 6
B01110000, // 7
B01111111, // 8
B01111011, // 9
B10000000 // .
};
二進位碼顯示 H 字元示意圖
設定前列項數碼陣列的長度(HELLO.0123456789. 共17個字元)
於 setup() 函數內設定 Nano 對應到數碼的PIN 均為 OUTPUT
void setup(){
pinMode(pin_DP, OUTPUT);
pinMode(pin_A, OUTPUT);
pinMode(pin_B, OUTPUT);
pinMode(pin_C, OUTPUT);
pinMode(pin_D, OUTPUT);
pinMode(pin_E, OUTPUT);
pinMode(pin_F, OUTPUT);
pinMode(pin_G, OUTPUT);
}
撰寫 loop()函數, 函數內執行迴圏依序顯示 0.9 秒的字元, 及關閉 0.1 秒的LED
void loop(){
for(int i=0; i<words_length; i++){
showIt(words[i]);
delay(900);
clearLED();
delay(100);
}
delay(5000);
}
建立 showIt()函式, showIt()函式傳入要顯示字元的二進位碼, 在依據二進位碼各位元的 0, 1 值決定所對應數碼管的亮與滅
void showIt(byte data){
int quotient = 0;
int remainder = 0;
remainder= data % 2;
// 取得 G 值
if(remainder == 1){
digitalWrite(pin_G, HIGH);
} else {
digitalWrite(pin_G, LOW);
}
// 取得 F 值
quotient = data / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_F, HIGH);
} else {
digitalWrite(pin_F, LOW);
}
// 取得 E 值
quotient = quotient / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_E, HIGH);
} else {
digitalWrite(pin_E, LOW);
}
// 取得 D 值
quotient = quotient / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_D, HIGH);
} else {
digitalWrite(pin_D, LOW);
}
// 取得 C 值
quotient = quotient / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_C, HIGH);
} else {
digitalWrite(pin_C, LOW);
}
// 取得 B 值
quotient = quotient / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_B, HIGH);
} else {
digitalWrite(pin_B, LOW);
}
// 取得 A 值
quotient = quotient / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_A, HIGH);
} else {
digitalWrite(pin_A, LOW);
}
// 取得 DP 值
quotient = quotient / 2;
remainder= quotient % 2;
if(remainder == 1){
digitalWrite(pin_DP, HIGH);
} else {
digitalWrite(pin_DP, LOW);
}
}
showIt()函式之二進位解碼示意圖
建立 clearLED()函式, clearLED()函式非常簡單, 就是將對應到數碼管的 DP, A, B, C, D, E, F, G 等腳位信號設定為 LOW(低電位, 不亮)
void clearLED(){
digitalWrite(pin_DP, LOW);
digitalWrite(pin_A, LOW);
digitalWrite(pin_B, LOW);
digitalWrite(pin_C, LOW);
digitalWrite(pin_D, LOW);
digitalWrite(pin_E, LOW);
digitalWrite(pin_F, LOW);
digitalWrite(pin_G, LOW);
}