For the “Arduino For Kooks” course, I recommend you get the Arduino Starter Kit available here.
Up until this point in the series, we have been using LEDs to manipulate light with the Arduino. For this project, we’re going to incorporate a piezo buzzer to manipulate sound for Maximum Annoyance Value! The piezo is a small element that vibrates in the presence of an electric current or–alternatively–generates an electric current when it vibrates.
The Circuit:
Connect jumper wires from the +5V and GND pins on the Arduino to the bus rails along one side of the breadboard. Connect a jumper from the +5V rail to one side of a tactile switch. Connect the other side of the switch with a jumper to one side of the next switch, and so on, until you have wired all 4 switches in series. Connect a jumper from the last switch terminal to pin A0 on the Arduino.
Connect the 220R, 1KR, and 1MR resistors to the switches as shown in the diagram.
Connect the ground lead of the piezo buzzer to the ground rail and the positive lead to pin 8 on the Arduino via jumper wires.
The Sketch:
/*
Play It Again, Sam
A rudimentary Arduino synthesizer
created 13 Sep 2012
by Scott Fitzgerald
This example code is part of the public domain.
*/
// create an array of notes
// the numbers below correspond to the frequencies of middle C, D, E, and F
int notes[] = {262, 294, 330, 349};
void setup() {
//start serial communication
Serial.begin(9600);
}
void loop() {
// create a local variable to hold the input on pin A0
int keyVal = analogRead(A0);
// send the value from A0 to the Serial Monitor
Serial.println(keyVal);
// play the note corresponding to each value on A0
if (keyVal == 1023) {
// play the first frequency in the array on pin 8
tone(8, notes[0]);
} else if (keyVal >= 990 && keyVal <= 1010) { // play the second frequency in the array on pin 8 tone(8, notes[1]); } else if (keyVal >= 505 && keyVal <= 515) { // play the third frequency in the array on pin 8 tone(8, notes[2]); } else if (keyVal >= 5 && keyVal <= 10) {
// play the fourth frequency in the array on pin 8
tone(8, notes[3]);
} else {
// if the value is out of range, play no tone
noTone(8);
}
}