// Pin assignments
const int ledPin = 9; // Pin 9 is connected to the LED (PWM)
void setup() {
// Set pin 9 as an output
pinMode(ledPin, OUTPUT);
// Call function to set up Timer1
setupPWM();
}
void loop() {
// Change the duty cycle (PWM) from 0 to 255
for (int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) {
analogWrite(ledPin, dutyCycle); // Apply PWM signal
delay(20); // Small delay to visually notice the brightness change
}
delay(500);
}
// Function to set up Timer1 for PWM on pin 9
void setupPWM() {
// Clear Timer1 control registers
TCCR1A = 0;
TCCR1B = 0;
// Set Fast PWM mode with ICR1 as top
TCCR1A |= (1 << WGM11);
TCCR1B |= (1 << WGM12) | (1 << WGM13);
// Set non-inverting mode for PWM on OC1A (pin 9)
TCCR1A |= (1 << COM1A1);
// Set ICR1 to define the PWM frequency
// Example: For 31.25 kHz frequency, ICR1 should be 510
ICR1 = 510; // Adjust this value to change the frequency
// Set prescaler to 1 (no prescaling) for higher frequency
TCCR1B |= (1 << CS10);
// Set initial duty cycle to 50% (ICR1 / 2)
OCR1A = ICR1 / 2;
}