#include <LedControl.h>
// 超音波感測器腳位
#define trigPin 9
#define echoPin 8
// LED Matrix 腳位設定
#define DATA_IN 5 // DIN
#define CLK_PIN 7 // CLK
#define LOAD_PIN 6 // CS
LedControl lc = LedControl(DATA_IN, CLK_PIN, LOAD_PIN, 1);
// ❤️ 愛心圖案(超過 100cm)
byte heart[8] = {
B00000000,
B01100110,
B11111111,
B11111111,
B01111110,
B00111100,
B00011000,
B00000000
};
// 📦 圖案陣列(1–10)
byte patterns[10][8] = {
{ // 圖案 1:十字架
B00011000,
B00011000,
B01111110,
B01111110,
B00011000,
B00011000,
B00011000,
B00011000
},
{ // 圖案 2:笑臉
B00100100,
B00100100,
B00000000,
B00000000,
B00000000,
B01000010,
B00111100,
B00000000
},
{ // 圖案 3:箭頭
B00011000,
B00011100,
B00011110,
B11111111,
B00011110,
B00011100,
B00011000,
B00000000
},
{ // 圖案 4:方框
B11111111,
B10000001,
B10000001,
B10000001,
B10000001,
B10000001,
B10000001,
B11111111
},
{ // 圖案 5:X
B11111111,
B01000010,
B00100100,
B00011000,
B00011000,
B00011000,
B00111100,
B11111111
},
{ // 圖案 6:圓形
B00111100,
B01111110,
B11111111,
B11111111,
B11111111,
B11111111,
B01111110,
B00111100
},
{ // 圖案 7:梯形
B00000000,
B00011000,
B00111100,
B01111110,
B11111111,
B11111111,
B11111111,
B11111111
},
{ // 圖案 8:菱形
B00011000,
B00111100,
B01111110,
B11111111,
B01111110,
B00111100,
B00011000,
B00000000
},
{ // 圖案 9:小星星
B00000000,
B00100100,
B00011000,
B11111111,
B00011000,
B00100100,
B00000000,
B00000000
},
{ // 圖案 10:笑臉反轉
B00000000,
B00111100,
B01000010,
B00000000,
B00000000,
B00000000,
B00100100,
B00100100
}
};
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lc.shutdown(0, false); // 啟動 LED 模組
lc.setIntensity(0, 8); // 設定亮度(0~15)
lc.clearDisplay(0); // 清除顯示
}
void loop() {
long distance = getDistance();
if (distance > 100) {
displayPattern(heart); // 顯示愛心
} else {
int index = distance / 10; // 每 10cm 一個圖案
if (index >= 0 && index < 10) {
displayPattern(patterns[index]);
}
}
delay(100);
}
// 測距函數
long getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance = duration * 0.034 / 2; // 單位:cm
return distance;
}
// 顯示圖案函數
void displayPattern(byte pattern[8]) {
for (int row = 0; row < 8; row++) {
lc.setRow(0, row, pattern[row]);
}
}
留言
張貼留言