User Tools

Site Tools


soundforpassivespeaker
#include <Arduino.h>
const int SPEAKER_PIN = D7;
bool blink = true;

void setup() {
  pinMode(SPEAKER_PIN, OUTPUT);
  Serial.begin(115200);
  delay(5000);
  Serial.println("PC Speaker Doorbell Ready!");
  pinMode(LED_BUILTIN,OUTPUT);
}

// Function to play a tone using PWM
void playTone(int frequency, int duration) {
  if (frequency == 0) {
    delay(duration);
    return;
  }
  
  // Calculate the period in microseconds
  int period = 1000000L / frequency;
  int halfPeriod = period / 2;
  
  // Calculate how many cycles we need for the duration
  long cycles = (long)frequency * duration / 1000;
  
  for (long i = 0; i < cycles; i++) {
    digitalWrite(SPEAKER_PIN, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(SPEAKER_PIN, LOW);
    delayMicroseconds(halfPeriod);
  }
}

// Classic Ding-Dong chime
void dingDong() {
  playTone(1047, 500);  // Ding (C6)
  delay(50);
  playTone(784, 1200);   // Dong (G5)
  delay(750);
  playTone(1047, 500);  // Ding (C6)
  delay(50);
  playTone(784, 1200);   // Dong (G5)
}

// Two-tone chime
void twoTone() {
  playTone(880, 150);   // A5
  delay(100);
  playTone(660, 250);   // E5
}

// Westminster chime (4 notes)
void westminster() {
  int notes[] = {1047, 1175, 1319, 1568}; // C6, D6, E6, G6
  for (int i = 0; i < 4; i++) {
    playTone(notes[i], 200);
    delay(50);
  }
}

void loop() {
  // Play different chimes in sequence (for testing)
  blink = !blink;
  digitalWrite(LED_BUILTIN,blink);
  
  dingDong();
  delay(2000);

  twoTone();
  delay(2000);
  
  westminster();
  delay(2000);
}
soundforpassivespeaker.txt · Last modified: by jwan

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki