Thanks for taking interest.
Here is my:
#include <Servo.h>
#define outputA 2
#define outputB 3
int counter = 0;
int aState;
int aLastState;
int servoPin = 9;
Servo servo;
float angle = 90.00; // set initial servo position in degrees
void setup() {
// put your setup code here, to run once:
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
servo.attach(servoPin);
servo.write(angle); // set intital position of servo at 90 degree
}
void loop() {
// put your main code here, to run repeatedly:
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 ++;
LeftTurn(counter);
} else {
counter --;
RightTurn(counter);
}
// Serial.print("Counter: ");
//Serial.println(counter);
// Serial.print("Angle: ");
// Serial.println(angle);
}
aLastState = aState; // Updates the previous state of the outputA with the current state
}
void LeftTurn(int c) {
if ((-70<=c) && (c<=70)){
angle=angle+0.5;
servo.write(angle);
Serial.println(" Left Turn ");
Serial.print("Position:");
Serial.println(c);
Serial.print("Angle: ");
Serial.println(angle);
delay(50);
}
}
void RightTurn(int c) {
if ((-70<=c) && (c<=70)){
angle=angle-0.5;
servo.write(angle);
Serial.println(" Right Turn ");
Serial.print("Position:");
Serial.println(c);
Serial.print("Angle: ");
Serial.println(angle);
delay(50);
}
}