// 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 = 10;  // 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 = 100000;  // 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
bool pwmState = false; // Tracks the current state of PWM (HIGH or LOW)

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

  // Get the current time in microseconds
  unsigned long currentMicros = micros();

  // Check if it's time to change the state of the PWM pin
  if (currentMicros - previousMicros >= (pwmState ? highTime : lowTime)) {
    // Toggle the PWM state
    pwmState = !pwmState;  // Change state from HIGH to LOW or vice versa
    
    // Update the last time the state was changed
    previousMicros = currentMicros;

    // Set the PWM pin to the new state (HIGH or LOW)
    digitalWrite(pwmPin, pwmState ? HIGH : LOW);
    //Serial.print(" Output: ");
    //Serial.print( pwmState );
    //Serial.println("  ");
  }

  // 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);

  // No delay, just efficient non-blocking execution
}
D0D1D2D3D4D5D6D7GNDLOGIC