ArduinoGeneral

Problem with rotary encoders and attachInterrupts

userHead Account cancelled 2016-04-05 07:56:59 2159 Views1 Replies
Hi ! I have a strange behaviour with rotary encoders. It's already detailed on Arduino forum :

https://forum.arduino.cc/index.php?topic=391250.0

Any idea ?

Thanks !
2016-04-06 02:19:48 HI reseaux,

I read your link, have you tried:

1) To make the Arduino board (328 based) and motor&encoder to be at the same ground (same GND)?

2) The code given by dlloyd to deal with the noise effect.

Code: Select all
#define LEFT 0
#define RIGHT 1
const unsigned long interval = 200;              //interrupt debounce interval (µs)
volatile unsigned long timeNow[2] = {0, 0};
volatile unsigned long timePrev[2] = {0, 0};
volatile long coder[2] = {0, 0};
volatile int lastSpeed[2] = {0, 0};

void setup() {
  Serial.begin(9600);                            //init the Serial port to print the data
  attachInterrupt(LEFT, LwheelSpeed, CHANGE);    //init the interrupt mode for the digital pin 2
  attachInterrupt(RIGHT, RwheelSpeed, CHANGE);   //init the interrupt mode for the digital pin 3
}

void loop() {
  static unsigned long timer = 0;                //print manager timer

  if (millis() - timer > 100) {
    Serial.print("Coder value: ");
    Serial.print(coder[LEFT]);
    Serial.print("[Left Wheel] ");
    Serial.print(coder[RIGHT]);
    Serial.println("[Right Wheel]");

    lastSpeed[LEFT] = coder[LEFT];   //record the latest speed value
    lastSpeed[RIGHT] = coder[RIGHT];
    timer = millis();
  }
}

void LwheelSpeed() {
  timeNow[LEFT] = micros();
  if (timeNow[LEFT] - timePrev[LEFT] > interval) {
    timePrev[LEFT] += interval;
    coder[LEFT] ++;  //count the left wheel encoder interrupts
  }
}

void RwheelSpeed() {
  timeNow[RIGHT] = micros();
  if (timeNow[RIGHT] - timePrev[RIGHT] > interval) {
    timePrev[RIGHT] += interval;
    coder[RIGHT] ++; //count the right wheel encoder interrupts
  }
}


And here is another very good software debounce.

Code: Select all
byte LED = 13;
byte BUTTON = 3;
void setup(void)
{
  pinMode(LED,OUTPUT);
  pinMode(BUTTON,INPUT_PULLUP);
  digitalWrite(LED,LOW);
}
void loop(void)
{
  static unsigned long timepoint = millis();
  static byte count = 0;
  if(millis()-timepoint > 10)
  {
    timepoint = millis();
    if(digitalRead(BUTTON)) count = 0;
    if( (count<100) && (++count==10) )
      digitalWrite(LED, digitalRead(LED)^1);
  }
}
userHeadPic Leff