How to set 19.5Hz PWM frequency?

Hi there,

I am trying to control some solenoids and the pwm frequency has to be 19.5Hz!!! I have searched the forum and the tables say that the minimum frequency that i can set is around 30Hz. I have an arduino UNO board and i only need one output!

Set up a timer that interrupts at your duty cycle (say 500us). Once that timer trips, set it up for another interrupt for 51582us-500us. This provides a total period of 51582us -> 19.5hz.

On a resource rich system, you can implement a two-timer solution, with one setting the pin and another clearing it.

psyche: I am trying to control some solenoids and the pwm frequency has to be 19.5Hz!!!

At that low of a frequency you could just use blink-without-delay.

psyche: I am trying to control some solenoids and the pwm frequency has to be 19.5Hz!!!

That seems a very odd requirement. Are you quite sure it has to be exactly 19.5Hz, rather than at least 19.5Hz? Can you provide a link to the solenoid datasheet?

Although timer/counters 0 and 2 are limited to approximately 30Hz and above on a standard 16MHz Arduino, you should be able to get a single 19.5Hz PWM signal from TC1. Set the prescaler to 64, register OCR1A to 6409, and OCR1B to 0-6409 to get the required on/off ratio. That will give you a frequency of 16000000/(64*(6409+1)*2) = 19.5008Hz.

psyche: I am trying to control some solenoids and the pwm frequency has to be 19.5Hz!!!

That is sloooow. You can use as dumb an algorithm to control that as you want. It barely needs more than the Blink example, as long as you are not careless calculating the transition times.

You can do it with a hardware timer, but the last time someone wanted such a slow PWM frequency they were trying to change traffic lights from red to green on-the-fly. I don’t suppose this is anything to do with that?

Hehehehe! Nick what i want to do is control a solenoid from a car! People have reported the 19.5Hz frequency to be the correct one to control it! I haven't measured the output of the car's ECU but if everyone says that the frequency is 19.5Hz then this is it!

Any code examples to get an idea? Or a guide?

If i change the pwm frequency in this sketch, will i have to change it if i build a new sketch? Do i have to set it back to default?

Thanx guys

1000000 / 19.5 = 51282.0512821 microseconds. Let's call it 51282. I doubt the extra precision is going to matter with a solenoid.

This might work...

``````const uint8_t SOLENOID_PIN = 13;

const unsigned long PulseWidth = 51282UL;

static unsigned long CurrentHighWidth;

void setup( void 0
{
pinMode( SOLENOID_PIN, OUTPUT );
CurrentHighWidth = (PulseWidth / 2) /* some fraction of PulseWidth */;
}

void loop( void )
{
unsigned long Now;

Now = micros();

if ( Now - PreviousLeadingEdge >= PulseWidth )
{
digitalWrite( SOLENOID_PIN, HIGH );