void setup() {
// Configure Timer0 for 100 kHz PWM on Pin 5
pinMode(6, OUTPUT);
// Stop Timer0
TCCR0A = 0;
TCCR0B = 0;
// Set Timer0 to Fast PWM mode with no prescaler
TCCR0A = (1 << COM0A1) | (1 << WGM00) | (1 << WGM01); // Fast PWM mode
TCCR0B = (1 << CS00); // No prescaler
// Set the PWM frequency to 100 kHz
// Formula: PWM Frequency = 16,000,000 / (1 * (256 - OCR0A))
// Rearranging: OCR0A = 256 - (16,000,000 / (1 * 100,000))
OCR0A = 255 - (16,000,000 / 100,000); // Set for 100 kHz
// Set duty cycle to 50%
OCR0A = OCR0A / 2; // 50% of the calculated value
// Configure Timer2 for 2 kHz PWM on Pin 11
pinMode(11, OUTPUT);
// Stop Timer2
TCCR2A = 0;
TCCR2B = 0;
// Set Timer2 to Fast PWM mode
TCCR2A = (1 << COM2A1) | (1 << WGM20) | (1 << WGM21); // Fast PWM mode
TCCR2B = (1 << CS21); // Prescaler 8
// Set the PWM frequency to 2 kHz
// Formula: PWM Frequency = 16,000,000 / (8 * (256 - OCR2A))
// Rearranging: OCR2A = 256 - (16,000,000 / (8 * 2,000))
OCR2A = 255 - (16,000,000 / (8 * 2,000)); // Set for 2 kHz
// Set duty cycle to 50%
OCR2A = OCR2A / 2; // 50% of the calculated value
}
void loop() {
// Nothing needed here; PWM is handled by timers
}
I'm trying to generate PWM of 100kHz and 2kHz on Arduino Uno with 50% duty cycle, but unable to generate. Please help.