// Pin Definitions
const int analogPin = A0; // Potentiometer connected to A0
const int ledPin = 9; // LED connected to PWM pin 9
int adcValue = 0; // Variable to store ADC value
int ledBrightness = 0; // Variable for LED brightness
void setup() {
// Set pin 9 as output for PWM
DDRB |= (1 << PB1); // Set pin 9 (PB1) as output
// Initialize Timer1 for Fast PWM mode
TCCR1A = (1 << COM1A1) | (1 << WGM11) | (1 << WGM10); // Fast PWM mode, non-inverted
TCCR1B = (1 << WGM12) | (1 << CS11); // Prescaler = 8, Fast PWM mode
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Start ADC conversion for channel A0
ADMUX = (1 << MUX0); // Select channel A0 (pin 0)
ADCSRA |= (1 << ADSC); // Start ADC conversion
// Wait until conversion is complete
while (ADCSRA & (1 << ADSC));
// Get ADC result from the ADC Data Register (ADCL and ADCH)
adcValue = ADC;
// Map ADC value (0-1023) to PWM range (0-255)
ledBrightness = (adcValue * 255) / 1023;
// Set PWM duty cycle for LED on pin 9
OCR1A = ledBrightness; // Update the PWM duty cycle
// Print ADC and LED brightness values to Serial Monitor for debugging
Serial.print("ADC Value: ");
Serial.print(adcValue);
Serial.print(" | LED Brightness: ");
Serial.println(ledBrightness);
// Small delay for stability
delay(100);
}