#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
void setup() {
// Set Pin 11 (OC1A/PB5 on ATmega2560) as an OUTPUT
pinMode(11, OUTPUT);
// 1. Reset Timer 1 Control Registers
TCCR1A = 0;
TCCR1B = 0;
// 2. Set Waveform Generation Mode: Fast PWM (Mode 14)
// WGM13=1, WGM12=1, WGM11=1, WGM10=0
TCCR1A |= (1 << WGM11);
TCCR1B |= (1 << WGM13) | (1 << WGM12);
// 3. Set Compare Output Mode for Channel A: Non-inverted PWM
// Clears OC1A on compare match, sets at BOTTOM
TCCR1A |= (1 << COM1A1);
// 4. Set the TOP value in ICR1 for frequency control
// Formula: Frequency = Clock / (Prescaler * (1 + TOP))
// Example for ~2 kHz at 16MHz clock with a prescaler of 64:
// 16,000,000 / (64 * 12500) = ~20 Hz
ICR1 = 12499;
TCCR1B |= (1 << CS11) | (1 << CS10);
// 5. Set the Duty Cycle using OCR1A
// Value from 0 to ICR1. (e.g., 50% duty cycle)
for (uint16_t i = 12490; i > 0; i -= 5) {
OCR1A = i;
_delay_ms(1);
}
// 6. Set Clock Select: Prescaler = 64
}
void loop() {
}