// Include the AccelStepper Library
#include <AccelStepper.h>
#include "ESPRotary.h"
#include "Button2.h"
// Define pin connections
const int dirPin = 6;
const int stepPin = 7;
const int ROTARY_PIN1 = 2;
const int ROTARY_PIN2 = 3;
const int CLICKS_PER_STEP = 4;
const int BUTTON_PIN = 4;
boolean motoron = false;
int steps = 0;
// Define motor interface type
#define motorInterfaceType 1
ESPRotary r;
Button2 b;
// Creates an instance
AccelStepper myStepper(motorInterfaceType, stepPin, dirPin);
void setup() {
//Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
//Init Rotary Encoder
r.begin(ROTARY_PIN1, ROTARY_PIN2, CLICKS_PER_STEP);
r.setChangedHandler(rotate);
b.begin(BUTTON_PIN);
b.setLongClickTime(250);
b.setClickHandler(click);
b.setLongClickDetectedHandler(longClick);
// set the maximum speed, acceleration factor,
// initial speed and the target position
myStepper.setMaxSpeed(50);
myStepper.setAcceleration(500);
myStepper.setSpeed(200);
//myStepper.moveTo(200);
}
void rotate(ESPRotary& r) {
//myStepper.moveTo(r.getPosition());
steps = r.getPosition();
//r.resetPosition(0, false);
}
void click(Button2& btn) {
myStepper.moveTo(steps);
}
void longClick(Button2& btn) {
motoron = !motoron;
digitalWrite(LED_BUILTIN, motoron);
}
void loop() {
r.loop();
b.loop();
// Change direction once the motor reaches target position
//if (myStepper.distanceToGo() == 0)
//myStepper.moveTo(-myStepper.currentPosition());
// Move the motor one step
if (motoron == false) {
myStepper.stop();
} else {
myStepper.run();
}
}