Humans can hear sounds in a specific frequency range: 20Hz – 20kHz
Each tone is defined by the sound frequency, below is a full gamma: C D E F G A B C
Piezo play melody project on tinkercad
How to make Basic piano with Arduino
How to play any melody with Arduino
// pitches for C scale (tones):
int c4 = 261;
int d4 = 293;
int e4 = 330;
int f4 = 350;
int g4 = 392;
int a4 = 440;
int b4 = 494;
int c5 = 523;
Tones are played in rhytm which is represented by notes:
// rhytm
int tempo = 1000;
int w = tempo; //whole note - 4 beats
int h = tempo/2; // half note - 2 beats
int q = tempo/4; // quarter note - 1 beat
int e = tempo/8; // eight note - 1/2 beat
int s = tempo/16; // sixteen note - 1/4 beat
How to play sound with piezo
Tones can be played with tone() method, where pin, frequency(pitch) and rythm need to be provided.
tone(pin, frequency)
tone(pin, frequency, duration)
Play a single tone with piezo in Arduino
int speakerPin = 9;
// rhytm
int tempo = 1000;
int w = tempo;
int h = tempo/2;
int q = tempo/4;
int e = tempo/8;
int s = tempo/16;
// tones,pitch for C scale
int c4 = 261;
int d4 = 293;
int e4 = 330;
int f4 = 350;
int g4 = 392;
int a4 = 440;
int b4 = 494;
int c5 = 523;
void playTone(int t, int rythm)
{
tone(speakerPin, t, rythm);
}
void setup()
{
pinMode(speakerPin, OUTPUT);
playTone(e4, h);
}
void loop(){}
How to play melody with Piezo in Arduino
int speakerPin = 9;
// rhytm
int tempo = 1000;
int w = tempo;
int h = tempo/2;
int q = tempo/4;
int e = tempo/8;
int s = tempo/16;
// pitches for C scale
int c4 = 261;
int d4 = 293;
int e4 = 330;
int f4 = 350;
int g4 = 392;
int a4 = 440;
int b4 = 494;
int c5 = 523;
int melody[] = {c4, d4, e4, f4, g4, a4, b4, c5};
void playMelody()
{
for(int i=0; i<8; i++)
{
tone(speakerPin, melody[i], h);
delay(h);
}
}
void setup()
{
pinMode(speakerPin, OUTPUT);
playMelody();
}
void loop(){}
How to play twinkle twinkle little star / Pirates Of The Caribbean with Arduino
int speakerPin = 9;
// rhytm
int tempo = 1000;
int w = tempo;
int h = tempo/2;
int q = tempo/4;
int e = tempo/8;
int s = tempo/16;
// pitches for C scale
int c4 = 261;
int d4 = 293;
int e4 = 330;
int f4 = 350;
int g4 = 392;
int a4 = 440;
int b4 = 494;
int c5 = 523;
// Twinkle twinkle little star
int melody[] = {c4,c4,g4,g4,a4,a4,g4,f4,f4,e4,e4,d4,d4,c4};
int rhytm[] = {q,q,q,q,q,q,h,q,q,q,q,q,q,h};
// Pirates Of The Caribbean
//int melody[] = {a4,c4,d4,d4,d4,e4,f4,f4,f4,g4,e4,e4,d4,c4,d4};
//int rhytm[] = {e,e,q,q,e,e,q,q,e,e,q,q,e,e,h};
void playMelody()
{
int len = sizeof(melody)/sizeof(melody[0]);
for(int i=0; i<len; i++)
{
tone(speakerPin, melody[i], rhytm[i]);
delay(rhytm[i]*2);
}
}
void setup()
{
pinMode(speakerPin, OUTPUT);
playMelody();
}
void loop(){}
Simple Arduino piano
int tones[] = {261, 293, 330, 350, 392, 440};
int keys[] = {2,3,4,5,6,7};
int speakerPin = 9;
void setup()
{
pinMode(speakerPin, OUTPUT);
}
void loop()
{
for(int i=0; i<6; i++)
{
if(digitalRead(keys[i])==true)
{
tone(speakerPin, tones[i],50);
}
}
}