PWM duty cycle

I understand how PWM works, but am a bit foggy on how to apply it to my project. I am controlling a couple motors using a L293D and that’s working ok for on/off and direction. Now I would like to use PWM to control the speed of the motors. I am seeing a lot of stuff on the web about changing the frequency of PWM, but I am thinking that is not what I want to do. I need to change the duty cycle, not the frequency, right?

Can anyone point me to some examples of how I might change the duty cycle on one of the Arduino PWM pins. I know how to do it programatically with delaymicroseconds (I think), but that requres the full time attention of the processor. I need to change the duty cycle and forget it until I need to change it again.

Am I asking too much?

Charlie

You change the duty cycle of a PWM pin with analogWrite(). A value of 0 gets you 0% duty cycles (or nearly so). A value of 255 gets you 100% duty cycle. Can you guess that 128 gets you 50% duty cycle?

That simple. WOW! Not sure why I thought it was a bigger deal.

Thank you very much.

Charlie

This worked, but raised two issues. At 255 (100%) the motor works pretty much as it would if I used digitalWrite to set it high. Anything less than 255 causes a weird scream from the motor. Also, at lower speeds, the torque of the motor drops to just enough to move the wheels with no load, but would never operate under a load.

Is this more likely an issue of frequency, cheap motors, so something else? Would changing the PWM frequency help? If so, I would think the lower the better (up to a point), although maybe this would just create a lower pitched scream.

Thanks

The duty cycle is a percentage, but the torque will probably change exponentially. So 50 % duty cycle is nowhere near 50 % torque. I'd do some tests where you slowly ramp up the duty cycle (with and without load) and find optimal values. You'll see that there is a difference between starting (higher duty cycle needed) and keep running (so lower needed).

Changing the frequency might help against the audible noise, i don't think it will do much about the torque. I'd try a higher frequency first. The PWM from your Arduino has a relatively low frequency (somewhere between 400 and 500 Hz if i remember right). It wouldn't surprise me if the noise is caused by resonance, which is easier to occur on lower frequencies. Any object has its own optimum resonance frequency, and you want to stay away as far as possible for your object (the motor).