Pages: [1]   Go Down
Author Topic: Problem varying PWM frequency on Mega  (Read 926 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 7
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello,
I made a post in another 3-page thread about writing registers to change the duty cycle and frequency of PWM, but I'm re-posting it as a new thread.

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:

Code:
void setup()

{
  pinMode(7, OUTPUT);
 //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!)
}

void loop()
{
}
 


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?
Thanks so much!
Logged

0
Offline Offline
Shannon Member
****
Karma: 200
Posts: 11694
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

That means you forgot: pinMode (7, OUTPUT) !!
Logged

[ I won't respond to messages, use the forum please ]

Pages: [1]   Go Up
Jump to: