#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Pantalla OLED
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Constantes
const int pinLectura = A0; // Nodo entre resistencia y cable
const float resistenciaConocida = 100.0; // Ω
const float resistenciaUTP = 0.104; // Ω por metro (ida y vuelta)
const float voltajeFuente = 5.0; // V (asumido fijo)
void setup() {
Serial.begin(9600);
Wire.begin();
// OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("No se detectó la pantalla OLED"));
while (1);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(F("Inicializando..."));
display.display();
delay(1000);
}
void loop() {
float vMedido = analogRead(pinLectura) * (5.0 / 1023.0); // voltaje en nodo A0
float resistenciaCable = 0;
float metros = 0;
// Evitar división por cero
if (vMedido > 0 && vMedido < voltajeFuente) {
resistenciaCable = resistenciaConocida * ((voltajeFuente / vMedido) - 1.0);
metros = resistenciaCable / resistenciaUTP;
metros = constrain(metros, 0, 100); // máx 100 m
}
mostrarResultado(vMedido, resistenciaCable, metros);
delay(1000);
}
void mostrarResultado(float vCable, float rCable, float metros) {
display.clearDisplay();
display.setCursor(0, 0);
display.println(F(" MEDICION DE CABLE "));
display.println();
display.print(F("Voltaje: ")); display.print(vCable, 2); display.println(F(" V"));
display.print(F("Resist: ")); display.print(rCable, 2); display.println(F(" Ohm"));
display.print(F("Longitud: ")); display.print(metros, 1); display.println(F(" m"));
// Barra visual
int porcentaje = map(metros, 0, 100, 0, 100);
int barra = map(porcentaje, 0, 100, 0, 98);
barra = constrain(barra, 0, 98);
int x = 0, y = 54, w = 100, h = 8;
display.drawRect(x, y, w, h, SSD1306_WHITE);
display.fillRect(x + 1, y + 1, barra, h - 2, SSD1306_WHITE);
display.setCursor(103, 54);
display.print(porcentaje); display.println(F("%"));
display.display();
}