-2

I am new to Arduino Mega. I am using it to build a switch mode regulator. I need to change Arduino Mega pin 2 and pin 3 PWM frequency to 10kHz or more than that. Appreciate if you can explain in simple way and provide example code at here, thank you very much.

1 Answer 1

0

You need to access the Timer/Counter Control Register.

This will give you an PWM frequency of about 62.7 kHz. The next possible smaller frequency would be 7.8 kHz. For this you would have to set bit CS31 instead of CS30.

int pwmPin1 = 2;
int pwmPin2 = 3;

void setup() {
  pinMode(pwmPin1, OUTPUT);
  pinMode(pwmPin2, OUTPUT);

  //WGM30 = set Timer mode to PWM
  //COM3B/C1 = clear Output on compare match
  TCCR3A = (1<<WGM30)|(1<<COM3B1)|(1<<COM3C1);

  //CS30 = set prescaler to 1
  TCCR3B = (1<<CS30);  
}

void loop() {
  analogWrite(pwmPin1, 127); //Change for your desired Duty-Cycle (from 0 to 255)
  analogWrite(pwmPin2, 63);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.