Grove soundsensor lib
soundsensor.cpp@6:fb51a4b71646, 2019-01-21 (annotated)
- Committer:
- math991e
- Date:
- Mon Jan 21 13:08:11 2019 +0000
- Revision:
- 6:fb51a4b71646
- Parent:
- 5:944179f9d11f
- Child:
- 7:6f0c583b4f54
bugfixing
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 | 6:fb51a4b71646 | 16 | return 16.801 * log(value/65535) + 9.872; |
math991e | 0:18d442efc99a | 17 | } |
math991e | 0:18d442efc99a | 18 | |
math991e | 0:18d442efc99a | 19 | float soundsensor::revertFromDb(float value){ |
math991e | 0:18d442efc99a | 20 | /** |
math991e | 0:18d442efc99a | 21 | *CODE NEEDS TO BE IMPLEMENTED |
math991e | 0:18d442efc99a | 22 | **/ |
math991e | 1:29daa2bdd0c6 | 23 | return 0; |
math991e | 0:18d442efc99a | 24 | } |
math991e | 0:18d442efc99a | 25 | |
math991e | 0:18d442efc99a | 26 | float soundsensor::listen(bool toDb){ |
math991e | 1:29daa2bdd0c6 | 27 | AnalogIn sensor(this->getPin()); |
math991e | 6:fb51a4b71646 | 28 | int values[] = {}; |
math991e | 6:fb51a4b71646 | 29 | float sum; |
math991e | 6:fb51a4b71646 | 30 | float average; |
math991e | 3:372e67c123c3 | 31 | |
math991e | 3:372e67c123c3 | 32 | for(int i=0;i<100;i++){ |
math991e | 4:89a9c205446c | 33 | values[i] = sensor.read_u16(); |
math991e | 3:372e67c123c3 | 34 | wait(0.0001); |
math991e | 3:372e67c123c3 | 35 | } |
math991e | 3:372e67c123c3 | 36 | |
math991e | 3:372e67c123c3 | 37 | for(int j=0;j<100;j++){ |
math991e | 3:372e67c123c3 | 38 | sum += values[j]; |
math991e | 3:372e67c123c3 | 39 | } |
math991e | 3:372e67c123c3 | 40 | average = sum/100; |
math991e | 3:372e67c123c3 | 41 | |
math991e | 0:18d442efc99a | 42 | if(toDb){ |
math991e | 3:372e67c123c3 | 43 | return this->convertToDb(average); |
math991e | 0:18d442efc99a | 44 | }else{ |
math991e | 3:372e67c123c3 | 45 | return average; |
math991e | 0:18d442efc99a | 46 | } |
math991e | 0:18d442efc99a | 47 | } |