Enkoder Rotacyjny czyli Rotary Encoder – cyfrowy przełącznik

Dziś przyjrzymy się urządzeniu, które nazywa się Enkoder Rotacyjny (ang. Rotary Encoder)

Kupiłem go u Alice w Chinach: Rotary-Encoder-Module-Brick-Sensor-Development-Board-For-Arduino
Przejrzałem kilkanaście stron z opisami działania enkodera i wybrałem witrynę Dejana Nedelkovskiego. Program trochę zmodyfikowałem dodając SW, czyli przycisk, który w tym wypadku służy do zerowania zliczanych kroków. Jak na zdjęciu należy pin wyjściowy modułu (SW) podciągnąć pod VCC (+5V) rezystorem 10k.

<pre class="wp-block-syntaxhighlighter-code">
/* Arduino Rotary Encoder Tutorial
*
* by Dejan Nedelkovski, www.HowToMechatronics.com
*
*/

#define outputA 6
#define outputB 7
#define SW 5

int counter = 0;
int aState;
int aLastState;
//int SWread;
//int aLastSWstate;

void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
pinMode (SW,INPUT);

Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
//aLastSWstate = digitalRead(SW);
}

void loop() {

if (!digitalRead(SW))
{
counter=0;
Serial.println("Reset.Position: 0");
delay(500);
}

aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
} else {
counter --;
}
Serial.print("Position: ");
Serial.println(counter);

}
aLastState = aState; // Updates the previous state of the outputA with the current state
}
</pre>

Linki:

Dodaj komentarz