Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- float smoothDistance
- int readSensorValue()
- {
- //https://www.parallax.com/sites/default/files/downloads/28995-Sharp-GP2Y0A21YK0F-IR-Datasheet.pdf
- //This is a function that reads raw data from an IR sensor.
- //Our controller gives values between 0-255, but the data is noisy and often has spikes/dips in readings.
- }
- float runningAverage(float newValue, float lastValue)
- {
- float weight = 0.1; //Greater values give higher response rate, smaller values give smoother averages.
- lastValue = weight * newValue + ( weight - 1 ) * lastValue;
- return lastValue;
- }
- //main loop. Called forever like a while(true)
- loop()
- {
- smoothDistance = runningAverage( (float)readSensorValue(), distance);
- float noisyDistance = readSensorValue();
- //This will be more reliable based on true distance
- if ( smoothDistance < 10 )
- {
- //we are close to something
- }
- else if ( smoothDistance > 200 )
- {
- //we are far from something
- }
- //This will be more likely to get triggered due to spikes in data.
- if ( noisyDistance < 10 )
- {
- //we are close to something
- }
- else if ( noisyDistance > 200 )
- {
- //we are far from something
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment