# Generating Sinusoid Signal of 40khz [closed]

I would like to generate a sinusoidal signal of 40kHz using Arduino Uno. Maximum I could generate was 1kHz, using bit banging, fast PWM. Do you have ideas of how to boost it to 40kHz?

• What kind of resolution (both amplitude an time resolution) are you wanting? Mar 27, 2018 at 21:12
• Sorry, not sure what do you mean by the time resolution, but I am planning to feed the signal into a transmitter and receive it on the other end. I use speakers that work at 40kHz frequency as both transmitter and receiver. Mar 27, 2018 at 21:18
• Time resolution: how many samples per second (or samples per sinewave period) do you want? Mar 27, 2018 at 21:30
• i mean, based on Nyquist rate, I guess it should be 2*40khz at least. But otherwise, no preference Mar 27, 2018 at 21:32
• That would give you a square wave. It depends on what quality you want. Anything less than say 128 samples per period would end up in something more like a triangle wave. Mar 27, 2018 at 21:33

Let's first do some maths.

• You want 40,000 cycles per second.
• Each cycle needs splitting up into samples. For example, let's use 128 samples.
• Assume you want an 8-bit amplitude resolution.

Each second of signal would need 40,000 cycles * 128 samples. That's 5120000 samples per second.

If using PWM to generate the audio that's 256 clock cycles (28) per sample. That means 5120000 * 256 = 1,310,720,000.

That means a "carrier frequency" of over 1.3GHz. There's no way an Arduino can do that.

If instead you used a simple DAC (e.g., an R-2R ladder) connected to the 8 pins of port D (that's pins 0-7 on the Uno) you don't need the 256 clock cycles per sample. That means that you have to output a new sample to PORTD 5,120,000 times per second. That's outputting at over 5MHz.

With some well crafted assembly code that might be possible. The Arduino certainly won't be able to do anything else at all at the same time.

You would be much better off using a chip that has audio capabilities and DMA. Maybe a Teensy 3.x would be a better choice for your project.

• That seems reasonable, I'll research into that. Thanks a lot Mar 27, 2018 at 21:51
• You don't need anywhere near 128 samples per cycle; in fact you only need 2. Using so many just makes the analog cleanup filter simpler. Mar 28, 2018 at 0:49
• With 2 samples you can only generate a square wave. Yes, you can then add extra circuitry to remove the higher frequency components, but as you say it's more complex. The question is about generating a sinusoid, not generating a square wave and converting it to something close-ish to a sinusoid. Mar 28, 2018 at 8:48
• If let's say you decide to take 10 samples per period instead of 180, the sinusoid is still supposed to look decent. But that gives you 10*40,000*256 = 102MHz clock, but Arduino only has 16MHz clock. Mar 29, 2018 at 20:56
• Any number of samples is kind of ludicrous on such a small MCU. Mar 29, 2018 at 22:50