2

I'm working on a quadrature encoder(with a 500ppr codewheel) with a Channel A, B and an Index pulse output. Using an Arduino Mega I'm counting the number of pulses on Channel A on the rising edge. The code for counting pulses on channel A using an interrupt is straight forward enough with plenty of sources and examples out there to work with.

I've used the the code below to the count the pulses(in an increasing manner). What I'm trying to figure out is how I can reset the overall count using a second interrupt. The second interrupt is invoked when the Index channel pulses high.So in another words when the index channel pulses to indicate a full rotation on the code wheel the main count will reset to zero

#define CHA 2
#define CHB 3
#define CHI 19

volatile int count = 0; 
volatile byte INTFLAG1 = 0; 

void setup() 
{ 
  pinMode(CHA, INPUT);
  pinMode(CHB, INPUT);
  pinMode(CHI,INPUT);

  Serial.begin(9600); 
  Serial.println(count);

  attachInterrupt(0, flag, RISING); 

 }

void loop() 
   {

       if (INTFLAG1)   
             {
               Serial.println(count);
               INTFLAG1 = 0; // clear flag
             } 


    } 


void flag()
    {
       INTFLAG1 = 1;
       if (digitalRead(CHA) && !digitalRead(CHB)) 
               {
                count++ ;
               }
     }

Is it possible to implement the reset of the main pulse count with a second interrupt as described?

From what I've read interrupts work at the same level of priority- so I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested

Any help is appreciated if anyone has done anything like this using interrupts or can point me in the right direction.

1 Answer 1

1

Is it possible to implement the reset of the main pulse count with a second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19, which is interrupt 4 on the Mega, so you can simply

attachInterrupt(4, reset, RISING);

in setup(), where reset() is a function that resets the counter:

void reset()
{
    count = 0;
}

I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being serviced when a second interrupt fires, the second one will just wait for the first one to finish. This approach works fine as long as you do not have interrupt handlers that take too long to execute.

1
  • Very Straightforward and works accordingly.Thanks for the information.
    – Tino88
    Jul 12, 2016 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.