Skip to content

Instantly share code, notes, and snippets.

@polluxlabs
Last active April 17, 2020 15:29
Show Gist options
  • Save polluxlabs/b318372dfc3ee6a5d4efc0833fb9c07a to your computer and use it in GitHub Desktop.
Save polluxlabs/b318372dfc3ee6a5d4efc0833fb9c07a to your computer and use it in GitHub Desktop.
An Arduino Theremin with A-Minor Pentatonic
/*
Arduino Theremin with A minor pentatonic scale
pollux labs, 2020
All rights reserved.
*/
const int trigger = 5;
const int echo = 4;
const int piezo = 10;
int distance = 0;
int distanceHigh = 0;
int lengthOfScale = 0;
int note = 0;
//A Minor pentatonic scale
int scale[] = {
147, 165, 196, 220, 262, 294, 330, 392, 440,
523, 587, 659, 784, 880, 1047, 1175, 1319, 1568,
1760, 2093, 2349
};
//C Major scale
//int scale[] = {
// 131, 147, 165, 175, 196, 220, 247, 262, 294,
// 330, 349, 392, 440, 494, 523, 587, 659, 698,
// 784, 880, 988, 1047
//};
void setup() {
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
while (millis() < 5000) {
digitalWrite(trigger, HIGH);
digitalWrite(trigger, LOW);
distance = pulseIn(echo, HIGH);
if (distance > distanceHigh) {
distanceHigh = distance;
}
}
for (byte i = 0; i < (sizeof(scale) / sizeof(scale[0])); i++) {
lengthOfScale += 1;
}
}
void loop() {
digitalWrite(trigger, HIGH);
digitalWrite(trigger, LOW);
distance = pulseIn(echo, HIGH);
note = map(distance, 250, distanceHigh, scale[0], scale[lengthOfScale - 1]);
for (byte j = 0; j < (lengthOfScale); j++) {
if (note == scale[j]) {
tone(piezo, note);
break;
}
else if (note > scale[j] && note < scale[j + 1]) {
note = scale[j];
tone(piezo, note);
break;
}
}
delay(30);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment