#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address according to your specific module
// You might need to change this address if your module has a different address
// Use an I2C scanner sketch to find the correct address if needed
LiquidCrystal_I2C lcd(0x27, 16, 2); // 0x27 is the I2C address of the LCD
const int pwmPin = 9; // PWM output pin to control MOSFET
const int increaseButton = 2; // Button to increase voltage
const int decreaseButton = 3; // Button to decrease voltage
const int sensePin = A1; // Voltage sense pin
int setVoltage = 128; // Initial set voltage (mapped to 50% PWM)
const int maxVoltage = 255; // Maximum PWM value
const int minVoltage = 0; // Minimum PWM value
const int step = 1; // Step to increase/decrease voltage
void setup() {
pinMode(pwmPin, OUTPUT);
pinMode(increaseButton, INPUT_PULLUP);
pinMode(decreaseButton, INPUT_PULLUP);
pinMode(sensePin, INPUT);
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
lcd.backlight(); // Turn on the backlight
Serial.begin(9600); // For debugging
}
void loop() {
// Check if the increase button is pressed
if (digitalRead(increaseButton) == LOW) {
setVoltage = constrain(setVoltage + step, minVoltage, maxVoltage);
delay(200); // Debounce delay
}
// Check if the decrease button is pressed
if (digitalRead(decreaseButton) == LOW) {
setVoltage = constrain(setVoltage - step, minVoltage, maxVoltage);
delay(200); // Debounce delay
}
int actualVoltage = analogRead(sensePin); // Read actual output voltage
actualVoltage = map(actualVoltage, 0, 1023, 0, 255); // Map to PWM range
int error = setVoltage - actualVoltage; // Calculate error
// Adjust PWM signal to correct output voltage
int pwmValue = constrain(setVoltage + error, 0, 255);
analogWrite(pwmPin, pwmValue);
// Debugging
Serial.print("Set Voltage: ");
Serial.print(setVoltage);
Serial.print(" Actual Voltage: ");
Serial.print(actualVoltage);
Serial.print(" PWM Value: ");
Serial.println(pwmValue);
// Update LCD display
lcd.clear();{
lcd.setCursor(0, 0);
lcd.print("Set V: ");
lcd.print(map(setVoltage, 0, 255, 0, 255)); // Assuming 0-5V range for simplicity
lcd.setCursor(0, 1);
lcd.print("Actual V: ");
lcd.print(map(actualVoltage, 0, 255, 0, 255)); // Assuming 0-5V range for simplicity
delay(100); }// Small delay for stability
}