 # Generating 2 frequencies with timer 1 AND 2

Hello all,

I am trying to generate binaureal beats using the arduino. For this I need to generate two different frequencies at the same time, for example 400 and 414 HZ.

I want Timer1 to generate the 400 on one pin, and Timer2 to generate the 414 on another Pin, both at the same time.

I have no problem using FrequencyTimer2 to generate the frequencey with Timer2, but I have no clue how to do the same with Timer1.

The original idea is based on the Sound and Light Machine from Make Magazine 10, which runs on a ATTiny123. The source code for that can be found here:

http://www.makezine.com/10/brainwave/

In the "SLM Documentation" PDF, the source code is well documented but I do not know what needs to be changed to run it on Arduino.

For those who it may interest, I found out.

Generate two sounds,

one 400Hz (400.641 exactly, using 8 bit timer2, output on Arduino Board Pin 11 (ATMega168 Pin PB3) one 415Hz (using 16 bit timer1, output on Arduino Board Pin 9 (ATMega168 Pin PB1)

To generate different frequencies of binaural beats, change freq of timer1, as it is more accurate.

here is the code:

``````uint8_t pre, top;

uint16_t top2;

unsigned long periode = 0;
unsigned long clock = 0;
int freq = 0;

void setup() {

DDRB = 0xFF;  //all ports B as output
PORTB = 0x00; //all values to low ?

clock = clockCyclesPerMicrosecond()*1000000; //for 16Mhtz , this gives 16.000.000

//set up timer1
TIMSK1 = 0;  //Dont generate any interrupts from timer 1
TCCR1B = 0;  //we set to zero before we do anything else
TCCR1A = 0;
TCNT1H = 0;
TCNT1L = 0;

freq = 415;  //415 Hz frerquency

periode = clock/(2*freq); //multiply by 2, because its only toggled once per cycle
pre = 1; //predivide by nothing, Timer 1 is 16bit
top2 = periode; // if we predivide, it should be here

TCCR1B = ( _BV(WGM12) | pre);  //set the predivide, in this case 1 = 001 means no prescaling
TCCR1C = 0;
OCR1A = top2;  //16bit register, top2 should be uint16
TCCR1A = _BV(COM1A0);  //start the timer

//set up timer2

TIMSK2 = 0 ;  //We do NOT Generate interrupts

TCCR2B = 0;  //we set to zero before we do anything else
TCCR2A = 0;
TCNT2 = 0;

freq = 400;  //set frequency to 400 hz

periode = clock/(2*freq);
pre = 5; //predivide by 128, Binary 101 for Timer 2 !!
top = periode/128;

ASSR &= ~_BV(AS2);    // use clock, not T2 pin
TCCR2A = (_BV(WGM21) | _BV(COM2A0) );
TCCR2B = pre;  //set the predivide
OCR2A = top;
}
``````

Claude,

I am doing the same thing as you, and now it looks like you've done the hard work for me. Your code seems to work, how did you end up timing the LED lights?

if i would like to do the same on PORTD
what instruction i have to change ?

thx