from machine import Pin, I2C, ADC
import time
import ssd1306
# === Parámetros de configuración ===
sample_rate_hz = 200 # Muestras por segundo (puedes ajustar)
display_window_s = 1.0 # Tiempo visible en pantalla (segundos)
max_pixels = 128 # Ancho en píxeles del OLED
# (para evitar aliasing, según Nyquist: f_máx ≈ sample_rate / 2)
# === Inicialización OLED y ADC ===
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
adc = ADC(Pin(15))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)
# === Función para convertir voltaje a coordenada Y en pantalla ===
def voltage_to_y(voltage):
return int(62 - (voltage / 3.3) * 54) + 8
# === Cálculo de retardo y puntos ===
sleep_time = 1.0 / sample_rate_hz
num_points = int(display_window_s * sample_rate_hz)
if num_points > max_pixels:
num_points = max_pixels # limitar al ancho de pantalla
# === Inicializar gráfico y variables ===
oled.fill(0)
oled.vline(0, 8, 56, 1) # Eje Y
oled.hline(0, 63, 128, 1) # Eje X
oled.show()
voltages_y = [63] * num_points
last_displayed = -1
# === Bucle principal ===
while True:
raw = adc.read()
voltage = (raw / 4095.0) * 3.3
y = voltage_to_y(voltage)
voltages_y.pop(0)
voltages_y.append(y)
oled.fill_rect(0, 8, 128, 55, 0)
scale_x = max_pixels / num_points
for i in range(num_points - 1):
x1 = int(i * scale_x)
x2 = int((i + 1) * scale_x)
y1 = voltages_y[i]
y2 = voltages_y[i + 1]
oled.line(x1, y1, x2, y2, 1)
oled.vline(0, 8, 56, 1)
oled.hline(0, 63, 128, 1)
if abs(voltage - last_displayed) > 0.01:
oled.fill_rect(0, 0, 128, 8, 0)
oled.text("V = {:.2f} V".format(voltage), 0, 0)
last_displayed = voltage
oled.show()
time.sleep(sleep_time)