Need to set PWM frequency on Micro/Leonardo to 16khz for motor control

I have an Arduino Micro and I am controlling a motor with PWM but the 490hz frequency of the normal PWM can be heard coming from my motor and through my speakers (I have an MP3 module attached to my board as well).

I need to change one of the timers, and I'd rather it not be timer 0 because that would mess up millsecs(), or timer 4 because I may wish to switch to using a Pro Mini instead of the Micro. And since the Micro doesn't have a Tmer 2, that leaves Timer 3 or Timer 1.

Here are the pin mappings for the timers on the Micro:

TIMER0B, /* 3 /
TIMER3A, /
5 /
TIMER4D, /
6 /
TIMER1A, /
9 /
TIMER1B, /
10 /
TIMER0A, /
11 /
TIMER4A, /
13 */

There's a few things I'm confused about at this point.

First, if I set a prescalar of 1024 then that gives 16000000 / 1024 = 15625. Now does that mean my max PWM frequency will be 15625? In other words, will be pin be toggled 15625 a second? Or, will it actually be toggled at half that speed? I'm thinking it's half, because you can apparently set a prescalar of 1 on some timers and obviously the microcontroller can't toggle a pin on and off in the same cycle. So that would mean my max PWM frequency would be 7812 hz which is too low.

I guess one option to is to use the 256 prescalar, but then my max frequency is gonna be 31250 hz. If I set the output compare A I guess I can halve that to get 15625. But that brings me to the second thing I'm confused about.

I believe I can't vary the PWM frequency on pins marked with an A if I want to have that finer control of my output frequency using the compare A. Is that correct?

If so, that would seem to leave me with only one option, if I want a PWM frequency of 15625 hz... use TIMER1B on Pin 10.

But is there any real downside to using a PWM frequency of 31250 hz with my motor? It seems that since 15625 hz is still within range of our hearing that if I use that I may still be able to hear the noise on my speakers even if the motor doesn't make a sound at that frequency. And if I use the higher frequency will that then allow me to use pin 5 (TIMER3A) and 9 (TIMER1A)?

And how do I go about setting this anyway? I mean if I just change the prescalar can I just use the standard PWM functions? Or are those limited in precision in some way and I should just set the compare B directly to adjust the frequency? It seems timers 1 and 3 are 16bit on the Micro, but I think the pwm functions only use 8 bits of precision? I guess 8 bits is sufficient, I only need to run the motor at a minimum speed of 1/256.

The PWM frequency depends not only on the system clock frequency and prescaler, but also on the timer mode that is used and the TOP value that the timer is using. In the Arduino core, timer 0 is programmed in Fast PWM mode, with TOP=255. This gives a PWM frequency of F_CLK/(prescaler * 256). The other timers are programmed in phase-correct PWM mode, also with TOP=255, and the PWM frequency is F_CLK/(prescaler * 510).

So to get about 15kHz on timer 1 or 3, assuming a 16MHz clock you would need a prescaler of 2. Unfortuately, this isn't available - the nearest values you can get are 1 (giving about 33kHz) and 8 (giving about 4kHz).

The main downside to using a frequency as high as 33kHz is that switching losses in whatever is driving the motor will be higher, which could result in the motor driver overheating. What is driving the motor? If it is an H-bridge chip or module, check its recommended operating frequency range. Don't connect a capacitor in parallel with the motor, unless you also connect an inductor between the motor driver and the motor/capacitor junction.

If you want to use a frequency lower than 33kHz, then you can further tune the PWM frequency by using a different TOP value. As timers 1 and 3 are 16-bit, you can use TOP values up to 65535. For example, a prescaler of 1 and a TOP value of 500 in phase correct PWM mode will give you a frequency of 16000/(2*500) = 16kHz. You won't be able to use analogWrite in this case, because PWM values will range from 0 to 500 instead of 0 to 255, so you will have to write to the approriate registers directly.

The OCnA and OCnB outputs are no different from each other in terms of how you can control them, unless you use the OCRnA register to control the TOP value. But both timer 1 and timer 3 allow you to use the ICPn register to define the TOP value instead.

The atmega32u4 datasheet explains how to program the timers.

[EDIT: corrected numbers]

Thanks for the info.

I assume you meant to write 16000000 and not 16000 there.

The motor driver I am using is the following:

I don't see any specs as to the max drive frequency on either that page or in the chip's datasheet.

So if I use a TOP value of 511 and a prescalar of 1 in phase correct mode, I will get a frequency of 15656 hz..

Is there a benefit to using phase correct mode here? I've read about that but I still don't really understand the difference aside from it taking twice as long to count up and then down again. But perhaps that's the point here? To emulate having a prescalar of 2 available?

And if that's the case could I not use the prescalar of 256, which when doubled would give me 512 like I need, thus allowing the use of analogWrite(), and all the pins labeled A, without requiring the use of the ICPn register?

scswift:
I assume you meant to write 16000000 and not 16000 there.

I meant 16000 because I was calculating the result in kHz, but I guess it's a bit ambiguous.

scswift:
The motor driver I am using is the following:
Pololu - DRV8801 Single Brushed DC Motor Driver Carrier

I don't see any specs as to the max drive frequency on either that page or in the chip's datasheet.

The chip datasheet quotes a propagation delay time to LOW output of 100ns, and 600ns to HIGH - but that includes a deliberate delay to avoid shoot-through. With the switching being that fast, I don't think you will have a problem using 33kHz PWM with that chip.

scswift:
So if I use a TOP value of 511 and a prescalar of 1 in phase correct mode, I will get a frequency of 15656 hz..

Yes.

scswift:
Is there a benefit to using phase correct mode here? I've read about that but I still don't really understand the difference aside from it taking twice as long to count up and then down again. But perhaps that's the point here? To emulate having a prescalar of 2 available?

I think that in this application, you could just as well use a TOP value of 1020 and fast PWM mode to get the same frequency.

scswift:
And if that's the case could I not use the prescalar of 256, which when doubled would give me 512 like I need, thus allowing the use of analogWrite(), and all the pins labeled A, without requiring the use of the ICPn register?

A prescaler of 256 will give you a much lower PWM frequency. The output frequency is:

  • in fast PWM mode: F_CLK/(prescaler * (1 + TOP))
  • in phase-correct PWM mode: F_CLK/(prescaler * TOP * 2)

If you are looking for about 16kHz PWM, then if TOP = 255 (the default), you would need a prescaler of 4 in fast PWM mode, or 2 in phase-correct PWM mode - but the prescsaler does not support these values.

A prescaler of 256 will give you a much lower PWM frequency. The output frequency is:

  • in fast PWM mode: F_CLK/(prescaler * (1 + TOP))
  • in phase-correct PWM mode: F_CLK/(prescaler * TOP * 2)

If you are looking for about 16kHz PWM, then if TOP = 255 (the default), you would need a prescaler of 4 in fast PWM mode, or 2 in phase-correct PWM mode - but the prescsaler does not support these values.

I'm still a bit confused here.

In fast PWM mode I have:
16000000/(prescaler * (1 + TOP))

If TOP is 0, then PWM frequency is 16000000/prescaler. If prescalar is 1 then that would mean the PWM frequency is 16mhz. But that can't be right, can it? The frequency would be half that because it's set high for one cycle and then low for the next, wouldn't it? So the max PWM frequency would be 8mhz.

And that means if I used a prescalar of 1024 in fast PWM mode, my frequency would be half of 15625 or 7812 hz, right?'

So if I used a prescalar of 256 in fast PWM mode, 16mhz / 256 = 62500, which divided by 2 = 31250.

But perhaps when you talk of PWM frequency you're talking about how fast the pin toggles rather than counting full on/off cycles as you would if you were talking about the frequency of a sound?

scswift:
I'm still a bit confused here.

In fast PWM mode I have:
16000000/(prescaler * (1 + TOP))

If TOP is 0, then PWM frequency is 16000000/prescaler.

If TOP is 0 then you can't do PWM at all. The value for TOP when you don't use ICRn or OCRnA to define it is 255.

I'm still confused about how to set this up.

I guess what I want to do is set up timer 1 to be phase correct, with a prescalar of 1 and a count of 511.

But reading this tutorial it doesn't make sense:

