So I am trying to create PWM using Timer4 on the Arduino Mega. I know that Timer4 uses pins 6, 7, and 8 on the Mega, and I'm trying to use output pin 7.
I want to use Fast PWM mode with a frequency of 62.5 kHz. (Ideally I would like 80kHz, but it seemed easier to get 62.5kHz by setting the clock prescale value to 1.)
Here is my code:
//Within the TCCR4A register:
//COM4A1:0 = 10 for non-inverted output
//WGM41:0 = 11 for the LSBs of WGM setting to fast PWM mode
TCCR4A = _BV(COM4A1) | _BV(WGM41) | _BV(WGM40);
//Within the TCCR4B register:
//CS42:0 = 001 for clock prescale of 1, which should make a frequency of 62.5 kHz
//WGM43:2 = 01 for the MSBs of WGM setting to fast PWM mode
TCCR4B = _BV(CS40) | _BV(WGM42);
OCR4A = 14970; // change the frequency by some (arbitrary) amount
OCR4B = 819; // set 80% duty cycle on channel 4B (this is supposed to show up on output pin 7!)
I don't completely understand how to use the OCR registers, but from what I've seen it seems like you use OCR4A to set the timer compare value to determine the frequency you want. Then, you use the OCR4B and OCR4C registers to set the values for the duty cycles of your respective output channels.
BUT, this code just gives me a noisy sine wave on output pin 7. What am I doing wrong?