]> git.piffa.net Git - arduino/blob - books/ArduinoNextSteps-master/ArduinoNextSteps/sketch_13_05_band_stop_due/sketch_13_05_band_stop_due.ino
first commit
[arduino] / books / ArduinoNextSteps-master / ArduinoNextSteps / sketch_13_05_band_stop_due / sketch_13_05_band_stop_due.ino
1 // sketch_13_05_band_stop_due
2
3 const long samplePeriod = 23L; // micro seconds
4
5 const int analogInPin = A0;
6 const int analogOutPin = DAC0;
7
8 // 1000 to 1500 band stop filter
9 // 44100 Hz sample rate
10 // http://www.schwietering.com/jayduino/filtuino/index.php?characteristic=bu&passmode=bs&order=1&usesr=usesr&sr=44100&frequencyLow=1000&noteLow=&frequencyHigh=1500&noteHigh=&pw=pw&calctype=float&run=Send
11
12 //Band stop butterworth filter order=1 alpha1=0.022675736961451 alpha2=0.034013605442177 
13 class filter
14 {
15         public:
16                 filter()
17                 {
18                         v[0]=0.0;
19                         v[1]=0.0;
20                 }
21         private:
22                 float v[3];
23         public:
24                 float step(float x)
25                 {
26                         v[0] = v[1];
27                         v[1] = v[2];
28                         v[2] = (9.655920584452e-1 * x)
29                                  + ( -0.9311841169 * v[0])
30                                  + (  1.9018448769 * v[1]);
31                         return 
32                                  (v[0] + v[2])
33                                 - 1.969615 * v[1];
34                 }
35 };
36
37
38 filter f;
39
40
41 void setup()                 
42 {
43   // http://www.djerickson.com/arduino/
44   REG_ADC_MR = (REG_ADC_MR & 0xFFF0FFFF) | 0x00020000;
45   analogWriteResolution(8);
46   analogReadResolution(8);
47 }
48
49 void loop()                   
50 {
51   static long lastSampleTime = 0;
52   long timeNow = micros();
53   if (timeNow > lastSampleTime + samplePeriod)
54   {
55     int raw = analogRead(analogInPin);
56     
57     float filtered = f.step(raw);
58     
59     analogWrite(analogOutPin, (int)filtered);
60     lastSampleTime = timeNow;
61   }
62 }