Similarly, the timer can be configured in phase-correct PWM mode to reset when it reaches OCRnA. Phase-Correct PWM with OCRA top The following code fragment sets up phase-correct PWM on pins 3 and 11 (Timer 2), using OCR2A as the top value for the timer. The waveform generation mode bits WGM are set to to 101 for phase-correct PWM with OCRA controlling the top limit.

  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS22);
  OCR2A = 180;
  OCR2B = 50;

I see bit 0 being set in TCCR2A there. And I see bit 2 being set in TCCR2B. But the tutorial says "The waveform generation mode bits WGM are set to to 101 for phase-correct PWM". Neither 001 or 100 are 101.

I also noticed it seems possible to set up the timer to have an 8 bit 9 bit or 10 bit count, and I suspect this code is setting it up to be 8 bit and I don't know how to set it to phase correct 16 bit. There's so many options and I have no idea which are the right ones. It mentioned phase correct AND frequency correct in one option and I didn't even know frequency correct was an option or how that affects the PWM.

scswift:
I see bit 0 being set in TCCR2A there. And I see bit 2 being set in TCCR2B. But the tutorial says "The waveform generation mode bits WGM are set to to 101 for phase-correct PWM". Neither 001 or 100 are 101.

The WGM bits are split between TCCRnA and TCCRnB. Bits 0 and 1 live in TCCRnA. Bit 2, and bit 3 for timers that use it, live in TCCRnB.

scswift:
I also noticed it seems possible to set up the timer to have an 8 bit 9 bit or 10 bit count, and I suspect this code is setting it up to be 8 bit and I don't know how to set it to phase correct 16 bit. There's so many options and I have no idea which are the right ones. It mentioned phase correct AND frequency correct in one option and I didn't even know frequency correct was an option or how that affects the PWM.

The datasheet explains it all quite well, although there is a lot of information to digest. I haven't used the 9- or 10-bit PWM modes of timer 1, but I frequently use the modes in which ICR1 sets the TOP value. If you really want to get 16 bits of PWM resolution, then you will need to set TOP to 0xFFFF, and the maximum PWM frequency (with prescaler set to 1) will be 16MHz/(2 * 65536), which is 122Hz and probably lower than you want.

I don't want 16 bits of PWM resolution but rather to be able to set the top value to a value greater than 255.

scswift:
I don't want 16 bits of PWM resolution but rather to be able to set the top value to a value greater than 255.

Then use WGM mode 0010 to get TOP = 511, or mode 0011 to get top = 1023, or mode 1010 and program the required TOP value into ICR1. See table 16-4 on the atmega328p datasheet.

Hm...

This is so simple yet so difficult to understand, but I think I'm starting to get it.

So if we look at mode 0 there, the TOP value is set to 0xFFFF. That's all it can ever be, so when we set OCR1B to adjust the PWM duty cycle, it's relative to that.

IE:
OCR1B / 0xFFFF = PWM duty cycle (0 .. 100%)

And the TOP value (along with the prescalar, and choice of fast or phase correct pwm mode) defines our PWM frequency.

You gave these equations for that:

  • in fast PWM mode: F_CLK/(prescaler * (1 + TOP))
  • in phase-correct PWM mode: F_CLK/(prescaler * TOP * 2)

So with a TOP value of 0xFFFF (65535), and a F_CLK of 16000000, and a prescalar of 1, we get 16000000 / 65536 = 244hz

And that PWM will be 244hz no matter what we set our duty cycle to with OCR1B. The duty cycle merely adjusts the ratio of how long the pulse is on vs. off.

Now, since I need a PWM frequency much higher than 244hz, for fast PWM (with a prescalar of 1) I can calculate the TOP value I need like so: 16000000 / frequency = TOP.

So for 30khz I would need a TOP value around 530. Or for 15khz, I would need a TOP value around 1067. Since I like to stick to nice round binary numbers though, I'd choose 511 or 1023, which give me 31250 hz or 15625 hz.

Of course I can't use mode 0 if I want to change the TOP value. I have to choose one of the other modes.

I could choose a mode where I set the TOP value using OCRnA, but then I would lose the ability to do PWM on port 9. Not that I want to; just noting it.

