user42423
user42423

Reputation: 117

Change Arduino Mega pin 2 and pin 3 PWM frequency

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.

Upvotes: -2

Views: 460

Answers (1)

schl-sime
schl-sime

Reputation: 1

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);
}

Upvotes: 0

Related Questions