SONIC感應到 開眼 及 發出聲音

 #include <LedControl.h>


// 超音波感測器引腳定義

#define trigPin 9   // Trig 引腳 (HC-SR04 Trig)

#define echoPin 8   // Echo 引腳 (HC-SR04 Echo)


// LED 顯示模組引腳定義

#define DATA_IN 5   // DIN

#define CLK_PIN 7   // CLK

#define LOAD_PIN 6  // CS


// 喇叭引腳

#define speakerPin 3   // 外接喇叭 (接 Arduino 數位腳位 3)


// 初始化 LedControl 物件

LedControl lc = LedControl(DATA_IN, CLK_PIN, LOAD_PIN, 1);


// "開眼睛有瞳孔" 圖形

byte openEye[8] = {

    B00000000,

    B01100110,

    B01100110,

    B00000000,

    B00000000,

    B01100110,

    B01100110,

    B00000000

};


// "閉眼微笑" 圖形

byte closedEyeSmile[8] = {

    B00000000,

    B00000000,

    B01100110,

    B10011001,

    B10011001,

    B01100110,

    B00000000,

    B00011000

};


void setup() {

  Serial.begin(9600);         // 初始化串列監視器

  pinMode(trigPin, OUTPUT);   // 設定 Trig 引腳為輸出

  pinMode(echoPin, INPUT);    // 設定 Echo 引腳為輸入

  pinMode(speakerPin, OUTPUT); // 設定喇叭引腳為輸出


  // 初始化 LED 顯示模組

  lc.shutdown(0, false);      // 啟用 LED 模組

  lc.setIntensity(0, 8);      // 設定亮度 (0-15)

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

}


void loop() {

  long duration, distance;


  // 觸發超音波感測器

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);


  // 讀取回波時間並計算距離 (cm)

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;


  Serial.print("Distance: ");

  Serial.print(distance);

  Serial.println(" cm");


  // 根據距離顯示不同的圖形

  if (distance > 0 && distance <= 100) {

    Serial.println("Object detected! Displaying 'Open Eye'.");

    displayPattern(openEye); // 顯示「開眼睛有瞳孔」

    

    tone(speakerPin, 1000, 300); // 播放 1000Hz 音效,持續 300 毫秒

  } else {

    Serial.println("No object detected. Displaying 'Closed Eye Smile'.");

    displayPattern(closedEyeSmile); // 顯示「閉眼微笑」


    noTone(speakerPin); // 停止音效

  }


  delay(500);  // 避免過於頻繁的偵測

}


// 顯示特定 8×8 圖形

void displayPattern(byte pattern[8]) {

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

    lc.setRow(0, row, pattern[row]);

  }

}


留言