irSensor.ino 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. void irSensor() {
  2. static unsigned long last_interrupt_time = 0;
  3. unsigned long interrupt_time = millis();
  4. // If interrupts come faster than 200ms, assume it's a bounce and ignore
  5. if (interrupt_time - last_interrupt_time > 200)
  6. {
  7. tripSensor();
  8. }
  9. last_interrupt_time = interrupt_time;
  10. }
  11. void tripSensor() {
  12. unsigned long time = millis();
  13. if (mode == MODE_RESTING) {
  14. if (time < restExpires) return; // Ignore signals while resting
  15. mode = MODE_SPINUP;
  16. lastTime = 0;
  17. }
  18. if (mode == MODE_COUNTING && recordedTimes < maxTimes) {
  19. times[recordedTimes++] = time;
  20. if (recordedTimes == maxTimes) {
  21. mode = MODE_RESTING;
  22. restExpires = time + 30000;
  23. }
  24. }
  25. if (mode == MODE_SPINUP && lastTime == 0) {
  26. lastTime = time;
  27. showShape(4);
  28. return;
  29. }
  30. if (mode == MODE_SPINUP && lastTime != 0) {
  31. double duration = time - lastTime;
  32. double mph = durationToMph(duration);
  33. lastTime = time;
  34. showNumber(mph);
  35. return;
  36. }
  37. if (mode == MODE_COUNTING && recordedTimes == 1) {
  38. showShape(4);
  39. showNumberLAP(0);
  40. return;
  41. }
  42. if (mode == MODE_COUNTING && recordedTimes > 1) {
  43. double duration = times[recordedTimes - 1] - times[recordedTimes - 2];
  44. double mph = durationToMph(duration);
  45. showNumber(mph);
  46. showNumberLAP(recordedTimes - 1);
  47. return;
  48. }
  49. if (mode == MODE_RESTING) {
  50. double duration = averageTime();
  51. double mph = durationToMph(duration);
  52. showNumber(mph);
  53. showNumberLAP(recordedTimes - 1);
  54. return;
  55. }
  56. }
  57. double averageTime() {
  58. if (recordedTimes > 0) {
  59. double sum = 0;
  60. for (int i = 1; i < recordedTimes; i++) {
  61. sum = sum + (double)(times[i] - times[i - 1]);
  62. }
  63. double average = sum / (double)recordedTimes;
  64. return average;
  65. } else {
  66. return 0;
  67. }
  68. }
  69. double durationToMph(double duration) {
  70. seconds = (duration/1000);
  71. hours = (duration/3600000);
  72. mph = (distance/hours);
  73. return mph;
  74. }