超音波A 感應時 8X8LED 顯示A 超音波B 感應時 8X8LED 顯示B

 #include <LedControl.h>


// 定義 8x8 LED 引腳 (DIN, CLK, CS, 數量)

LedControl lc = LedControl(11, 13, 10, 1);


// 定義超音波引腳

const int trigA = 2, echoA = 3;

const int trigB = 4, echoB = 5;

const int threshold = 30; // 觸發門檻 (cm)


// 定義圖形 A 的位元組 (Byte)

byte letterA[8] = {

  B00011000, B00111100, B01100110, B01100110, B01111110, B01100110, B01100110, B00000000

};


// 定義圖形 B 的位元組 (Byte)

byte letterB[8] = {

  B01111100, B01100110, B01100110, B01111100, B01100110, B01100110, B01111100, B00000000

};


void setup() {

  lc.shutdown(0, false);       // 喚醒 MAX7219

  lc.setIntensity(0, 5);      // 設定亮度 (0~15)

  lc.clearDisplay(0);         // 清除顯示

  

  pinMode(trigA, OUTPUT); pinMode(echoA, INPUT);

  pinMode(trigB, OUTPUT); pinMode(echoB, INPUT);

}


// 讀取距離的函式

float getDistance(int trig, int echo) {

  digitalWrite(trig, LOW); delayMicroseconds(2);

  digitalWrite(trig, HIGH); delayMicroseconds(10);

  digitalWrite(trig, LOW);

  long duration = pulseIn(echo, HIGH, 30000); // 增加 Timeout 避免卡死

  if (duration == 0) return 999;             // 超過偵測範圍返回遠距離

  return duration * 0.034 / 2;

}


// 顯示圖形的函式

void drawGraphic(byte graphic[]) {

  for (int i = 0; i < 8; i++) {

    lc.setRow(0, i, graphic[i]);

  }

}


void loop() {

  float distA = getDistance(trigA, echoA);

  float distB = getDistance(trigB, echoB);


  if (distA < threshold) {

    drawGraphic(letterA);   // 顯示 A

  } 

  else if (distB < threshold) {

    drawGraphic(letterB);   // 顯示 B

  } 

  else {

    lc.clearDisplay(0);      // 沒人時熄滅

  }

  

  delay(50); // 小幅延遲讓顯示穩定

}

留言