Or I could choose a mode where I set the TOP value with ICRn. Unfortunately I have no idea what that register is or what side effects that may have. (And if there are none, then why would you ever want to use OCRnA?)

But what of these 8 bit, 9 bit, and 10 bit modes?

I have just realized that what those mean is that in those modes, TOP will be either 255, 511, or 1023. No need to set another register to determine it's value.

So with fast PWM, I could choose 9bit or 10bit mode to get the 31250 hz or 15625 hz I need.

Or, if I choose a phase correct mode (with a precalar of 1), since TOP counts both up and down, my frequency will be halved. So I would choose either 8bit or 9bit mode to get 31250 hz or 15625 hz PWM.

Now to see if I can figure out what ICRn is and why I would or would not want to use that all the time.

Well, I've gone though the document and I think maybe ICRn is used when triggering an interrupt on some input on a pin, so I guess whether I should use it or use OCRnA or not depends on what I want to use pin 9 for. If I want to use it for PWM then I'd use ICRn, and if I just want to use it for general input or output then it doesn't matter which I use.

Confused again.

Page 19, timer control register:

Some example code in reply #22:
http://forum.arduino.cc/index.php?topic=174677.15

  //  Sets Timer1 to Phase Correct
  //  F_CLOCK / ( Prescaler * ORCR1A * 2 ) = Freq in Hz
  //  16000000 / (1 * 512 * 2 ) = 15625 Hz
  TCCR1A = _BV (WGM10) | _BV (WGM11) | _BV (COM1B1);  // Phase Correct
  TCCR1B = _BV (WGM13) | _BV (CS10);                  // Phase Correct / Prescale 1
  OCR1A = 512;                                        // Sets Top to 512 
  OCR1B = 0;                                          // Sets Pwm = 0

So the WGM bits I get. That sets mode 11.

But the COM1B1 bit I don't get.

You've got COM1A0, COM1A1, COM1B0, COM1B1, and on the 32U4 which I'm using, COM1C0, COM1C1.
And Figure 14-4 shows what compare modes each pair of bits selects.

But I don't get how to use that information.

The example above sets COM1B1. And that appears to select this mode:

WGM13:0 = 8, 9 10 or 11: Toggle OC1A on
Compare Match, OC1B and OC1C
disconnected (normal port operation). For all
other WGM1 settings, normal port operation,
OC1A/OC1B/OC1C disconnected.

But why is this COM1B1 bit set? Why not COM1A1? Will setting either one enable this mode where B and C are disconnected? And if so, what happens if I set COM1B1 but also set COM1A1 and COM1A0 which would appear to set A to a mode that conflicts which what setting COM1B1 should enable?

And another thing I'm confused about is why does it say toggle A? I thought A was the pin you couldn't do PWM on when using OCRnA as the TOP value as is being done in mode 11?

WGM13:0 = 8, 9 10 or 11: Toggle OC1A on
Compare Match, OC1B and OC1C
disconnected (normal port operation). For all
other WGM1 settings, normal port operation,
OC1A/OC1B/OC1C disconnected.

Hm... wait, I think I understand. It's just written really confusingly.

If I in mode 11 (phase correct PWM) and I set COM1A0 then it will "toggle OC1A on Compare Match".
But setting that bit does not change the behavior or OC1B or OC1C at all.

And if I am in mode 11 and set COM1B0 or COM1C0, nothing special happens, they remain disconnected.

Also I just noticed I was looking at the wrong mode. It's bit 1 that's being set not bit 0. So the mode being set for B is:

Clear OCnA/OCnB/OCnC on compare
match when up-counting. Set
OCnA/OCnB/OCnC on compare match
when downcounting.

Which sounds right for phase correct PWM on B.

Looks like you're getting it now. Apart from setting TOP, the other use of the ICP1 register is with the Input Capture facility. If you enable this facility, then a transition on a particular pin (the ICP1 pin) or on the analog cmoparator output causes the current value of the TCNT1 register to be copied to the ICP1 register, and optionally an interrupt raised. This facility is useful for timing input signals. If you are not using input capture, then ICP1 is free for using as TOP.

