0
\$\begingroup\$

I am trying to read input from an optical rotary encoder that changes its state 360 times per rotation. My code currently reads the state from an arduino digital pin as fast as possible and counts when the state changes. This works while the motor spins slowly, but it misses a lot when the motor speeds up.

How can I detect changes in the state more accurately? Can I get an IC that would do this?

void setup() {
  pinMode(12, INPUT);
  Serial.begin(9600);
}

int count;
int last;
void loop() {
  int b = digitalRead(12);
  if (b != last){
    count++;
    Serial.println(count);
  }
  last = b;
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Use interrupts arduino.cc/en/Reference/AttachInterrupt \$\endgroup\$
    – jippie
    Commented Sep 29, 2013 at 16:15
  • \$\begingroup\$ @jippie Thank you that was exactly what I was looking for \$\endgroup\$
    – stas
    Commented Sep 29, 2013 at 17:30

1 Answer 1

2
\$\begingroup\$

Why don't you try improving your code efficiency? Increasing your baud rate for your serial will really help. Just change it to Serial.begin(115200);. Then use Serial.print() less often. If all that fails, this page is fantastic: http://playground.arduino.cc/Main/RotaryEncoders

\$\endgroup\$
1
  • \$\begingroup\$ i'd be tempted to do "if ( (count % 50) == 0) Serial.println..." \$\endgroup\$ Commented Sep 29, 2013 at 22:16

Your Answer

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

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