Hi,
I'm a beginner to Arduino, so I've been trying hard to break apart and understand the tutorial code for making sound with the Arduino and a piezo speaker.
MY GOAL: When I press a certain key on the keyboard, it will light up a specific LED and play a specific note.
MY PROBLEM: I can't seem to discern from the tutorial code what the actual command is to play a note. I tried cutting and pasting the essential elements from the tutorial into my LED code. But it doesn't seem to work. I think my understanding of how a note is played and how to tell it WHAT note to play isn't good enough. My code is turning on the lights correctly, but no sound is coming out. (the speaker is functioning well) My code is clearly wrong, but I need help on fixing it.
PLEASE HELP!
here's my best attempt code:
// TONES ==========================================
// Start by defining the relationship between
// note, period, & frequency.
#define c 3830 // 261 Hz
#define d 3400 // 294 Hz
#define e 3038 // 329 Hz
#define f 2864 // 349 Hz
#define g 2550 // 392 Hz
#define a 2272 // 440 Hz
#define b 2028 // 493 Hz
#define C 1912 // 523 Hz
// Define a special note, 'R', to represent a rest
#define R 0
int outputPin1 = 13;
int outputPin2 = 12;
int outputPin3 = 11;
int val;
int speakerOut = 9;
void setup()
{
Serial.begin(9600);
pinMode(outputPin1, OUTPUT);
pinMode(outputPin2, OUTPUT);
pinMode(outputPin3, OUTPUT);
pinMode(speakerOut, OUTPUT);
}
// Loop variable to increase Rest length
int rest_count = 100; //<-BLETCHEROUS HACK; See NOTES
// Initialize core variables
int tone = 0;
int beat = 0;
long duration = 0;
// PLAY TONE ==============================================
// Pulse the speaker to play a tone for a particular duration
void playTone() {
long elapsed_time = 0;
if (tone > 0) { // if this isn't a Rest beat, while the tone has
// played less long than 'duration', pulse speaker HIGH and LOW
while (elapsed_time < duration) {
digitalWrite(speakerOut,HIGH);
delayMicroseconds(tone / 2);
// DOWN
digitalWrite(speakerOut, LOW);
delayMicroseconds(tone / 2);
// Keep track of how long we pulsed
elapsed_time += (tone);
}
}
else { // Rest beat; loop times delay
for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count
delayMicroseconds(duration);
}
}
}
void loop()
{
if (Serial.available()) {
val = Serial.read();
if (val == 'a') {
digitalWrite(outputPin1, HIGH);
tone = a;
playTone();
delay(500);
digitalWrite(outputPin1, LOW);
}
if (val == 'b') {
digitalWrite(outputPin2, HIGH);
tone = b;
playTone();
delay(500);
digitalWrite(outputPin2, LOW);
}
if (val == 'c') {
digitalWrite(outputPin3, HIGH);
tone = c;
playTone();
delay(500);
digitalWrite(outputPin3, LOW);
}
}
}