Grove soundsensor lib
soundsensor.cpp@5:944179f9d11f, 2019-01-18 (annotated)
- Committer:
- math991e
- Date:
- Fri Jan 18 10:35:02 2019 +0000
- Revision:
- 5:944179f9d11f
- Parent:
- 4:89a9c205446c
- Child:
- 6:fb51a4b71646
Initialize array
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
math991e | 0:18d442efc99a | 1 | #include "soundsensor.h" |
math991e | 0:18d442efc99a | 2 | |
math991e | 0:18d442efc99a | 3 | soundsensor::soundsensor(PinName pin){ |
math991e | 1:29daa2bdd0c6 | 4 | soundsensor::setPin(pin); |
math991e | 0:18d442efc99a | 5 | } |
math991e | 0:18d442efc99a | 6 | |
math991e | 0:18d442efc99a | 7 | void soundsensor::setPin(PinName pin){ |
math991e | 0:18d442efc99a | 8 | this->_pin=pin; |
math991e | 0:18d442efc99a | 9 | } |
math991e | 0:18d442efc99a | 10 | |
math991e | 0:18d442efc99a | 11 | PinName soundsensor::getPin(){ |
math991e | 0:18d442efc99a | 12 | return this->_pin; |
math991e | 0:18d442efc99a | 13 | } |
math991e | 0:18d442efc99a | 14 | |
math991e | 0:18d442efc99a | 15 | float soundsensor::convertToDb(float value){ |
math991e | 3:372e67c123c3 | 16 | //return 16.801 * log (value/65535) + 9.872; |
math991e | 3:372e67c123c3 | 17 | return 1000000*20*(log(value)/log(10)))/1000000; |
math991e | 0:18d442efc99a | 18 | } |
math991e | 0:18d442efc99a | 19 | |
math991e | 0:18d442efc99a | 20 | float soundsensor::revertFromDb(float value){ |
math991e | 0:18d442efc99a | 21 | /** |
math991e | 0:18d442efc99a | 22 | *CODE NEEDS TO BE IMPLEMENTED |
math991e | 0:18d442efc99a | 23 | **/ |
math991e | 1:29daa2bdd0c6 | 24 | return 0; |
math991e | 0:18d442efc99a | 25 | } |
math991e | 0:18d442efc99a | 26 | |
math991e | 0:18d442efc99a | 27 | float soundsensor::listen(bool toDb){ |
math991e | 1:29daa2bdd0c6 | 28 | AnalogIn sensor(this->getPin()); |
math991e | 5:944179f9d11f | 29 | int values[]; |
math991e | 3:372e67c123c3 | 30 | |
math991e | 3:372e67c123c3 | 31 | for(int i=0;i<100;i++){ |
math991e | 4:89a9c205446c | 32 | values[i] = sensor.read_u16(); |
math991e | 3:372e67c123c3 | 33 | wait(0.0001); |
math991e | 3:372e67c123c3 | 34 | } |
math991e | 3:372e67c123c3 | 35 | |
math991e | 3:372e67c123c3 | 36 | for(int j=0;j<100;j++){ |
math991e | 3:372e67c123c3 | 37 | sum += values[j]; |
math991e | 3:372e67c123c3 | 38 | } |
math991e | 3:372e67c123c3 | 39 | average = sum/100; |
math991e | 3:372e67c123c3 | 40 | |
math991e | 0:18d442efc99a | 41 | if(toDb){ |
math991e | 3:372e67c123c3 | 42 | return this->convertToDb(average); |
math991e | 0:18d442efc99a | 43 | }else{ |
math991e | 3:372e67c123c3 | 44 | return average; |
math991e | 0:18d442efc99a | 45 | } |
math991e | 0:18d442efc99a | 46 | } |