Thanks for the info Phoxx, right now I'm trying to use a hardware interrupt to count pulses and divide the total time passed by the total number of pulses counted.
I'm also trying to readout other stuff and sensors, so I guess suspending the code is not really an option for me. In the end, I would like a 1-2 second fixed interval for the logged data.
Right now, for the RPM part, I have written the code below. I haven't been able to test it yet (components should come in tomorrow), but if I'm correct this should work for both a signal that varies in duty cycle or period since I'm interrupting on a falling edge (someone that can confirm this? I'm quite new to the whole interrupts game)
edit: I realised that for duty cycle it doesn't work since the time between falling edges would stay the same, maybe if I could read the time between a falling edge and the first rising edge... For now, I'm assuming that the signal is going to change by it's period/frequency, and not duty cycle.
@Riva, thanks for the code! As you can see below, right now I'm just using millis to do my timing. Is there any benefit to using another (dedicated) timer, like you did in your code? I know that the millis timer is only an 8-bit timer, but in my case it should not be able to overflow or anything since the code is at a maximum running for about 8 hours straight.
Thanks!
// define rpm variables
volatile int revs = 0;
unsigned long rpm = 0;
unsigned long lastmillis = 0;
#define rpmPin 2
// refreshrate of data logging/printing in ms (only full seconds!)
int refreshRate = 2000;
void setup() {
// connect at 115200
Serial.begin(115200);
// define pinmodes
pinMode(rpmPin, INPUT);
// setup interrupt for counting engine revolutions
attachInterrupt(digitalPinToInterrupt(rpmPin), rpm_engine, FALLING);
}
void loop() {
// RPM reading & logging/printing of data
if (millis() - lastmillis == refreshRate) { // update every one second, this will be equal to reading frequency(Hz)
detachInterrupt(digitalPinToInterrupt(rpmPin)); // disable interrupt when calculating
// RPM logging/printing
rpm = revs * 60 / (refreshRate / 1000); // convert frequency to RPM, this works for one interruption per full rotation.
Serial.print("RPM: ");
Serial.println(rpm);
// Finish line
Serial.println(" ");
Serial.flush();
revs = 0; // restart the RPM counter
lastmillis = millis(); // update lastmillis
attachInterrupt(digitalPinToInterrupt(rpmPin), rpm_engine, FALLING); // Enable interrupt
}
}
void rpm_engine() {
revs++; }