December 3, 2024

The circuit for this lesson is simple, we use a passive buzzer. The negative of the buzzer goes to the GND and positive goes to PIN 9 on the arduino.

 

int buzzerPIN = 9;
#define c 261
#define d 294
#define e 329
#define f 349
#define g 392
#define a 440
#define b 493
#define C 523
#define R 0
long tempo = 10;

int melody[] = { C, b, g, C, b, e, R, C, c, g, a, C };
int beats[] = { 32, 16, 16, 8, 8, 16, 32, 16, 16, 16, 8, 8 };
int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

// Set overall tempo

// Set length of pause between notes
int pause = 1000;
// Loop variable to increase Rest length

}

void playTone(int buz, int freq, int duration){

int playduration = duration * tempo;
tone(buz,freq,playduration);

}

void loop() {
// put your main code here, to run repeatedly:

for (int i=0; i<MAX_COUNT; i++) {
int tonep = melody[i];
int beatp = beats[i];

playTone(buzzerPIN,tonep,beatp);
delay(beatp * 20);
Serial.print(buzzerPIN);
Serial.print(“:”);
Serial.print(tonep);
Serial.print(” “);
Serial.print(beatp);
Serial.print(” “);

}

}