/* * 1 inch radius wheel, C = 2pir = 6.283 inches / rev * 5 degree encoder wheel, (360 degrees/rev) / (5 degrees/pin change) = 72 pin change/rev) * conversion factor, (6.283 inches/rev) / (72 pin change/rev) = 0.08727 inches / pin change * speedometer */ const int window_size = 72; // (360 degrees/rev)/ (5 degrees / pin change) = 72 pin change / rev) void speedometer(uint8_t pin) { static uint8_t state = 0; static uint16_t pulse_count; static uint32_t stopwatch_pressed; const float pinchange_to_inches = 0.08727; uint8_t wheel = digitalRead(pin); switch (state) { case 0: // start test pulse_count = 0; stopwatch_pressed = millis(); // start the stop watch state = 1; break; case 1: // statistics package if (pin_change(wheel)) pulse_count++; // increment the pulse counter if(pulse_count >= window_size){ float time_period = (millis() - stopwatch_pressed)/1000.0; // in seconds float s = (pinchange_to_inches * (float) pulse_count)/time_period; /* Serial.print(pulse_count); Serial.print(" "); Serial.print(time_period); Serial.print(" "); */ Serial.println(s); state = 0; } break; } // switch-case } // speedometer /* simulate with polling a pin change interrupt */ bool pin_change(uint8_t value){ // value may be HIGH or LOw static uint8_t last_value = value; // initalize to current value bool trigger = false; if (value != last_value){ last_value = value; // update to current value trigger = true; } return trigger; } /* running average */ uint16_t runningAverage(uint16_t val) { static uint16_t window[window_size] = {0}; // window into the data stream static int index = 0; // index pointer into the circular buffer static uint16_t sum = 0; // sum of the readings in the buffer uint16_t A_0 = window[index]; // oldest value uint16_t A_1 = val; // newest value sum += A_1 - A_0; // subtract out the oldest reading and // replace with the newest reading. // update window[index] = A_1; // update the buffer index++; // move pointer if(index >= window_size){ index = 0; } return sum/window_size; // integer division (round down) } int waitForKey() { while (!Serial.available()); // (!Serial) also works Serial.print("Hit any key to continue."); while (!Serial.available()); // wait for the key while(Serial.available()) Serial.read(); // clear the input buffer Serial.println(" Running code."); }