/ Trinket_Gemma_Mini_Theramin / Trinket_Gemma_Mini_Theramin.ino
Trinket_Gemma_Mini_Theramin.ino
1 // SPDX-FileCopyrightText: 2017 Limor Fried/ladyada for Adafruit Industries 2 // SPDX-FileCopyrightText: 2017 Phillip Burgess for Adafruit Industries 3 // 4 // SPDX-License-Identifier: MIT 5 /* Adafruit Trinket/Gemma Example: Simple Theramin 6 7 Read the voltage from a Cadmium Sulfide (CdS) photocell voltage 8 divider and output a corresponding tone to a piezo buzzer 9 10 Wiring: Photocell voltage divider center wire to GPIO #2 11 (analog 1) and output tone to GPIO #0 (digital 0) 12 13 Note: The Arduino tone library does not work for the ATTiny85 on the 14 Trinket and Gemma. The beep function below is similar. The beep 15 code is adapted from Dr. Leah Buechley at 16 http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html 17 */ 18 19 #define SPEAKER 0 // Speaker connected to this DIGITAL pin # 20 #define PHOTOCELL 1 // CdS photocell connected to this ANALOG pin # 21 #define SCALE 2.0 // You can change this to change the tone scale 22 23 void setup() { 24 // Set SPEAKER pin to output to drive the piezo buzzer (important) 25 pinMode(SPEAKER, OUTPUT); 26 } 27 28 void loop() { 29 // Read PHOTOCELL analog pin for the current CdS divider voltage 30 int reading = analogRead(PHOTOCELL); 31 // Change the voltage to a frequency. You can change the values 32 // to scale your frequency range. 33 int freq = 220 + (int)(reading * SCALE); 34 // Output the tone to SPEAKER pin. You can change the '400' 35 // to different times (in milliseconds). 36 beep(SPEAKER, freq, 400); 37 delay(50); // Delay a bit between notes (also adjustable to taste) 38 } 39 40 // The sound-producing function 41 void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds) 42 { // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html 43 int x; 44 long delayAmount = (long)(1000000 / frequencyInHertz); 45 long loopTime = (long)((timeInMilliseconds * 1000) / (delayAmount * 2)); 46 for (x = 0; x < loopTime; x++) { 47 digitalWrite(speakerPin, HIGH); 48 delayMicroseconds(delayAmount); 49 digitalWrite(speakerPin, LOW); 50 delayMicroseconds(delayAmount); 51 } 52 }