#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
LiquidCrystal_I2C lcd(0x27, 20, 4); // Adjust the I2C address if needed
const int buttonUpPin = 2; // Pin for the up button
const int buttonDownPin = 3; // Pin for the down button
const int solenoidPin = 13; // Pin connected to the solenoid
int frequency; // Frequency in Hz
unsigned long pulseDuration = 500; // Pulse duration in milliseconds
unsigned long period;
unsigned long lastPulseTime = 0;
// Define states for button debouncing
#define IDLE 0
#define PRESSED 1
int buttonUpState = IDLE;
int buttonDownState = IDLE;
void setup() {
pinMode(buttonUpPin, INPUT_PULLUP);
pinMode(buttonDownPin, INPUT_PULLUP);
pinMode(solenoidPin, OUTPUT);
lcd.begin(20, 4); // Initialize the LCD with 20 columns and 4 rows
lcd.print("Frequency: ");
// Read frequency from EEPROM
frequency = EEPROM.read(0);
if (frequency == 255 || frequency < 1) {
frequency = 1; // Default value if EEPROM is not initialized or less than 1
}
period = 1000 / frequency;
lcd.setCursor(12, 0);
lcd.print(frequency);
lcd.print(" Hz");
}
void loop() {
// Check for button presses
if (digitalRead(buttonUpPin) == LOW) {
if (buttonUpState == IDLE) {
frequency = min(6, frequency + 1); // Limit to 10 Hz
updateLCD();
saveFrequencyToEEPROM();
buttonUpState = PRESSED;
}
} else {
buttonUpState = IDLE;
}
if (digitalRead(buttonDownPin) == LOW) {
if (buttonDownState == IDLE) {
frequency = max(1, frequency - 1); // Limit to 1 Hz
updateLCD();
saveFrequencyToEEPROM();
buttonDownState = PRESSED;
}
} else {
buttonDownState = IDLE;
}
// Generate pulse
unsigned long currentTime = millis();
if (currentTime - lastPulseTime >= period) {
lastPulseTime = currentTime;
digitalWrite(solenoidPin, HIGH);
delay(pulseDuration);
digitalWrite(solenoidPin, LOW);
}
}
void updateLCD() {
period = 1000 / frequency;
lcd.setCursor(12, 0);
lcd.print(" "); // Clear previous frequency value
lcd.setCursor(12, 0);
lcd.print(frequency);
lcd.print(" Hz");
}
void saveFrequencyToEEPROM() {
EEPROM.write(0, frequency);
// EEPROM.commit(); // Not needed for the built-in EEPROM in Arduino
}