Go Down

Topic: Generating 40kHz square wave (Read 2 times) previous topic - next topic

sirch

Hi, new here and probably being a bit dim but I've Googled and done all the obvious stuff and I cannot figure out how to program the PWM to get a 40kHz signal to drive an ultrasonic sender for a distance measurement device.

I've got the example below running an giving me 8kHz but how do I scale this to get 40kHz. Also on my ATMega1280 the output is on pin 13, not pin 6 which this example code suggests (I guess the code is for a different processor). I've read the datasheet but it just went in and fell straight out again. Any help appreciated.

Code: [Select]

#include <avr/io.h>

int main(void)
{
    DDRD |= (1 << DDD6);
    // PD6 is now an output

    OCR0A = 128;
    // set PWM for 50% duty cycle


    TCCR0A |= (1 << COM0A1);
    // set none-inverting mode

    TCCR0A |= (1 << WGM01) | (1 << WGM00);
    // set fast PWM Mode

    TCCR0B |= (1 << CS01);
    // set prescaler to 8 and starts PWM


    while (1);
    {
        // we have a working Fast PWM
    }
}

dhenry

You need a pwm mode that allows you to set the top.

AWOL

Quote
You need a pwm mode that allows you to set the top.

Was the any more to your post, dhenry?
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

PeterH

You need to carefully read Nick Gammon's web site, I'd suggest starting here:

Nick Gammon's description of Timers and Counters
I only provide help via the forum - please do not contact me for private consultancy.

GoForSmoke

PWM frequency on the Playground:
http://playground.arduino.cc//Code/PwmFrequency

Quote
Please keep in mind that changing the PWM frequency changes the Atmega's timers and disrupts the normal operation of many functions that rely on time (delay(), millis(), Servo library).



I find it harder to express logic in English than in Code.
Sometimes an example says more than many times as many words.

Go Up