Pitch follower using the tone() function
Play a pitch on a piezo speaker depending on an analog input.
This example shows how to use the tone() command to generate a pitch that follows the values of an analog input. Using a photoresistor your Arduino board becomes a simplified light theremin.
Hardware Required
Arduino board
8 ohm speaker
photoresistor
4.7K ohm resistor
100 ohm resistor
hook-up wires
breadboard
Circuit
Connect one terminal of your speaker to digital pin 9 through a 100 ohm resistor, and its other terminal to ground. Power your photoresistor with 5V, and connect it to analog 0 with the addition of a 4.7K resistor to ground.
Schematic
Code
The code for this example is very simple. Just take an analog input and map its values to a range of audible pitches. Humans can hear from 20 - 20,000Hz, but 120 - 1,500 usually works pretty well for this sketch.
You'll need to get the actual range of your analog input for the mapping. In the circuit shown, the analog input value ranged from about 400 to about 1,000. Change the values in the map() command to match the range for your sensor.
The sketch is as follows:
1/*2
3 Pitch follower4
5 Plays a pitch that changes based on a changing analog input6
7 circuit:8
9 - 8 ohm speaker on digital pin 910
11 - photoresistor on analog 0 to 5V12
13 - 4.7 kilohm resistor on analog 0 to ground14
15 created 21 Jan 201016
17 modified 31 May 201218
19 by Tom Igoe, with suggestion from Michael Flynn20
21 This example code is in the public domain.22
23 https://www.arduino.cc/en/Tutorial/Tone224
25*/26
27void setup() {28
29 // initialize serial communications (for debugging only):30
31 Serial.begin(9600);32}33
34void loop() {35
36 // read the sensor:37
38 int sensorReading = analogRead(A0);39
40 // print the sensor reading so you know its range41
42 Serial.println(sensorReading);43
44 // map the analog input range (in this case, 400 - 1000 from the photoresistor)45
46 // to the output pitch range (120 - 1500Hz)47
48 // change the minimum and maximum input numbers below depending on the range49
50 // your sensor's giving:51
52 int thisPitch = map(sensorReading, 400, 1000, 120, 1500);53
54 // play the pitch:55
56 tone(9, thisPitch, 10);57
58 delay(1); // delay in between reads for stability59}
Learn more
You can find more basic tutorials in the built-in examples section.
You can also explore the language reference, a detailed collection of the Arduino programming language.
Last revision 2015/08/11 by SM
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.