]> git.piffa.net Git - sketchbook_andrea/blob - oggi/photo_7_tonePitchFollower/photo_7_tonePitchFollower.ino
Analog
[sketchbook_andrea] / oggi / photo_7_tonePitchFollower / photo_7_tonePitchFollower.ino
1 /*
2   Pitch follower
3  
4  Plays a pitch that changes based on a changing analog input
5  
6  circuit:
7  * 8-ohm speaker on digital pin 8
8  * photoresistor on analog 0 to 5V
9  * 4.7K resistor on analog 0 to ground
10  
11  created 21 Jan 2010
12  modified 31 May 2012
13  by Tom Igoe, with suggestion from Michael Flynn
14
15 This example code is in the public domain.
16  
17  http://arduino.cc/en/Tutorial/Tone2
18  
19  */
20
21 // These constants won't change:
22 const int sensorPin = A0;    // pin that the sensor is attached to
23 const int ledPin = 9;        // pin that the LED is attached to
24
25 // variables:
26 int sensorValue = 0;         // the sensor value
27 int sensorMin = 1023;        // minimum sensor value
28 int sensorMax = 0;           // maximum sensor value
29
30 void setup() {
31   // initialize serial communications (for debugging only):
32   Serial.begin(9600);
33     pinMode(13, OUTPUT);
34   digitalWrite(13, HIGH);
35
36   // calibrate during the first five seconds 
37   while (millis() < 5000) {
38     sensorValue = analogRead(sensorPin);
39
40     // record the maximum sensor value
41     if (sensorValue > sensorMax) {
42       sensorMax = sensorValue;
43     }
44
45     // record the minimum sensor value
46     if (sensorValue < sensorMin) {
47       sensorMin = sensorValue;
48     }
49   }
50
51   // signal the end of the calibration period
52   digitalWrite(13, LOW);
53 }
54
55 void loop() {
56   // read the sensor:
57   int sensorReading = analogRead(sensorPin);
58   // print the sensor reading so you know its range
59   Serial.println(sensorReading);
60   // map the analog input range (in this case, 400 - 1000 from the photoresistor)
61   // to the output pitch range (120 - 1500Hz)
62   // change the minimum and maximum input numbers below
63   // depending on the range your sensor's giving:
64   int thisPitch = map(sensorReading, sensorMin, sensorMax, 220, 3500);
65
66   // play the pitch:
67   if (sensorReading < sensorMax -50) {
68   tone(ledPin, thisPitch, 10);
69   }
70   delay(1);        // delay in between reads for stability
71 }
72
73
74
75
76
77