#include <AccelStepper.h>
#include <Preferences.h>
// Pines encoder
#define ENCODER_CLK 34 // Change this to the desired CLK pin on ESP32
#define ENCODER_DT 35 // Change this to the desired DT pin on ESP32
//#define ENCODER_SW 32
// Pines driver
#define MOTOR_STEP_PIN 17
#define MOTOR_DIR_PIN 16
// Límites giro reductor
#define MAX 10
#define MIN 0
AccelStepper motor(AccelStepper::DRIVER, MOTOR_STEP_PIN, MOTOR_DIR_PIN);
Preferences guarda;
int lastClk = HIGH;
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
//pinMode(ENCODER_SW, INPUT_PULLUP);
motor.setMaxSpeed(1000.0);
motor.setAcceleration(500.0);
guarda.begin("memoria", false); //Abrimos los namespace con permiso de lectura/escritura
}
void loop() {
unsigned int posicion_red = guarda.getUInt("contador", 0);
int newClk = digitalRead(ENCODER_CLK);
int dtValue = digitalRead(ENCODER_DT);
//int swValue = digitalRead(ENCODER_SW);
if (newClk != lastClk) {
lastClk = newClk;
if (newClk == LOW && dtValue == HIGH) {
if(posicion_red<MAX) {
// Motor moves clockwise
posicion_red++;
guarda.putUInt("contador", posicion_red);
motor.setSpeed(20);
motor.runSpeed();
Serial.println("Motor: Clockwise");
Serial.print("Encoder Steps: ");
Serial.println(posicion_red);
}
}
if (newClk == LOW && dtValue == LOW) {
if(posicion_red>MIN) {
// Motor moves counterclockwise
posicion_red--;
guarda.putUInt("contadorr", posicion_red);
motor.setSpeed(-20);
motor.runSpeed();
Serial.println("Motor: Counterclockwise");
Serial.print("Encoder Steps: ");
Serial.println(posicion_red);
}
}
}
//if (swValue==LOW){
// guarda.end();
// Serial.println("Restarting");
// delay(1000);
// ESP.restart();
//}
}