Salve, come da titolo ho un grattacapo riguardante la lettura di un Encoder in quadratura.
Utilizzo un Arduino Micro (originale) l'encoder
é collegato ai pin 2 e 3.
Utilizzo il PIN 2 per generare l'interrupt e poi leggo il valore sul PIN 3 per controllare la direzione, dopo di ché all'interno di una switch case aggiorno lo stato dell'encoder per ignorare i rimbalzi.
Più facile a vedersi che dirsi.
// Input pins to connect to the encoder
const uint8_t CLK = 2;
const uint8_t DT = 3;
volatile int16_t inputDelta = 0; // Counts up or down depending which way the encoder is turned
volatile static bool printFlag = false; // Flag to indicate that the value of inputDelta should be printed
volatile static uint8_t state = 0; // Variabile che indica lo stato dell'encoder
volatile bool CLKstate;
volatile bool DTstate;
void setup() {
Serial.begin(115200);
pinMode(CLK, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(CLK), readEncoder, FALLING);
}
void loop() {
printDelta();
}
void readEncoder() {
while(printFlag == false){
CLKstate = digitalRead(CLK);
DTstate = digitalRead(DT);
switch (state) {
case 0: // interrupt generato
state = 1; //salto al controllo direzione
break;
case 1:
if (DT){ // Turn clockwise and CLK goes low first
state = 2;
} else if (!DTstate) { // Turn anticlockwise and DT goes low first
state = 5;
}
break;
// Clockwise rotation
case 2:
if (!DTstate) { // Continue clockwise and DT will go low after CLK
state = 3;
}
break;
case 3:
if (CLKstate) { // Turn further and CLK will go high first
state = 4;
}
break;
case 4:
if (CLKstate && DTstate) { // Both CLK and DT now high as the encoder completes one step clockwise
state = 0;
++inputDelta;
printFlag = true;
}
break;
// Anticlockwise rotation
case 5: // As for clockwise but with CLK and DT reversed
if (DTstate) {
state = 6;
}
break;
case 6:
if (CLKstate && DTstate) {
state = 0;
--inputDelta;
printFlag = true;
}
break;
}
}
}
void printDelta() {
if (printFlag) {
printFlag = false;
Serial.println(inputDelta);
}
}
Probabilmente mi perdo in un bicchiere d'acqua.
Ma se compilo e carico il programma nella porta seriale vedo solo incrementi sia che giri in senso orario che antiorario