113寒假_科技小創客-互動科技裝置設計(五)II

const int resistorPin = 6;   // 連接電阻的腳位

const int groundPin = A0;    // 連接導線的腳位

const int ledPin = 7;        // 連接LED的腳位

const int buzzerPin = 2;     // 連接蜂鳴器的腳位

void setup() {

  Serial.begin(9600);        // 初始化序列通訊

  pinMode(ledPin, OUTPUT);    // 設定LED腳位為輸出

  pinMode(buzzerPin, OUTPUT); // 設定蜂鳴器腳位為輸出

}

void loop() {

  int sensorValue = analogRead(groundPin);  // 讀取電壓值,使用導線連接的腳位

  Serial.println(sensorValue);  // 將值輸出到序列監視器

  if (sensorValue > 500) {  // 設定一個閾值,當觸碰時LED發亮

    digitalWrite(ledPin, HIGH);  // 點亮LED

    // 播放 "小星星"

    playTwinkleTwinkle();

  } else {

    digitalWrite(ledPin, LOW);  // 關閉LED

    noTone(buzzerPin);          // 停止蜂鳴器的聲音

  }

  delay(100);  // 延遲以減少讀取速率

}

// 函數:播放 "小星星"

void playTwinkleTwinkle() {

  int melody[] = {262, 262, 392, 392, 440, 440, 392, 349, 349, 330, 330, 294, 294, 262}; // 音階

  int noteDuration = 300; // 音符持續時間(毫秒)

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

    tone(buzzerPin, melody[i], noteDuration);

    delay(150); // 音符之間的短暫延遲

  }

}


0 條回復   |  直到 2月前 | 107 次瀏覽




熱門評論


登入後才可發表內容