#include <Wire.h> // include the Wire library for I2C communication
#include "LiquidCrystal_I2C.h"
//#include LiquidCrystal_I2C lcd(0x27, 16, 2);
LiquidCrystal_I2C lcd(0x27,16,2);
#define POT_PIN A3 // pin for the potentiometer
#define RELAY_PIN A0 // pin for the relay
#define BUTTON_A_PIN A1 // pin for button A
#define BUTTON_B_PIN A2 // pin for button B
#define CYCLE_DURATION 50 // cycle duration in milliseconds
int cycleRatio = 0; // variable to store the cycle ratio
bool cycleActive = false; // variable to store if the cycle is active or not
void setup() {
lcd.begin();
lcd.backlite();
pinMode(POT_PIN, INPUT); // set potentiometer pin as input
pinMode(RELAY_PIN, OUTPUT); // set relay pin as output
pinMode(BUTTON_A_PIN, INPUT); // set button A pin as input
pinMode(BUTTON_B_PIN, INPUT); // set button B pin as input
}
void loop() {
// read the potentiometer value and map it to a range of 0-100
cycleRatio = map(analogRead(POT_PIN), 0, 1023, 0, 100);
// check if button A is pressed
if (digitalRead(BUTTON_A_PIN) == HIGH) {
// if cycle is not active, activate it
if (!cycleActive) {
cycleActive = true;
}
}
// check if button B is pressed
if (digitalRead(BUTTON_B_PIN) == HIGH) {
// if cycle is active, stop it
if (cycleActive) {
cycleActive = false;
}
}
// if cycle is active, turn on the relay for the specified cycle ratio
if (cycleActive) {
digitalWrite(RELAY_PIN, HIGH);
delay(cycleRatio * CYCLE_DURATION / 100); // delay for the specified cycle ratio
digitalWrite(RELAY_PIN, LOW);
delay((100 - cycleRatio) * CYCLE_DURATION / 100); // delay for the remaining cycle ratio
}
// display the cycle ratio and cycle status on the LCD screen
displayLCD(cycleRatio, cycleActive);
}
// function to display the cycle ratio and cycle status on the LCD screen
void displayLCD(int ratio, bool active) {
// convert the cycle ratio to a string
String ratioString = String(ratio) + "%";
// create a string to display the cycle status
String statusString;
if (active) {
statusString = "ON";
} else {
statusString = "OFF";
}
// send the commands to the LCD screen to display the strings
LCD.setCursor(1, 0);
LCD.print(ratioString); // display the cycle ratio
LCD.setCursor(1, 2);
LCD.print(statusString); // display the cycle status
}
// code sourced from https://www.arduino.cc/en/Tutorial/LiquidCrystalI2C
// and https://www.arduino.cc/en/Tutorial/AnalogReadSerial