Arduino sketch for high frequency precision sine wave tone sound synthesis

This table-based digital audio oscillator implementation illustrates a few useful techniques on 8-bit microprocessors such as the Atmel parts supported by the Arduino/Wiring IDE. A timer is used to establish the sample rate clock and PWM is used to output an 8-bit signal. Human hearing has impressive frequency precision so accumulation is done on 32-bit integers. The code is a lesson in how to used fixed point representations and careful sizing of tables as powers of 2. This reduces the computational cost of the inner loop of the oscillator to a single 8-bit multiply, table lookup and addition of the phase accumulator. This snapshot is part of my ongoing effort to provide some sound synthesis tools for the Arduino beyond the basic buzzy tones. And as Sabine Gruffat shows us beautifully you can use oscillators like this for image synthesis: Some useful references:
 // Atmega table-based digital oscillator
// using "DDS" with 32-bit phase register to illustrate efficient
// accurate frequency.
// 20-bits is on the edge of people pitch perception  
// 24-bits has been the usual resolution employed.
// so we use 32-bits in C, i.e. long.
// smoothly interpolates frequency and amplitudes illustrating
// lock-free approach to synchronizing foreground process  control and background (interrupt) 
// sound synthesis

// copyright 2009. Adrian Freed. All Rights Reserved.
// Use this as you will but include attribution in derivative works.
// tested on the Arduino Mega

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>

const unsigned int LUTsize = 1<<8; // Look Up Table size: has to be power of 2 so that the modulo LUTsize
                                   // can be done by picking bits from the phase avoiding arithmetic