Well I seem to have it figured out and working. I decided to go with the 8 bit or 9 bit phase correct mode just to be different, since I was going to set TOP to 511 or 255 anyway.

I do have a question about something you said earlier though. You said not to put capacitors on the motor unless I also had an inductor. Why is that?

scswift:
I do have a question about something you said earlier though. You said not to put capacitors on the motor unless I also had an inductor. Why is that?

If you put a capacitor across the motor terminals, or between the motor terminals and ground, then every time the H-bridge switches polarity, those capacitors have to charge to the new output voltage. If you don't have any series resistance or inductance, then this puts high peak currents through the H-bridge mosfets. This is not good for them, and at high PWM frequencies may result in a substantial power dissipation, as well as RFI generated by the motor wires. So if you use a capacitor on the motor, then I suggest you use only modest capacitor values, and add some series inductance to reduce the peak current.

Wow.
This is lengthy, but just what I needed. Reading Data sheets is like learning telephone books.

I have a similar problem, on a stage our kids want to do a gospel musical where motors should change the appearance of the stage by winding up cloth on an axis or letting it down dynamically as part of the DMX controlled light show. Reading http://ulrichradig.de a lot, no libraries, plain c, very clean and reliable code...

I have bought the Infineon motor control shield for Arduino, 32-bit XMC™ Industrial Microcontroller Arm® Cortex®-M - Infineon Technologies
doing max. 24 kHz / 40A / 18V. Sounds promising and seems to keep the promises - this is not trivial because a lot of chip companies lie a bit with their specs on H-Bridges.
In the vicinity of microphones etc. I will be well advised to use a "ultra-sound" PWM base frequency.

The hint on removing Capacitance at the motor is really good. I broke one open, and easter eggs I found: inside sit 2 inductances wirth open coils for filtering broad-band noise, and a capacitor over the terminals, and a serial PTC as some protection against fire inside. Perhaps I will throw all of it out, insert some NTC delivering temperature to the micro pro board. I read that the coils are damping, special ferrite core, in a wide frequency range, but I do not want to damp my high speed pwm. Infineon has some examples just using small capacitances on their board. They also elaborate on the trade-off between EMC and Efficiency, because you can control the steepness of the switching curve at a pin on their 1/2 H-bridge chip BTN8982TA.

To make the motor a servo:
I broke apart an old fan, and extracted the flat H-Magnetic field sensor with digital (schmitt-triggered) output from its pcbs and got a nice ring magnet with 4 N and 4 S - Poles per 1rotation from the blade. I broke away the fins and drilled a center hole after breaking out the axis. I could just tightly fit it on my 8,5mm motor axis inside the motor casing between case and coils, just using 3mm space along the axis and 15mm diameter or so.
Perhaps I will place a second H-Sensor-Chip from a to-be-slaughtered old fan to have a directional signal by placing it 90 deg. phase shifted in the magnetic signal.
But since I don't have a xmega that is able to decode endian per hardware, I will use this only when the motor is moving slow, coming to a halt, because then the simply counting of impulses will be error prone when a motor hovers vibrating on a spot (i.e. around some angular position where he induces a lot of counts in simple rotational sensors, but doesn't move at all.) This implies programming interrupt on pin changes on the 2 pins coming from the 2 magnetic sensors. If I should add fotos / circuitry, tell me.

The ATmega32U4 Datasheet says: it has a PLL.
If you switch off USB on the MICRO PRO or Fio you are able to use PLL as clock source for timers.
Theoretically you may be able to get a clock of 60MHz by this. After waiting 0,1s to stabilize, that is.
Don't touch the PLL if USB is on, it needs it. Perhaps one could get out of the USB serial monitoring in arduino for the micro what PLL frequency is set and if we can copy this without disturbing the USB to some PWM Timer.

Thank you for patient explanations, dc42. Some like me need that badly :wink:

Andi

Confusion comes from overload with me: I'm starting to learn C, C++, bit Assembler, using AVR Studio6, eclipse, cypress pSoC, Arduino nano v3 and micro pro and a breadboard with good plain 328p with AVR JtagIceMkII. Still 19cm of paper from library are waiting. The best one is o'really advanced arduino cookbook.