Skip to content

Instantly share code, notes, and snippets.

@jeffeb3 jeffeb3/rpm_test.ino
Last active Feb 16, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.