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