I set an Arduino Nano to read the time between 2 pulses of a signal (kind of rotary encoder) to get and display an rpm value. I've done this using interrupts.

Now I'd like to add a second (kind of) encoder, which may produce 2/3/n pulses per revolution, and I'd like to display how many pulses per revolution it produces. So basically, what I need is to count the pulses of the second signal between 2 pulses of the first signal.

I tried adding a second interrupt but I get pulses = 0. Here is the last version of code I tried:

byte pin = 2;
volatile float elapsed;
volatile float previous;
float rpm;
volatile int pulses;
volatile bool flag;

void setup() {
  pinMode(pin, INPUT);
  attachInterrupt(0, elapse, RISING); 
  previous = millis();

void loop() {
  pulses = 0; // reset pulses counter

  attachInterrupt(0, elapse, RISING); // attach interrupt for rpm counter
  detachInterrupt(0); // detach interrupt for rpm counter

  if (flag == true) {
    attachInterrupt(1, count, RISING); // attach interrupt for pulses counter
    detachInterrupt(1); // detach interrupt for pulses counter
    flag = false; // reset flag

  rpm = 1000 / elapsed * 60;

  Serial.print("elapsed: "); // print resuslts
  Serial.print("rpm: ");
  Serial.print("pulses: ");

void elapse() { 
  elapsed = millis() - previous;
  previous = millis(); 
  flag = true; // set flag to activate pulses counter

void count() {

Is there a better way to handle this? Thank you :)

  • 1
    You're making it overly complicated. Just combine both functions together. Every minor interrupt you add one to a count. Every major interrupt you save that count to another variable and reset it to 0. At the same time save the time since the previous major interrupt. – Majenko May 21 '18 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.