20-30kHz PWM on Arduino UNO

I´m pretty new to using Arduino and coding, but I´m trying to run a Nidec 24h motor using an Arduino uno. According to the pinout sheet the motor needs a 20-30kHz PWM and duty cycle 20-100%.

How can I obtain a code to do that for me?

Would 32KHz be OK? Pretty sure Uno can do that.

Moved to Programming Questions....Please don't post in Uncategorized again.

2 Likes

I´m not sure, its the motor that requires it, but I can try

Which PWM pin on Uno are you using?

Different PWM pins use different internal hardware timers, so its important to know which timer needs to be changed to a higher frequency.

If you are using pins 5 or 6, I would recommend changing to use a different PWM pin. If you change the frequency for those pins, it might affect how delay() and millis() work.

For pins 9 or 10, try adding this to setup():

// Pins D9 and D10 - 31.4 kHz
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000001; // x1 phase correct

For pins 3 or 11

// Pins D3 and D11 - 31.4 kHz
TCCR2B = 0b00000001; // x1
TCCR2A = 0b00000001; // phase correct
2 Likes

for now I use 11, but I have all of them available to change if necessary

It is done by "manipulating the chip's timer registers directly". Interesting to look into; google will give you everything you need.

Alternatively, there are a few different libraries that will do most of the work for you.
TimerOne comes to mind. This example in particular seems appropriate.

Note: as PaulRB was getting at, this library will only work for pins 9 and 10.

1 Like

Follow up question, because I'm genuinely interested:

After setting TCCR1A / TCCR1B like that, can you adjust the duty with analogWrite(), or do you need to manually change OCR2A / OCR2B?

I think so, but test it. It might be necessary to set TCCR1A / TCCR1B each time after you use analogWrite().

I got the scope out and checked (UNO R3):

Calling analogWrite() doesn't seem to affect the clock select bits; setting the clock select bits doesn't seem to change the duty set by analogWrite(). Same behaviour on all pins, on all timers.

Which is neat!

2 Likes

The source of analogWrite() function is freely available, you can make sure that it doesn't affect a timer control registers.

That would have been, uh, a more intellectual way to go about it, yes..

Yes you can.

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