// This code generated using ChatGPT
// Pin definition
const int pwmPin = 9; // PWM output pin (can be any digital pin)
const int sensorPin = A1; // Sensor connected to analog pin 1
// Variables
int pwmFrequency = 100; // Default frequency (Hz)
int dutyCycle = 50; // Default duty cycle (percent)
unsigned long previousMicros = 0; // Stores the last time the PWM state changed
unsigned long period = 10000; // Period for PWM signal in microseconds (default 100Hz)
int highTime = 0; // Duration of the HIGH state for PWM (based on duty cycle)
int lowTime = 0; // Duration of the LOW state for PWM
void setup() {
// Initialize the PWM pin as an output
pinMode(pwmPin, OUTPUT);
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read the sensor value (0 to 1023)
int sensorValue = analogRead(sensorPin);
// Map sensor value (0-1023) to a duty cycle percentage (0-100)
dutyCycle = map(sensorValue, 0, 1023, 0, 100);
// Calculate the period (in microseconds) for the desired PWM frequency
period = 1000000 / pwmFrequency; // period = 1 / frequency, in microseconds
// Calculate the high and low time for the duty cycle
highTime = (dutyCycle * period) / 100; // high time based on duty cycle
lowTime = period - highTime; // low time is the remainder of the period
// Generate PWM signal using micros()
unsigned long currentMicros = micros();
if (currentMicros - previousMicros >= period) {
previousMicros = currentMicros; // Update the last time we changed the PWM state
// Toggle PWM pin (HIGH/LOW) based on the duty cycle
digitalWrite(pwmPin, HIGH); // Turn on the PWM pin
delayMicroseconds(highTime); // Stay HIGH for the calculated high time
digitalWrite(pwmPin, LOW); // Turn off the PWM pin
delayMicroseconds(lowTime); // Stay LOW for the calculated low time
}
// Optional: Monitor and change the frequency through Serial Monitor
if (Serial.available() > 0) {
pwmFrequency = Serial.parseInt(); // Read the frequency from serial input
pwmFrequency = constrain(pwmFrequency, 1, 500); // Ensure it's within the range of 1-500 Hz
Serial.print("New PWM Frequency: ");
Serial.println(pwmFrequency);
}
// Debugging output to monitor duty cycle and sensor values
Serial.print("Sensor Value: ");
Serial.print(sensorValue);
Serial.print(" => Duty Cycle: ");
Serial.println(dutyCycle);
//delay(100); // Delay to stabilize sensor readings (optional)
}