// Incluimos las bibliotecas Wire y LiquidCrystal_I2C
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Definiciones para pines
const uint8_t ledRojo = 45;
const uint8_t ledAzul = 40;
const uint8_t pot = 6;
const uint8_t I2C_SDA = 1;
const uint8_t I2C_SCL = 2;
const uint8_t boton = 7;
const uint8_t apagado = 0;
const uint8_t prender = 255;
// Declaramos variables y objetos
int duty;
int botonP;
int PinLed;
int dutyPorcentaje;
LiquidCrystal_I2C miLCD(0x27, 16, 2);
void setup() {
// Reconfiguramos pines para I2C
Wire.begin(I2C_SDA, I2C_SCL);
// Configuramos pines para led y el botón
pinMode(ledRojo, OUTPUT);
pinMode(ledAzul, OUTPUT);
pinMode(boton,INPUT_PULLUP);
// Inicializamos la pantalla LCD
miLCD.init();
miLCD.backlight();
miLCD.setCursor(1, 0);
miLCD.print("D.C: ");
miLCD.setCursor(6, 0);
miLCD.print("100%");
// Inicializamos variable led
PinLed = ledAzul;
//Encendemos el led azul y apagamos el rojo
analogWrite(ledRojo,apagado);
analogWrite(PinLed,prender);
delay(1000);
}
void loop() {
// Detectar si se presiono el botón
botonP = digitalRead(boton);
delay(10);
if(botonP == LOW){
delay(10);
while(digitalRead(boton)==LOW){}
//Si se presionó se ve cual led es el encendido y se cambia el PinLed
//Para que el otro led reciba el nuevo valor del DC y el led anterior se apaga
if(PinLed == ledAzul){
PinLed = ledRojo;
analogWrite(ledAzul,0);
}
else if(PinLed == ledRojo){
PinLed = ledAzul;
analogWrite(ledRojo,0);
}
}
//Lectura del valor del potenciómetro y convertirlo a la resolución de 8 bits
duty = map(analogRead(pot), 0, 4095, 0, 255);
analogWrite(PinLed, duty); // actualizamos ciclo de trabajo
dutyPorcentaje = duty*100/255; // calculamos ciclo de trabajo en porcentaje
miLCD.setCursor(6, 0); // mostramos en pantalla el valor calculado
miLCD.printf("%03d", dutyPorcentaje);
delay(10); // this speeds up the simulation
}