Seeeduino Xiao PWM

Hi,
I want to set PWM parameters like frequency, duty cycle etc on a Seeeduino XIAO. I have tried several libraries that did not work. I am not good in modifying the libraries. I need the PWM at D1/A1. Can you please provide an example for Arduino IDE that works with the Xiao?
Thanks,
Holger

Hi @HGlasmachers, Did you tired the analogWrite() function to generate the PWM?

example;

void setup()
{
  pinMode(1,OUTPUT);
}

void loop(){
  for(int i=0; i<=255; i++){
    analogWrite(1,i);
    delay(10);
  }

 digitalWrite(1,LOW);

}

Output:

Does it offer a wax to modify the PWM frequency? I need to vary it in small steps between 20kHz and 50kHz. This is easily possible with an ESP32 with a standard library without modification. How do I realize this with the XIAO?

I’m not sure about it, @Baozhu can you help please !

Hi HGlasmachers

I’m set D1/A1 as PWM, actually, I just adjust the duty cycle. If you want to vary it between 20kHz to 50kHz. Please follow this formula:
Frequency = 48MHz / x / 255 / 2 = 20kHz to 50kHz (48MHz is XIAO default frequency)
so between the 20kHz to 50kHz, the answer is x = 1.88 to 4.7
in this code, you just need set val = 1.88 to 4.7

int ledPin = 1;
int val = 0;

void setup() {
//  pinMode(ledPin, OUTPUT);
}

void loop() {
  for (val = 0; val <= 100; val++) {         // 100 -> mean the frequency is 941.1Hz
    analogWrite(ledPin, val);
    delay(10);
  }
  for (val = 100; val >= 0; val--) {
    analogWrite(ledPin, val);
    delay(10);
  }
}

Wish it help you.

Best regards
Fenyi

Hi, thank you very much for the time you spend in the answer.
Your code varies the duty cycle, not the PWM frequency. The duty cycle gives the HIGH-time / LOW-time relation. It defines how long the PWM-pin is LOW or HIGH within one time period. The PWM-frequency defines, how often the PWM changes its state within one second.
Best regards,
Holger

Hi HGlasmachers

I see.
use this:

pwm(pin, frequency, duty cycle);

then you just calculator by yourself.

int ledPin = 1;
int val;
void setup() {
}
void loop() {
  for (val = 0; val <= 1024; val++) {         // 100 -> mean the frequency is 941.1Hz
  pwm(ledPin, 20000, val);
    delay(1);
  }
  for (val = 1024; val >= 0; val--) {
    pwm(ledPin, 20000, val);
    delay(1);
  }
}

Best regards
Fenyi

2 Likes

Wow, thank you very much. This solved my problem. You can close this thread. You really did a good job, thank you!

1 Like

To Fenyi
Where did you locate information on the function pwm(pin, frequency, duty cycle) ?
Thanks

Found the file at
user\AppData\Local\Arduino15\packages\Seeeduino\hardware\samd\1.8.1\cores\arduino

NDC-SC

Hi NDC-SC
That file path is right, you just find out the wiring_pwm.cpp, the function is there.

Best regards
Fenyi

Hi,

What is the upper and lower bounds for the duty cycle in this function? I am getting very weird results when trying to specify the duty cycle