| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- void irSensor() {
- static unsigned long last_interrupt_time = 0;
- unsigned long interrupt_time = millis();
- // If interrupts come faster than 200ms, assume it's a bounce and ignore
- if (interrupt_time - last_interrupt_time > 200)
- {
- tripSensor();
- }
- last_interrupt_time = interrupt_time;
- }
- void tripSensor() {
- unsigned long time = millis();
- if (mode == MODE_RESTING) {
- if (time < restExpires) return; // Ignore signals while resting
- mode = MODE_SPINUP;
- lastTime = 0;
- }
- if (mode == MODE_COUNTING && recordedTimes < maxTimes) {
- times[recordedTimes++] = time;
- if (recordedTimes == maxTimes) {
- mode = MODE_RESTING;
- restExpires = time + 30000;
- }
- }
- if (mode == MODE_SPINUP && lastTime == 0) {
- lastTime = time;
- showShape(4);
- return;
- }
- if (mode == MODE_SPINUP && lastTime != 0) {
- double duration = time - lastTime;
- double mph = durationToMph(duration);
- lastTime = time;
- showNumber(mph);
- return;
- }
- if (mode == MODE_COUNTING && recordedTimes == 1) {
- showShape(4);
- showNumberLAP(0);
- return;
- }
- if (mode == MODE_COUNTING && recordedTimes > 1) {
- double duration = times[recordedTimes - 1] - times[recordedTimes - 2];
- double mph = durationToMph(duration);
- showNumber(mph);
- showNumberLAP(recordedTimes - 1);
- return;
- }
- if (mode == MODE_RESTING) {
- double duration = averageTime();
- double mph = durationToMph(duration);
- showNumber(mph);
- showNumberLAP(recordedTimes - 1);
- return;
- }
- }
- double averageTime() {
- if (recordedTimes > 0) {
- double sum = 0;
- for (int i = 1; i < recordedTimes; i++) {
- sum = sum + (double)(times[i] - times[i - 1]);
- }
- double average = sum / (double)recordedTimes;
- return average;
- } else {
- return 0;
- }
- }
- double durationToMph(double duration) {
- seconds = (duration/1000);
- hours = (duration/3600000);
- mph = (distance/hours);
- return mph;
- }
|