Skip to content

Instantly share code, notes, and snippets.

@jeffeb3
Last active February 16, 2018 03:53
Show Gist options
  • Save jeffeb3/9cd8c6958de6293345c6e3f369b74684 to your computer and use it in GitHub Desktop.
Save jeffeb3/9cd8c6958de6293345c6e3f369b74684 to your computer and use it in GitHub Desktop.
Measure RPM from a piece of tape spinning on a fast thing.
// These aren't special, just use ints.
const int IR = 4;
const int PHOTO = 2;
// These are coming from the "micros()" function, so that dictates an unsigned long
volatile unsigned long rpm_value;
volatile unsigned long prev_rpm_time = 0;
volatile unsigned long current_rpm_time = 0;
float rpmmath;
float smooth_rpm = 0.0; // Be sure you initialize this.
void setup() {
// Power the LED
pinMode(IR, OUTPUT);
digitalWrite(IR, HIGH);
pinMode(PHOTO, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PHOTO), rpm_falling, FALLING);
Serial.begin(9600);
}
const float MICROS_PER_MINUTE = 60.0 * 1000 * 1000;
const float ALPHA = 0.10;
void loop() {
rpmmath = MICROS_PER_MINUTE / rpm_value;
smooth_rpm += ALPHA * (rpmmath - smooth_rpm);
Serial.print("RPM In = ");
Serial.print(smooth_rpm);
Serial.print(" raw = ");
Serial.println(rpmmath);
delay(200);
}
void rpm_falling() {
// Store the time of the rising.
current_rpm_time = micros();
// Compute the delta time.
rpm_value = current_rpm_time - prev_rpm_time;
// Store the time of the rising for the next time.
prev_rpm_time = current_rpm_time;
// Now, add the interrupt.
attachInterrupt(digitalPinToInterrupt(PHOTO), rpm_falling, FALLING);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment