Created
November 12, 2015 18:48
-
-
Save garethfoote/1ec87e8208160b3e6909 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Sound - Using a pressure sensor to change the tone of a piezo speaker. | |
* @author Gareth Foote & Berit Greinke | |
* 12th November 2015 | |
* | |
* Code adapted from here: | |
* https://learn.adafruit.com/trinket-gemma-mini-theramin-music-maker/code | |
* | |
* Note: The Arduino tone library does not work for the ATTiny85 on the | |
* Trinket and Gemma. The beep function below is similar. The beep code | |
* is adapted from Dr. Leah Buechley at | |
* http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html | |
*/ | |
int sensorPin = 1; // The number of the input pin for the pressure sensor | |
int speakerPin = 1; // The number of the output pin for the speaker | |
void setup() { | |
// Tell the Gemma that the speaker pin is an output | |
pinMode(speakerPin, OUTPUT); | |
// Tell the Gemma that the sensor pin is an input | |
pinMode(sensorPin, INPUT); | |
} | |
void loop() { | |
// Read the value of the pressure sensor (variable resistor). | |
// analogRead() returns a range of values. | |
// The value increases the more pressure is | |
// applied to our sensor. | |
int sensorReading = analogRead(sensorPin); | |
// The range of values we get from our sensorReading | |
// will vary depending on the resistance of our pressure | |
// sensor. We estimate that the range is approximately | |
// between 0 and 50 depending on the pressure sensor. | |
// The tone of the speaker is controlled by hertz. | |
// A sensible range is between 0hz and 2000hz. We | |
// therefore need to convert/map our sensorReading to this range. | |
int frequency = map(sensorReading, 0, 50, 0, 2000); | |
// We then tell the speakerPin to play a note at that | |
// frequency. | |
beep(speakerPin, frequency, 400); | |
delay(50); | |
} | |
// The function that produces the sound. | |
void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds) { | |
int x; | |
long delayAmount = (long)(1000000/frequencyInHertz); | |
long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2)); | |
for (x=0;x<loopTime;x++){ | |
digitalWrite(speakerPin,HIGH); | |
delayMicroseconds(delayAmount); | |
digitalWrite(speakerPin,LOW); | |
delayMicroseconds(delayAmount); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment