倒車音樂盒
「倒車音樂盒」的創作理念,源自於將科技與生活結合,讓警示不再只是單調的嗶嗶聲,而是轉化為有趣的旋律。超音波感測器量測距離,透過程式邏輯將數據轉換成音樂的速度變化,距離越近,節奏越快,形成一種直覺的提醒方式。這樣的設計不僅提升了警示效果,也讓倒車過程更具人性化與趣味性。它象徵著「安全」與「創意」的融合:安全提醒不必冰冷,而是可以用音樂傳遞情感,讓駕駛者在緊張的倒車環境中,感受到一絲輕鬆與趣味。這是一種將工程思維與藝術表達結合的嘗試,讓日常科技更貼近人心。
使用的模組:超音波+speaker
// 超音波感測器模組
腳位接法
const
int trigPin = 7; // Trig 腳位
const
int echoPin = 6; // Echo 腳位
// 喇叭模組 腳位接法
const
int speakerPin = 9; // 喇叭接 + 極
// 定義旋律 (倒車音樂盒)
int
melody[] = {
262, 294, 330, 349, 392, 440, 494, 523
}; // C
D E F G A B C
int
noteDurations[] = {
4, 4, 4, 4, 4, 4, 4, 4
}; // 每個音符長度 (四分音符)
// 量測距離函式
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
playMelody(long distance) {
// 根據距離計算速度因子
// 距離越近,速度越快 (最小 100ms,最大 600ms)
int baseTempo = map(distance, 30, 100, 100,
600);
baseTempo = constrain(baseTempo, 100, 600);
for (int thisNote = 0; thisNote < 8;
thisNote++) {
int noteDuration = baseTempo /
noteDurations[thisNote];
tone(speakerPin, melody[thisNote],
noteDuration);
delay(noteDuration * 1.3); // 音符間隔
}
}
void
loop() {
long distance = getDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance > 100 || distance == 0) {
noTone(speakerPin); // 太遠不播放
} else {
playMelody(distance);
}
}
留言
張貼留言