Grove soundsensor lib

soundsensor.cpp

Committer:
math991e
Date:
2019-01-23
Revision:
9:c38836e5d1f5
Parent:
8:5b4b258eb1da

File content as of revision 9:c38836e5d1f5:

/**
* @file soundsensor.cpp
* @brief this cpp file is where all the logic is handled.
*
* @author Nikolaj M. & Mathias R.
*
* @date 23/1/2019
*/

#include "soundsensor.h"

/**
* Constructor that sets pin to to take analog input form.
* @author Nikolaj M. & Mathias R.
* @param pin The pin that the sound sensor is placed
* @date 23/1/2019
*/  
soundsensor::soundsensor(PinName pin){
    soundsensor::setPin(pin);
}

/**
* Set function to set pin where sound sensor is placed.
* @author Nikolaj M. & Mathias R.
* @param pin The pin that the sound sensor is placed
* @date 23/1/2019
*/
void soundsensor::setPin(PinName pin){
    this->_pin=pin;
}


/**
* Get function to get pin where sound sensor is placed.
* @author Nikolaj M. & Mathias R.
* @return pin The pin that the sound sensor is placed
* @date 23/1/2019
*/
PinName soundsensor::getPin(){
    return this->_pin;
}

/**
* Function to convert sound sensor input to DB.
* @author Nikolaj M. & Mathias R.
* @input value Input value from sound sensor.
* @date 23/1/2019
*/
float soundsensor::convertToDb(float value){
    return 16.801 * log(value/65535) + 9.872;
}


/**
* Function to convert sound sensor DB to raw input.
* @author Nikolaj M. & Mathias R.
* @input value DB value from sound sensor.
* @date 23/1/2019
*/
float soundsensor::revertFromDb(float value){
/**
*CODE NEEDS TO BE IMPLEMENTED
**/
    return 0;
}


/**
* Takes raw input from sound sensor returns Db or raw input depending of input parameter in function.
* @author Nikolaj M. & Mathias R.
* @input toDb value that sets to true or false depending if return should be db og raw input.
* @date 23/1/2019
*/
float soundsensor::listen(bool toDb){
    AnalogIn sensor(this->getPin());
    int values[100 + 1];
    float sum;
    float average;
    
    ///Run through for loop to get average of 100 readings to make an more avarage calculation
    for(int i=0;i<100;i++){
        ///This calculation of db is not precise and reliable
        values[i] = soundSensor.read() * 3.3; 
        wait(0.0001);
    }
 
    for(int j=0;j<100;j++){
        sum += values[j];   
        }
    average = sum/100;
    
    ///This returns either db or raw input depending of paramater input of function
    if(toDb){
        return this->convertToDb(average);
    }else{
        return average;
    }
}