Lindy Wilkins 2010
CART 352 Concordia University, Montreal
Code | Schematics | pictures
const int threshold = 2; // threshold value to decide when the detected sound is a knock or not
int sensorReading = 0; // variable to store the value read from the sensor pin
int speakerOut = 13;
int speakerOutTwo = 12;
int DEBUG = 1;
#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 ab 1661
#define b 2028 // 493 Hz
#define C 1912 // 523 Hz
#define R 0
void setup() {
pinMode(speakerOut, OUTPUT);
pinMode(speakerOutTwo, OUTPUT);
if (DEBUG) {
Serial.begin(9600);
}
}
int melody[] = { c, d, f, g, ab, a, b, c };
int beats[] = { 16, 16, 16, 16, 16, 16, 16, 16 };
int MAX_COUNT = sizeof(melody) / 2;
long tempo = 10000;
int pause = 1000;
int rest_count = 100;
int tone = 0;
int beat = 0;
long duration = 0;
int speaker = 0;
// functions
void reading(int sensorNumber){
sensorReading = analogRead(sensorNumber);
if (sensorReading >= threshold) {
Serial.println("Knock!");
if(sensorNumber % 2 == 0){
speaker = 12;
}
else {
speaker = 13;
}
playTone(beat, tone, speaker);
delayMicroseconds(pause);
}
delay(10);
Serial.println(sensorReading);
}
void playTone(int beat, int tone, int speaker) {
long elapsed_time = 0;
duration = beat * tempo;
if (tone > 0) {
while (elapsed_time < duration) {
digitalWrite(speaker,HIGH);
delayMicroseconds(tone / 2);
digitalWrite(speaker, LOW);
delayMicroseconds(tone / 2);
elapsed_time += (tone);
}
}
else {
for (int j = 0; j < rest_count; j++) {
delayMicroseconds(duration);
}
}
}
void loop() {
for(int i = 0; i < 4; i++){
tone = melody[i];
beat = beats[i];
reading(i);
}
}