Go Down

Topic: How to create a 38 Khz pulse with arduino using timer or PWM? (Read 21 times) previous topic - next topic

praky


Quote
Also I understand pin 3 and pin 11 cannot be use for any other purpose

If that is what you understand then you are wrong.


Please explain. I am not an experienced coder.

I see in the comments that pin 11 is being disabled for the output that why i said i t is not available for use.
As for pin 3, i meant that since the 38 Khz wave will be available on that pin, it has been made use of.


Nick Gammon

#12
Apr 23, 2012, 12:05 am Last Edit: Mar 14, 2013, 09:57 am by Nick Gammon Reason: 1
This code generates 38 KHz on pin D11 on the Mega2560:

Code: [Select]

const byte LED = 11;  // Timer 2 "A" output: OC2A

void setup() {
 pinMode (LED, OUTPUT);
 
 // set up Timer 2
 TCCR2A = _BV (COM2A0) | _BV(WGM21);  // CTC, toggle OC2A on Compare Match
 TCCR2B = _BV (CS20);   // No prescaler
 OCR2A =  209;          // compare A register value (210 * clock speed)
                        //  = 13.125 nS , so frequency is 1 / (2 * 13.125) = 38095

}  // end of setup

void loop() { }


It does not use interrupts and does not interfere with any other pin.

(edit) Changed from D10 to D11. OC2A outputs on D11.

praky

#13
Apr 23, 2012, 12:21 am Last Edit: Apr 23, 2012, 12:23 am by praky Reason: 1

Why not just use the Tone() function?
http://arduino.cc/en/Reference/Tone


This looks interesting!! and hugely simplistic.

Can this produce a freq. as large as 38 Khz? In the example they are using quite low frequencies. will test this tomorrow.

Nick Gammon

Code: [Select]
void setup ()
{
tone (10, 38000);
}
void loop () {}


That generates a 38 KHz output, more or less. However it's not as smooth as the hardware timer.

The tone library uses a timer, but that causes an interrupt. Inside the interrupt it does a counter. When the counter is met it toggles the pin. So there is a bit of jitter (because other interrupts might fire), and it consumes CPU resources.

The pure hardware solution described above runs without any code being called at all (once you set it up).

Go Up