Hello,
i have two water valves which i like to control with my Arduino Due via PWM. The frequency which is required for the valve is 180Hz to 280Hz and i would like to use pin 9 and 10 on the board. How can i switch the Frequency to 200Hz? Can someone give me an example code?
Thanks
fiso42
January 21, 2025, 3:15pm
2
parok030405:
Arduino Due
Not sure, but I am affraid, that the Arduino DUE needs then a bit more detailed treatment:
Hi @hyakoubi
I tried to tweaking the analogWrite() function to change the PWM frequency, since it's possible with AVR microcontrollers (Uno/Mega, etc...), but it turns out for the Due's implementation this isn't so easy.
Here's a code example that outputs 15kHz PWM on pins D5 and D10. The duty-cycle is set by setting the respective timers' TC_RA and TC_RB registers between 0 and 2800, (with this code you're getting a much higher resolution):
// Set up the Arduino Due's digital pins D5 and D10…
Not directly fitting, but it opens the perspective to fiddle directly with the timers close to the hardware.
If you not need the output with a high resolution, I would take into acount, to programme directly in the loop() with micros() timings.
fiso42
January 21, 2025, 3:33pm
3
Without waranty (it´s not tested and needs adjustment to your needs):
void setup() {
}
int dutyCycle01 = 0; // 0-100 %
unsigned long currentTime = 0;
unsigned long lastRisingEdgeTime = 0;
bool output = false;
void loop() {
currentTime = micros();
if ((currentTime > (lastRisingEdgeTime+4999)) && (output == false)) //if one 200Hz cycle is over (1000000 us div 200 --> 5000 us per cycle) ...
{
output = true;
lastRisingEdgeTime = currentTime;
}
if ((currentTime > (lastRisingEdgeTime+(dutyCycle01*50))) && (output == true)) //if duty cycle is reached ...
{
output = false;
}
if (output)
{
//set output pin accordingly
}
else
{
//set output pin accordingly
}
}
system
Closed
July 20, 2025, 3:34pm
4
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.