#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// === Configuración de la pantalla OLED ===
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// === Pines ===
#define POT_UMBRAL 35 // Pin del potenciómetro/señal a medir
// === Variables para el gráfico ===
int buffer[SCREEN_WIDTH]; // Almacena los valores para graficar
int indiceBuffer = 0;
// === Declaración de funciones ===
void actualizarGrafico(int valor);
void inicializarPantalla();
void leerSenalAnalogica();
// === Setup ===
void setup() {
Serial.begin(115200);
// Inicializar pantalla
inicializarPantalla();
// Configurar pin de entrada
pinMode(POT_UMBRAL, INPUT);
// Inicializar buffer en 0
for (int i = 0; i < SCREEN_WIDTH; i++) {
buffer[i] = 0;
}
Serial.println("Osciloscopio iniciado");
}
// === Loop principal ===
void loop() {
// Leer señal analógica
leerSenalAnalogica();
// Pequeña pausa para controlar velocidad de actualización
delay(5); // 5ms = 200 muestras por segundo
}
// === Funciones ===
void inicializarPantalla() {
// Inicializar OLED
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("Error al inicializar OLED"));
for(;;); // Detener si falla
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.println("Osciloscopio");
display.println("Iniciando...");
display.display();
delay(1000);
}
void leerSenalAnalogica() {
// Leer valor del ADC (0-4095 en ESP32)
int valorPot = analogRead(POT_UMBRAL);
// Actualizar el gráfico con el valor leído
actualizarGrafico(valorPot);
// Opcional: imprimir valor en Serial para debugging
// Serial.println(valorPot);
}
void actualizarGrafico(int valor) {
// Escalar el valor del ADC (0-4095) al rango de la pantalla (0-63)
int yVal = map(valor, 0, 4095, 0, SCREEN_HEIGHT - 1);
// Desplazar el buffer hacia la izquierda
for (int i = 0; i < SCREEN_WIDTH - 1; i++) {
buffer[i] = buffer[i + 1];
}
// Agregar el nuevo valor al final del buffer
buffer[SCREEN_WIDTH - 1] = yVal;
// Limpiar la pantalla
display.clearDisplay();
// Dibujar el gráfico conectando puntos consecutivos
for (int x = 1; x < SCREEN_WIDTH; x++) {
int y1 = SCREEN_HEIGHT - 1 - buffer[x - 1];
int y2 = SCREEN_HEIGHT - 1 - buffer[x];
display.drawLine(x - 1, y1, x, y2, WHITE);
}
// Opcional: Agregar líneas de referencia
// Línea horizontal en el medio
display.drawFastHLine(0, SCREEN_HEIGHT / 2, SCREEN_WIDTH, WHITE);
// Mostrar voltaje en la esquina
float voltaje = (valor / 4095.0) * 3.3;
display.setCursor(0, 0);
display.setTextSize(1);
display.print(voltaje, 2);
display.print("V");
// Actualizar la pantalla
display.display();
}