Загрузка данных


const int micPin = A0;      // A0 микрофона
const int buzzerPin = 8;    // S пищалки
const int buttonPin = 3;    // S кнопки

const int threshold = 60;   // Порог хлопка

bool alarmActive = false;
bool lastButtonState = HIGH;
bool clapLock = false;
bool melodyPlayed = false;  // Чтобы мелодия не играла повторно

// Ноты мелодии
int melody[] = {587, 698, 831, 587, 698, 988};
// Длительности (мс) — можно менять на вкус
int durations[] = {300, 300, 300, 300, 300, 600};
int noteCount = 6;

void setup() {
  pinMode(buzzerPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // 1. Читаем микрофон
  int micValue = analogRead(micPin);

  if (micValue > threshold && !alarmActive && !clapLock) {
    alarmActive = true;
    clapLock = true;
    melodyPlayed = false;
    Serial.print("CLAP! Value: ");
    Serial.println(micValue);
  }

  if (micValue < threshold - 10) {
    clapLock = false;
  }

  // 2. Кнопка — стоп
  bool btnState = digitalRead(buttonPin);
  if (btnState == HIGH && lastButtonState == LOW) {
    delay(50);
    if (digitalRead(buttonPin) == HIGH) {
      alarmActive = false;
      melodyPlayed = false;
      noTone(buzzerPin);
      Serial.println("STOP");
    }
  }
  lastButtonState = btnState;

  // 3. Играем мелодию один раз
  if (alarmActive && !melodyPlayed) {
    for (int i = 0; i < noteCount; i++) {
      // Проверяем кнопку во время игры, чтобы можно было прервать
      if (digitalRead(buttonPin) == HIGH) {
        alarmActive = false;
        noTone(buzzerPin);
        melodyPlayed = false;
        return;
      }
      tone(buzzerPin, melody[i], durations[i]);
      delay(durations[i] + 50); // +50 мс пауза между нотами
    }
    noTone(buzzerPin);
    melodyPlayed = true;
  }
}