超音波+喇叭 範例_超音波感應電子琴

 

當物體進入不同的距離範圍時,應該能聽到對應的音符

(C, D, E, F, G, A, B)



超音波感測器 HC-SR04  --->  Arduino
-----------------------------------
VCC   (超音波)  --->  5V (Arduino)
GND   (超音波)  --->  GND (Arduino)
Trig  (超音波)  --->  7   (Arduino)
Echo  (超音波)  --->  6   (Arduino)

喇叭           --->  Arduino
-----------------------------------
+ (喇叭)       --->  9   (Arduino)
- (喇叭)       --->  GND (Arduino)


const int trigPin = 7;     // 超音波感測器 Trig 腳位
const int echoPin = 6;     // 超音波感測器 Echo 腳位
const int speakerPin = 9;  // 3W 喇叭腳位接+極

// 各個音符的頻率 (Hz)
const int noteC = 261;  // C (261 Hz)
const int noteD = 294;  // D (294 Hz)
const int noteE = 329;  // E (329 Hz)
const int noteF = 349;  // F (349 Hz)
const int noteG = 392;  // G (392 Hz)
const int noteA = 440;  // A (440 Hz)
const int noteB = 493;  // B (493 Hz)

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; // 轉換為公分
    return distance;
}

void setup() {
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(speakerPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    long distance = getDistance();
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");

    // 根據距離發出對應的音符
    if (distance >= 10 && distance < 20) {
        tone(speakerPin, noteC);  // 10cm 內 發出 C
    } else if (distance >= 20 && distance < 30) {
        tone(speakerPin, noteD);  // 20-30cm 發出 D
    } else if (distance >= 30 && distance < 40) {
        tone(speakerPin, noteE);  // 30-40cm 發出 E
    } else if (distance >= 40 && distance < 50) {
        tone(speakerPin, noteF);  // 40-50cm 發出 F
    } else if (distance >= 50 && distance < 60) {
        tone(speakerPin, noteG);  // 50-60cm 發出 G
    } else if (distance >= 70 && distance < 80) {
        tone(speakerPin, noteA);  // 70-80cm 發出 A
    } else if (distance >= 80 && distance < 90) {
        tone(speakerPin, noteB);  // 80-90cm 發出 B
    } else {
        noTone(speakerPin);  // 超過 90cm 停止發聲
    }

    delay(100);  // 等待一段時間再讀取下一次距離
}


留言