]> git.piffa.net Git - sketchbook_andrea/blob - basic/analog_input/photo_7_tonePitchFollower/photo_7_tonePitchFollower.ino
Calibrazioni
[sketchbook_andrea] / basic / analog_input / 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  Modified by A.Manni
16
17 This example code is in the public domain.
18  
19  http://arduino.cc/en/Tutorial/Tone2
20  
21  */
22
23 // These constants won't change:
24 const int sensorPin = A0;    // pin that the sensor is attached to
25 const int piezoPin  = 9;     // pin that the piezo is attached to
26
27 // variables:
28 int sensorValue = 0;         // the sensor value
29 int sensorMin   = 1023;      // minimum sensor value
30 int sensorMax   = 0;         // maximum sensor value
31 int pitch       = 0;         // pithc value for the piezo
32
33 void setup() {
34   // initialize serial communications (for debugging only):
35   Serial.begin(9600);
36     pinMode(13, OUTPUT);
37     pinMode(piezoPin, OUTPUT);
38   digitalWrite(13, HIGH);
39
40   // calibrate during the first five seconds 
41   while (millis() < 5000) {
42     sensorValue = analogRead(sensorPin);
43
44     // record the maximum sensor value
45     if (sensorValue > sensorMax) {
46       sensorMax = sensorValue;
47     }
48
49     // record the minimum sensor value
50     if (sensorValue < sensorMin) {
51       sensorMin = sensorValue;
52     }
53   }
54
55   // signal the end of the calibration period
56   digitalWrite(13, LOW);
57 }
58
59 void loop() {
60   // read the sensor:
61   int sensorValue = analogRead(sensorPin);
62   // print the sensor reading so you know its range
63   Serial.println(sensorValue);
64   // map the analog input range 
65   // to the output pitch range (120 - 1500Hz)
66   // change the minimum and maximum input numbers below
67   // depending on the range your sensor's giving:
68   pitch = map(sensorValue, sensorMin, sensorMax, 220, 3500);
69
70   // play the pitch:
71   if (sensorValue < sensorMax -50) { // Offset to prevent the piezo to ring
72                                      // all the time, check sensor polarity
73   tone(piezoPin, pitch, 10);
74   }
75   delay(1);        // delay in between reads for stability
76 }
77
78
79
80 /* Esercizi:
81  1. Implementare constrain e smoothing in questo sketch
82
83  */
84
85