/* Simple Square Synth This was built using bits and pieces of the "Button" tutorial, "Melody," tutorial and "Analog Input" tutorial, which can be found here: http://arduino.cc/en/Tutorial/Button http://arduino.cc/en/Tutorial/Melody http://arduino.cc/en/Tutorial/AnalogInput The circuit is as follows: Gnd -> Piezo speaker negative, 10K ohm resistor, outside leg of pot 10K ohm resister -> first leg of button +5V -> other outside leg of pot, second leg of button first leg of button (other side) -> digital pin 2 middle leg of pot -> analog pin 0 + leg of piezo spk -> digital pin 9 */ // constants won't change. They're used here to // set pin numbers: const int buttonPin = 2; // the number of the pushbutton pin const int speakerPin = 9; // the number of the piezo speaker const int sensorPin = 0; // the number of the linear trim potentiometer // variables will change: int sensorValue = 0; // the value read from the pot int noteValue = 0; // gets converted to a "note" /* From the documentation for the "Melody" example: (beginning of quoted portion) The calculation of the tones is made following the mathematical operation: timeHigh = period / 2 = 1 / (2 * toneFrequency) where the different tones are described as in the table: note frequency period timeHigh c 261 Hz 3830 1915 d 294 Hz 3400 1700 e 329 Hz 3038 1519 f 349 Hz 2864 1432 g 392 Hz 2550 1275 a 440 Hz 2272 1136 b 493 Hz 2028 1014 C 523 Hz 1912 956 (end of quoted portion) This basically generates a square wave by setting a digital pin high for the duration given by the timeHigh formula, then low for the same duration, and looping this action. The linear trim potentiometer produces values from 0 to 1023, which I crudely convert to a value from 1024 to 1, and then from 959 to 1, and then offset by 956 to give me a value from 1915 to 956 corresponding to the single octave used in the Melody example. */ void setup() { pinMode(buttonPin, INPUT); // set the button's pin for input pinMode(speakerPin, OUTPUT); // set the speaker's pin for output // (We don't need to set the pot's pin because all analog pins are input-only) } void loop(){ // The inner loop only gets executed while the button is pushed // When the button is released, it drops back out to the outer loop until // it gets pushed again while (digitalRead(buttonPin) == HIGH) { sensorValue = analogRead(sensorPin); // get the pot's value noteValue = ((((1024 - sensorValue) / 1024.0) * 959) + 956); // convert as discussed // generate a single cycle of a square wave by going high then low for the // calculated duration digitalWrite(speakerPin, HIGH); delayMicroseconds(noteValue); digitalWrite(speakerPin, LOW); delayMicroseconds(noteValue); } }