How would I go about changing the frequency of the analogWrite() function in Arduino?

I am designing an ultrasonic parking sensor, and need to use the analogWrite() function to produce a 50% duty cycle PWM.

I would ordinarily use the tone() function in this situation however, this is currently tied up with something else and noTone() cannot be called.

The problem I am having is with the default frequency of the analogWrite() function aliasing occurs with my reading on the ultrasonic sensor and I receive values that are a factor of ten off what they should be. I have tested the sensor at a range of frequencies and it appears to work best at about 50 Hz.

Any help would be greatly appreciated.

sort by: active | newest | oldest
50Hz is not very ultrasonic. AFAIR, the default PWM frequency is pretty low - 400 Hz rings a bell.

When you need to code down to the iron on an Arduino, for PWM purposes, this is the best reference I know of
Pash1987 (author)  steveastrouk6 years ago
Yeah, 50Hz isn't very ultrasonic, but I've got a component to do that for me. All I need to do is give it a pulse to initiate the sensor.

Thanks for the link. I haven't fully read it yet, but it seems to be what I'm after.
NOT the old "polaroid" system, or its newer incarnation ?

Steve
Pash1987 (author)  steveastrouk6 years ago
Sorry, I'm quite new to this. I'm not quite sure what you mean, but if its the sensor you're on about, its an SRF04 ultrasonic ranger - http://www.robotstorehk.com/srf04tech.pdf
Ah, its a descendant of the Polaroid system.

I'm not sure why you need a 50Hz square wave to drive it though.

Steve
Pash1987 (author)  steveastrouk6 years ago
That's a very good point. I think I was just in a one-track fame of mind.
Although I guess it's useful to know how to alter the PWM frequency :)
Its also important to dynamically adjust the trigger depending on how long the last pulse took....

Steve