#include <Wire.h>
#include <Encoder.h>;
#include <Servo.h>;
const int SW_PIN = 4;
const int PIN_A = 2;
const int PIN_B = 3;
// Change these two numbers to the pins connected to your encoder.
// Best Performance: both pins have interrupt capability
// Good Performance: only the first pin has interrupt capability
// Low Performance: neither pin has interrupt capability
// avoid using pins with LEDs attached
Encoder myEnc(PIN_A, PIN_B);
const int homePosition = 90;
const int stepValue = 10;
const int servopin = 9;
Servo myservo;
int servoangle = homePosition;
void setup() {
Serial.begin(9600);
pinMode(SW_PIN, INPUT);
Serial.println("Basic Encoder Test:");
myservo.attach(servopin); // attaches the servo on pin
myservo.write(servoangle);//move servo to initial position
}
long oldPosition = -999;
void loop() {
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
if (newPosition > oldPosition)
{
int newstep = abs(newPosition - oldPosition);
Serial.print("Angle");
Serial.println(servoangle);
servoangle -= stepValue;
if(servoangle <0)
servoangle=0;
}
if(newPosition < oldPosition){
int newstep = abs(newPosition - oldPosition);
Serial.print("Angle");
Serial.println(servoangle);
servoangle += stepValue;
if(servoangle >180)
servoangle=180;
}
oldPosition = newPosition;
Serial.println(newPosition);
}
if ( digitalRead(SW_PIN) == LOW)
{
Serial.print("home:");
Serial.println(homePosition);
servoangle = homePosition;
myservo.write(servoangle);
}
delay(200);
//watch video details https://youtu.be/6xVLbNlmK-g
}