// Forum: https://forum.arduino.cc/t/ai-random-melody-composer-arduino-uno-r3/1220467
// This Wokwi project: https://wokwi.com/projects/388939478540441601
#define BUZZER_PIN 5 // Usa il numero del pin diretto per il buzzer
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
command.trim(); // Rimuovi eventuali spazi bianchi extra
if (command.equalsIgnoreCase("componi")) {
composeRandomMelody();
}
}
}
void composeRandomMelody() {
for (int i = 0; i < 8; i++) {
int randomNote = random(1, 8);
playNote(getNoteFrequency(randomNote), 500);
delay(100);
}
}
void playNote(int frequency, int duration) {
tone(BUZZER_PIN, frequency, duration);
delay(duration + 50);
noTone(BUZZER_PIN);
}
int getNoteFrequency(int noteIndex) {
switch (noteIndex) {
case 1:
return 262; // Do
case 2:
return 294; // Re
case 3:
return 330; // Mi
case 4:
return 349; // Fa
case 5:
return 392; // Sol
case 6:
return 440; // La
case 7:
return 494; // Si
default:
return 0; // Nota non valida
}
}Type "componi" in the Serial Monitor