Setting Pins

Download: file
int piezoPin = 9;
int photoLightSensorPin = A0;

The pins for both the piezo and the photo light sensor are both declared as integer types. The A in front of the photo light sensor stands for analog. 

Reading the photo light sensor

Download: file
void loop() {
  //  get photo sensor value
  int photoVal = analogRead(photoLightSensorPin);
}

The photo light sensor is read within the loop(). We restricted the photoVal to integer values only (no decimal points). Then, an analogRead() was called on the photo light sensor pin to read pin data.

Creating the Pitch

Download: file
int pitch = map(photoVal, 190, 1100, 150, 1500);

The pitch variable is created to store the resulting pitch. Then, map() is called. This function takes in photoVal and photoVal's lower and upper values. Then, it maps that range to a range within 150Hz and 1500Hz

Playing the Pitch

Download: file
// play tone 
tone(piezoPin, pitch);

Tone() is passed both the pin with the Piezo and the pitch integer generated before.

The complete theremin code is below. Copy and paste it into a blank Arduino sketch, then compile and upload!

/*
 * (PROJ01) Metro (and Metro Express) Theremin
 * Desc: Super basic theremin using a light sensor and a piezo element
 * 
 * by Brent Rubell for Adafruit Industries.
*/

int piezoPin = 9;
int photoLightSensorPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  //  get photo sensor value
  int photoVal = analogRead(photoLightSensorPin);
  /* Create the pitch
   *  map() the photolightsensor value to
   *  a frequency from 150Hz to 1500Hz 
   *  more info about map() - https://www.arduino.cc/en/Reference/Map
   */
  int pitch = map(photoVal, 190, 1100, 150, 1500);
  //  play tone 
  tone(piezoPin, pitch);
}

Move your hand around the circuit to play music with your theremin! Congrats, you just built your first quest circuit.

Bored of this theremin? Let's Make It Better!

Wait...my PROJect doesn't work!

I don't hear anything

Check the wiring of both the piezo and the light sensor. You might find flipping the light sensor around will fix it.

This guide was first published on Aug 18, 2017. It was last updated on Aug 18, 2017.
This page (Code) was last updated on Apr 22, 2020.