#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP32Servo.h>
#define POT_PIN 34
#define LED_PIN 25
#define SERVO_PIN 27
#define BRAKE_PIN 26 // Botón de freno
#define OLED_WIDTH 128
#define OLED_HEIGHT 64
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(OLED_WIDTH, OLED_HEIGHT, &Wire, -1);
Servo motor;
float bateria = 100.0; // porcentaje inicial
unsigned long lastUpdate = 0;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BRAKE_PIN, INPUT_PULLUP); // Botón activo en LOW
motor.attach(SERVO_PIN, 500, 2400);
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println(F("Error al iniciar OLED"));
for(;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(10, 10);
display.println("Bicicleta Electrica");
display.display();
delay(1000);
}
void loop() {
int potValue = analogRead(POT_PIN);
bool freno = digitalRead(BRAKE_PIN) == LOW; // Si se presiona el freno
int velocidad = map(potValue, 0, 4095, 0, 180);
int porcentaje = map(potValue, 0, 4095, 0, 100);
// Control del freno
if (freno) {
velocidad = 0; // Detiene el motor
porcentaje = 0;
}
// Control del motor
motor.write(velocidad);
digitalWrite(LED_PIN, (porcentaje > 10 && !freno) ? HIGH : LOW);
// Simular batería
unsigned long now = millis();
if (now - lastUpdate > 500) { // actualizar cada 0.5 s
if (porcentaje > 10 && !freno) {
bateria -= 0.2 + (porcentaje / 100.0) * 0.5; // consumo
if (bateria < 0) bateria = 0;
} else {
bateria += 0.1; // recarga lenta
if (bateria > 100) bateria = 100;
}
lastUpdate = now;
}
// Mostrar en pantalla
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Acelerador:");
display.setTextSize(2);
display.setCursor(0, 15);
display.print(porcentaje);
display.println("%");
display.setTextSize(1);
display.setCursor(0, 45);
if (freno) display.println("Freno ACTIVADO");
else if (porcentaje > 10) display.println("Motor: Encendido");
else display.println("Motor: Apagado");
display.setCursor(0, 55);
display.print("Bateria: ");
display.print((int)bateria);
display.println("%");
display.display();
delay(100);
}