Grove soundsensor lib
soundsensor.cpp@4:89a9c205446c, 2019-01-18 (annotated)
- Committer:
- math991e
- Date:
- Fri Jan 18 10:33:01 2019 +0000
- Revision:
- 4:89a9c205446c
- Parent:
- 3:372e67c123c3
- Child:
- 5:944179f9d11f
error fix
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 | 3:372e67c123c3 | 29 | |
math991e | 3:372e67c123c3 | 30 | for(int i=0;i<100;i++){ |
math991e | 4:89a9c205446c | 31 | values[i] = sensor.read_u16(); |
math991e | 3:372e67c123c3 | 32 | wait(0.0001); |
math991e | 3:372e67c123c3 | 33 | } |
math991e | 3:372e67c123c3 | 34 | |
math991e | 3:372e67c123c3 | 35 | for(int j=0;j<100;j++){ |
math991e | 3:372e67c123c3 | 36 | sum += values[j]; |
math991e | 3:372e67c123c3 | 37 | } |
math991e | 3:372e67c123c3 | 38 | average = sum/100; |
math991e | 3:372e67c123c3 | 39 | |
math991e | 0:18d442efc99a | 40 | if(toDb){ |
math991e | 3:372e67c123c3 | 41 | return this->convertToDb(average); |
math991e | 0:18d442efc99a | 42 | }else{ |
math991e | 3:372e67c123c3 | 43 | return average; |
math991e | 0:18d442efc99a | 44 | } |
math991e | 0:18d442efc99a | 45 | } |