// Pin definitions
const int pwmPin = 5; // PWM output pin
const int voltageSensePin = A0; // Voltage sensing pin
// Variables
int Vref = 6; // Desired reference voltage in v
int t = 50; // Initial pulse width in microseconds (adjust as needed)
// Functions
void setup() {
pinMode(pwmPin, OUTPUT); // Set the PWM pin as an output
pinMode(voltageSensePin, INPUT); // Set the voltage sensing pin as an input
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
int sensorValue = analogRead(voltageSensePin); // Read the analog input
float Vin = sensorValue * (5.0 / 1023.0); // Convert the analog reading to voltage
float Vout = Vin * 12.0 / 5.0; // Calculate the output voltage
// Debugging
Serial.print("Vin: ");
Serial.print(Vin);
Serial.print(" V, Vout: ");
Serial.print(Vout);
Serial.print(" V, t: ");
Serial.print(t);
Serial.print(" us, sv ");
Serial.println(sensorValue);
// Compare Vout with Vref and adjust t accordingly
if (Vout > 1.02 * Vref)
{
t = t - 2; // Decrease pulse width
}
else if (Vout < 0.98 * Vref)
{
t = t + 2; // Increase pulse width
}
// Ensure t is within a reasonable range
if (t < 0) t = 0;
if (t > 100) t = 100; // Adjust max value as needed
// Generate PWM signal
digitalWrite(pwmPin, HIGH);
delayMicroseconds(t);
digitalWrite(pwmPin, LOW);
delayMicroseconds(100 - t); // Adjust period as needed
}