/* * MECRO KIT - PROYECTO 14: ASCENSOR (DRIVER A4988)
* Objetivo: Control de Posición Absoluta con Driver Industrial
* Hardware: ESP32 + A4988 + NEMA 17 + 3 Botones
*/
// --- 1. DEFINICIONES DE PINES A4988 ---
const int PIN_STEP = 19; // Genera los pulsos
const int PIN_DIR = 18; // Controla la dirección (HIGH/LOW)
const int PIN_EN = 5; // Enable (LOW = Activo, HIGH = Apagado)
// --- 2. CONFIGURACIÓN FÍSICA ---
// Un NEMA 17 típico tiene 200 pasos por vuelta (1.8 grados/paso).
// Si usas microstepping, multiplica este número.
const int PASOS_VUELTA = 200;
// --- 3. DEFINICIÓN DE PISOS (En Pasos Absolutos) ---
const int PISO_1 = 0;
const int PISO_2 = 800; // 4 vueltas
const int PISO_3 = 1600; // 8 vueltas
// --- 4. BOTONES ---
const int BTN_1 = 4;
const int BTN_2 = 16;
const int BTN_3 = 15;
// Estado del Sistema
int posicionActual = 0; // Memoria de posición (Pasos)
int velocidadDelay = 2000; // Microsegundos entre pasos (Menos es más rápido)
void setup() {
Serial.begin(115200);
// Configurar Pines del Driver
pinMode(PIN_STEP, OUTPUT);
pinMode(PIN_DIR, OUTPUT);
pinMode(PIN_EN, OUTPUT);
// Activar el Driver (Active LOW)
digitalWrite(PIN_EN, LOW);
// Configurar Botones
pinMode(BTN_1, INPUT_PULLUP);
pinMode(BTN_2, INPUT_PULLUP);
pinMode(BTN_3, INPUT_PULLUP);
Serial.println("--- ASCENSOR A4988: SISTEMA ONLINE ---");
Serial.println("Calibrado en: Piso 1 (Home)");
}
void loop() {
if (digitalRead(BTN_1) == LOW) moverA(PISO_1, "Piso 1");
else if (digitalRead(BTN_2) == LOW) moverA(PISO_2, "Piso 2");
else if (digitalRead(BTN_3) == LOW) moverA(PISO_3, "Piso 3");
}
// Función de Ingeniería: Control de Movimiento A4988
void moverA(int destino, String nombrePiso) {
int distancia = destino - posicionActual;
if (distancia == 0) return; // Ya estamos ahí
Serial.print("Viajando a "); Serial.print(nombrePiso);
Serial.print(" (Delta: "); Serial.print(distancia); Serial.println(" pasos)");
// 1. Configurar Dirección
if (distancia > 0) {
digitalWrite(PIN_DIR, HIGH); // Subir (Dirección +)
} else {
digitalWrite(PIN_DIR, LOW); // Bajar (Dirección -)
distancia = -distancia; // Trabajar con valor positivo para el bucle
}
// 2. Generar Tren de Pulsos (Step Train)
// Aquí ocurre la magia del movimiento
for (int i = 0; i < distancia; i++) {
digitalWrite(PIN_STEP, HIGH);
delayMicroseconds(velocidadDelay); // Controla la velocidad
digitalWrite(PIN_STEP, LOW);
delayMicroseconds(velocidadDelay);
// Opcional: Rampa de aceleración/desaceleración iría aquí
}
// 3. Actualizar Posición
posicionActual = destino;
Serial.println("-> Llegada: " + nombrePiso);
// NOTA: Con A4988, NO apagamos el PIN_EN si queremos "Holding Torque"
// (Fuerza para mantener el ascensor quieto).
}