int8_t sintable[LUTsize] PROGMEM = { // already biased with +127

int8_t triangletable[LUTsize] PROGMEM = {


const int timerPrescale=1<<9;

struct oscillator
    uint32_t phase;
    int32_t phase_increment;
    int32_t frequency_increment;
    int16_t amplitude;
    int16_t amplitude_increment;
    uint32_t framecounter;
} o1;

const int fractionalbits = 16; // 16 bits fractional phase
// compute a phase increment from a frequency
unsigned long phaseinc(float frequency_in_Hz)
   return LUTsize *(1l<<fractionalbits)* frequency_in_Hz/(F_CPU/timerPrescale);

// The above requires floating point and is robust for a wide range of parameters
// If we constrain the parameters and take care we can go much
// faster with integer arithmetic
// We control the calculation order to avoid overflow or resolution loss
 // we chose "predivide" so that (pow(2,predivide) divides F_CPU,so 4MHz (1.7v), 8Mhz, 12Mhz (3.3v) and 16Mhz 20Mhz all work
 // AND note that "frequency_in_Hz" is not too large. We only have about 16Khz bandwidth to play with on
 // Arduino timers anyway
const int predivide = 8;
unsigned long phaseinc_from_fractional_frequency(unsigned long frequency_in_Hz_times_256)
    return (1l<<(fractionalbits-predivide))* ((LUTsize*(timerPrescale/(1<<predivide))*frequency_in_Hz_times_256)/(F_CPU/(1<<predivide)));


// tabulate phaseincrements correspondending to equaltemperament and midi note numbers (semitones)
#define MIDITOPH
#define mtoph(x) ( phaseinc(8.1757989156* pow(2.0, x /12.0) ))

unsigned long midinotetophaseinc[128]= 
  mtoph(0), mtoph(1), mtoph(2),mtoph(3), mtoph(4), mtoph(5), mtoph(6), mtoph(7),    
  mtoph(8),mtoph(9), mtoph(10), mtoph(11), mtoph(12), mtoph(13), mtoph(14), mtoph(15),    
   mtoph(16), mtoph(17), mtoph(18), mtoph(19), mtoph(20), mtoph(21), mtoph(22), mtoph(23),   
  mtoph(24), mtoph(25), mtoph(26), mtoph(27), mtoph(28), mtoph(29), mtoph(30), mtoph(31),   
   mtoph(32), mtoph(33), mtoph(34), mtoph(35), mtoph(36), mtoph(37), mtoph(38), mtoph(39),   
  mtoph(40), mtoph(41), mtoph(42), mtoph(43), mtoph(44), mtoph(45), mtoph(46), mtoph(47),   
   mtoph(48), mtoph(49), mtoph(50), mtoph(51), mtoph(52), mtoph(53), mtoph(54), mtoph(55),   
  mtoph(56), mtoph(57), mtoph(58), mtoph(59), mtoph(60), mtoph(61), mtoph(62), mtoph(63),   
  mtoph(64), mtoph(65), mtoph(66), mtoph(67), mtoph(68), mtoph(69), mtoph(70), mtoph(71),   
  mtoph(72), mtoph(73), mtoph(74), mtoph(75), mtoph(76), mtoph(77), mtoph(78), mtoph(79),   
   mtoph(80), mtoph(81), mtoph(82), mtoph(83), mtoph(84), mtoph(85), mtoph(86), mtoph(87),   
  mtoph(88), mtoph(89), mtoph(90), mtoph(91), mtoph(92), mtoph(93), mtoph(94), mtoph(95),   
   mtoph(96),mtoph(97), mtoph(98), mtoph(99), mtoph(100), mtoph(101), mtoph(102), mtoph(103),    
  mtoph(104),mtoph(105), mtoph(106), mtoph(107), mtoph(108), mtoph(109), mtoph(110), mtoph(111),    
   mtoph(112),mtoph(113), mtoph(114), mtoph(115), mtoph(116), mtoph(117), mtoph(118), mtoph(119),    
  mtoph(120), mtoph(121), mtoph(122), mtoph(123), mtoph(124), mtoph(125), mtoph(126), mtoph(127)  
#undef mtoph

// Timer setup constants

#if defined(__AVR_ATmega8__)

// On old ATmega8 boards, output is on pin 11
#define PWM_PIN       11
#elif defined(__AVR_ATmega1280__)

#define PWM_PIN       3

// For modern ATmega168 boards, output is on pin 3
#define PWM_PIN       3

void initializeTimer() {
 // Set up PWM  with Clock/256 (i.e.  31.25kHz on Arduino 16MHz;
 // and  phase accurate

#if defined(__AVR_ATmega8__)
  // ATmega8 has different registers
  TCCR2 = _BV(WGM20) | _BV(COM21) | _BV(CS20);
#elif defined(__AVR_ATmega1280__)
  TCCR3A = _BV(COM3C1) | _BV(WGM30);
  TCCR3B = _BV(CS30);
  TIMSK3 = _BV(TOIE3);
  TCCR2A = _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);
  TIMSK2 = _BV(TOIE2);

void setup()
    o1.phase = 0;
   o1.phase_increment = 0 ;
   o1.amplitude_increment = 0;
   o1.frequency_increment = 0;
   o1.framecounter =0;
     o1.amplitude = 0; // full amplitude

void loop() {

// Examples
  o1.amplitude = 255*256; // full amplitude
  // All the MIDI note numbers
   for(int i=0;i<128;++i)
     o1.phase_increment = midinotetophaseinc[i];
   // linear frequency steps from fractional frequency
   unsigned long l;
     o1.phase_increment = phaseinc_from_fractional_frequency(l*256);

 o1.phase_increment = phaseinc(440.0);
  o1.phase_increment = phaseinc(220.0);
  o1.phase_increment = phaseinc(600.0);

   //sweep up
 o1.phase_increment = phaseinc_from_fractional_frequency(100UL*256);
  o1.frequency_increment = phaseinc(0.02);
  o1.framecounter = 200000;
  //sweep down
  o1.phase_increment = phaseinc_from_fractional_frequency(10000UL*256);
  o1.frequency_increment = -phaseinc(0.02);
  o1.framecounter = 200000;

// this is the heart of the wavetable synthesis. A phasor looks up a sine table
int8_t outputvalue  =0;
   PWM_VALUE_DESTINATION = outputvalue; //output first to minimize jitter
   outputvalue = (((uint8_t)(o1.amplitude>>8)) * pgm_read_byte(sintable+((o1.phase>>16)%LUTsize)))>>8;
  o1.phase += (uint32_t)o1.phase_increment;
  // ramp amplitude and frequency
     o1.amplitude += o1.amplitude_increment;
     o1.phase_increment += o1.frequency_increment;



Very nice compact code! I was thinking about doing such a thing, and you example has given me a flying start. I'm working on my guitar, it has a DIY midi remote for my guitarsynthesizer. The guitarsynhesizer has midi out, so if I take you code and add a midi input, I can create a simple monophonic synth on the same chip without any extra hardware. great!

Thanks and request for some hints

I copied and edited out much of your wavetable synth sketch and feel that it is very close to what I need for a project I am working on. I am a beginner with Arduino and know very little C so I am having trouble understanding exactly how the interrupts work and how I can adapt the code to do what i really need. I need to produce single pulses of triangle waves (one 360degree waveform) at precise times and always starting at 0 degrees. Can you provide some hints as to how I can generate single pulses in stead of having the PWM run all the time?

Arduino sketch for high frequency precision sine wave tone sound

Still a great way to get clean sine wave sound out of the Arduino's digital output without additional electronics! I would appreciate a newbie-friendly explanation of how this example works, especially what the triangle-table is for and where the data in it come from.

16 bit

It seems possible to use the 16bit PWM on timer1 to make a 16bit sine wave instead of the 8bit one here. I'm having some trouble in my implementation and was wondering if you have any code to do this? Anytime I go above 8bit PWM I get an unsine response.

Thanks for your interest. No

Thanks for your interest. No I haven't done a higher resolution one. Most users of the code won't want to spend the money on the analog reconstruction filter required to get 16-bit quality. Also to get the corresponding signal/noise ration you will need a 64K sized table which the Arduino doesn't have.


Hi Adrian, this is fantastic! I'm using an arduino duemilanove and it works like a charm. I've been toying with the arrays for some interesting effects! Would it be possible to use another pin for a second voice or would I need two cores? Thanks

You can do either. I have

You can do either. I have successfully made two timers run different oscillators and also done several oscillators on one timer but multiple pins.

Turning it on and off

Just a quick comment for anybody who wants to use this code as a "black box": Get it ready using pinMode(PWM_PIN, OUTPUT); TCCR2A = _BV(WGM20); TCCR2B = _BV(CS20); in the setup. Then when you want to start the wave, call the lines TCCR2A |= _BV(COM2B1); TIMSK2 = _BV(TOIE2); to enable the timer and the interrupt. delayMicroseconds() will not work when the timer is running, but you can still use either delay() or micros() and your own custom delay function. To turn the wave off, use TCCR2A &= ~(_BV(COM2B1)); //deactivate the pin TIMSK2 &= ~(_BV(TOIE2)); //deactivate interrupts on overflow


Hi Thank you for this marvelous piece of code ! Works like a charm. I tried to add an LFO to modulate the main frequency : i instanciate another osc, and i multiply o1.amplitude>>8 by the output of o2 (basically : outputvalue = (((uint8_t)(o1.amplitude>>8)*(((uint8_t)(o2.amplitude>>8)) * pgm_read_byte(sintable+((o2.phase>>16)%LUTsize)))>>8)>>8 * pgm_read_byte(sintable+((o1.phase>>16)%LUTsize)))>>8;. So far, no luck. Do you have any clue on how i could do ? Thanks !

I think you need to add a

I think you need to add a scaled version of modulating oscillator to the phase of the modulated oscillator. Think your code is multiplying the outputs which is AM not FM.