]> git.piffa.net Git - sketchbook_andrea/blob - basic/analog_input/photo_7_tonePitchFollower/photo_7_tonePitchFollower_ino/photo_7_tonePitchFollower_ino.ino
Sensors analog
[sketchbook_andrea] / basic / analog_input / photo_7_tonePitchFollower / photo_7_tonePitchFollower_ino / photo_7_tonePitchFollower_ino.ino
1 /*
2 Pitch following
3
4 The input from a photo resistor dictates the pitch of a piezo.
5
6  
7  */
8
9 // These constants won't change:
10 const int sensorPin = A0;    // pin that the sensor is attached to
11 const int ledPin = 9;        // pin that the LED is attached to
12 int thisPitch ;
13
14 // calibration variables:
15 int sensorValue = 0;         // the sensor value
16 int sensorMin = 1023;        // minimum sensor value
17 int sensorMax = 0;           // maximum sensor value
18
19
20 void setup() {
21   // turn on LED to signal the start of the calibration period:
22   pinMode(13, OUTPUT);
23   digitalWrite(13, HIGH);
24
25   // calibrate during the first five seconds 
26   while (millis() < 5000) {
27     sensorValue = analogRead(sensorPin);
28
29     // record the maximum sensor value
30     if (sensorValue > sensorMax) {
31       sensorMax = sensorValue;
32     }
33
34     // record the minimum sensor value
35     if (sensorValue < sensorMin) {
36       sensorMin = sensorValue;
37     }
38   }
39
40   // signal the end of the calibration period
41   digitalWrite(13, LOW);
42 }
43
44 void loop() {
45   // read the sensor:
46   sensorValue = analogRead(sensorPin);
47
48   // apply the calibration to the sensor reading
49   thisPitch = map(sensorValue, sensorMin, sensorMax, 120, 1500);
50   // map the analog input range (in this case, min - max from the photoresistor)
51   // to the output pitch range (120 - 1500Hz)
52   // change the minimum and maximum input numbers below
53   // depending on the range your sensor's giving:
54   
55   // in case the sensor value is outside the range seen during calibration
56   thisPitch = constrain(sensorValue, 120, 1500);
57
58
59   
60   // play the pitch:
61   tone(ledPin, thisPitch, 10); // Tone is built in function
62   delay(1);        // delay in between reads for stability
63 }
64