// This code plays a simple melody on the ATtiny85.
// The melody is stored in a string called "melody".
const char melody[] = "CDEFGABcdefgab";
// The duration of each note is stored in a string called "durations".
const char durations[] = "444444444444";
// The tempo is stored in a variable called "tempo".
int tempo = 120;
// This function plays a note.
void playNote(char note, char duration) {
// Get the frequency of the note.
int frequency = noteToFrequency(note);
// Play the note for the specified duration.
tone(6, frequency, duration);
}
// This function converts a note name to a frequency.
int noteToFrequency(char note) {
switch (note) {
case 'C': return 261;
case 'D': return 294;
case 'E': return 329;
case 'F': return 349;
case 'G': return 392;
case 'A': return 436;
case 'B': return 494;
default: return 0;
}
}
// This function sets up the ATtiny85.
void setup() {
// Set the pin mode of the speaker pin.
pinMode(6, OUTPUT);
}
// This function plays the melody.
void loop() {
// For each note in the melody...
for (int i = 0; i < strlen(melody); i++) {
// Play the note.
playNote(melody[i], durations[i]);
// Wait for the note to finish playing.
delay(durationToMs(durations[i]));
}
}
// This function converts a duration to milliseconds.
int durationToMs(char duration) {
switch (duration) {
case '4': return 400;
case '8': return 200;
case '16': 100;
case '32': 50;
default: return 0;
}
}