Help with rotary encoder

Hi!

Please someone can tell me what I need change on code below to use the pins 2 and 8 with a rotary encoder?

#include <rotary.h>

Rotary r = Rotary(2, 3);

void setup() {
  Serial.begin(9600);
  PCICR |= (1 << PCIE2);
  PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
  sei();
}

void loop() {

}

ISR(PCINT2_vect) {
  unsigned char result = r.process();
  if (result) {
    Serial.println(result == DIR_CW ? "Right" : "Left");
  }
}

EDIT: I'm using an Arduino Uno.

Thanks in advance.

My guess (and it is no more than that) is to change the line to Rotary r = Rotary(2, 8 ); - but maybe you have already tried that.

You should not have the line Serial.println(result == DIR_CW ? "Right" : "Left"); in your ISR.

Just have the ISR save a value to a variable and set a flag to say the variable has been written. Then in loop() you can print the value if the flag is set.

...R

Thanks for your reply.

It doesn't works.

I found this code:

#include <rotary.h>

Rotary r = Rotary(8, 9);

void setup() {
  Serial.begin(9600);
  PCICR |= (1 << PCIE0);
  PCMSK0 |= (1 << PCINT4) | (1 << PCINT5);
  sei();
}

void loop() {

}

ISR(PCINT0_vect) {
  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }
}

Changing "Rotary(8, 9)" to "Rotary(8, 2)" this example works but with my main code doesn't work because I have the pin 9 used to other function.

I don't know what I need use here:

  PCICR |= (1 << PCIE0);
  PCMSK0 |= (1 << PCINT4) | (1 << PCINT5);

  ISR(PCINT0_vect)

Looking for this: Arduino Playground - Pins

I can see that pin 2 is PCMSK2 PCINT18 and pin 8 is PCMSK0 PCINT0

Best regards.

Read this first
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
than keep in mind that PCINT will trigger on ANY changes.

When I have used pin change interrupts on the UNO digital pins 8 and 9 my code looked like this

PCICR |= (1<<PCIE0);//enable group interrupts on PORTB PCINT[7:0] Digital pins 8-13
  PCMSK0 |= (1<<PCINT0);//enable interrupt pin 8
  PCMSK0 |= (1<<PCINT1);//enable interrupt pin 9

The ISR for those pins is indeed ISR (PCINT0_vect) which handle pin change interrupts for D8 to D13.

With the code you posted PCINT4 and PCINT5 should be for pins 12 and 13.

I don't know how rotary.h works, and whether or not it can deal with pins on different ports. The pin pairs 2,3 (PortD) and 8,9(PortB) and A0,A1(PortC) are frequently used because they are on the same Port and that fact makes it simple to check what has happened when an interrupt is triggered.

You say you cant use pin9. What about 8 and another pin on PortB. The set up for PCMSK0 will have the bit shift into PCINT2 Pin10; PCINT3 Pin11; PCINT4 Pin12 and PCINT5 Pin 13.