Arduino due, create variable frequency PWM signal

Hi All, I am currently playing with an Arduino Due, and after going through some tutorials, I am able to use analogwrite() function to generate PWM signal with different duty cycle, the following is my code, while I am not sure how can I change its default frequency to a different value, it will be really great if anyone could help me to add a few lines of code to change the PWM frequency.

int Output = 3;      // Output chosen as digital pin 9
int analogPin = A2;   // Analog input connected to analog pin 2
int val = 0;         // variable to store the read value
int Mapvalue = 0;
int DutyCycle;
int MappedDC;  //mapped duty cycle
void setup() {
  pinMode(Output, OUTPUT);  // sets the pin as output
  Serial.begin(9600);
}

void loop() {
  DutyCycle=20;
  MappedDC = map(DutyCycle,0,100,0,255);
  val = analogRead(analogPin);  // read the input pin
  analogWrite(Output,MappedDC); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255, if 255 means 100% duty cycle
  Mapvalue=map(val,0,1023,0,255);
  Serial.print(val);
  Serial.println();
  
}

Hi @cooperli welcom to the forum.

Why do you want a different PWM frequency? What are you trying to achieve?

This post might help you:-

Hi Mike, I really appreciate your help, the post you shared with me solved my problems, by the way, I am using this functionality of arduino to generate a square wave with variable duty cycle and frequency, this will be used to control the on off frequency and on off period for an analog switch.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.