Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleBeispiel Interrupt
collapsetrue
#define ENCODER_A 2
#define ENCODER_B 4
volatile int encoderValue = 0;
volatile int oldEncoderReading = 0;
int oldEncoderValue = 0;
void setup()
{
  Serial.begin(9600);
  pinMode(ENCODER_A, INPUT_PULLUP);
  pinMode(ENCODER_B, INPUT_PULLUP);
  attachInterrupt(0, readEncoder, CHANGE);
}
void loop()
{
  if (encoderValue != oldEncoderValue)
  {
    Serial.print("ENCODER: ");
    Serial.println (encoderValue, DEC);
    oldEncoderValue = encoderValue;
  }
}

void readEncoder()
{
  int currReading = digitalRead(ENCODER_A);
  if (oldEncoderReading == LOW && currReading == HIGH)
  {
    if (digitalRead(ENCODER_B) == LOW)
    {
      encoderValue++;
    }
    else
    {
      encoderValue--;
    }
  }
  oldEncoderReading = currReading;
  delayMicroseconds(500);
}

 

Weitere Informationen:

attachInterrupt() - auf Arduino.cc

Interrupts - von Nick Gammon