Guest User

Untitled

a guest
Feb 8th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1.  
  2.  
  3. float smoothDistance
  4.  
  5. int readSensorValue()
  6. {
  7. //https://www.parallax.com/sites/default/files/downloads/28995-Sharp-GP2Y0A21YK0F-IR-Datasheet.pdf
  8. //This is a function that reads raw data from an IR sensor.
  9. //Our controller gives values between 0-255, but the data is noisy and often has spikes/dips in readings.
  10. }
  11.  
  12.  
  13. float runningAverage(float newValue, float lastValue)
  14. {
  15. float weight = 0.1; //Greater values give higher response rate, smaller values give smoother averages.
  16. lastValue = weight * newValue + ( weight - 1 ) * lastValue;
  17. return lastValue;
  18. }
  19.  
  20.  
  21. //main loop. Called forever like a while(true)
  22. loop()
  23. {
  24. smoothDistance = runningAverage( (float)readSensorValue(), distance);
  25. float noisyDistance = readSensorValue();
  26.  
  27. //This will be more reliable based on true distance
  28. if ( smoothDistance < 10 )
  29. {
  30. //we are close to something
  31. }
  32. else if ( smoothDistance > 200 )
  33. {
  34. //we are far from something
  35. }
  36.  
  37. //This will be more likely to get triggered due to spikes in data.
  38. if ( noisyDistance < 10 )
  39. {
  40. //we are close to something
  41. }
  42. else if ( noisyDistance > 200 )
  43. {
  44. //we are far from something
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment