This is an AI random melody composer for arduino uno r3, writing the command componi in the serial monitor and pressing return key it will make a new melody everytime. Use the buzzer in pin 5 and gnd.
#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
}
}
Sorry @jremington but Wokwi can not make sound from high frequency PWM signals
Wokwi has extra things to make the Arduino tone() function sound smooth in the simulation in the browser.
Here the code for a melody random composer for arduino uno r3 and buzzer in pin 5 and gnd:
#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() {
composeRandomMelody();
delay(2000); // Pausa di 2 secondi tra le composizioni
}
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
}
}