The easiest way is to use the timer1 library written for arduino. You can download it here.
To install, simply unzip and put the files in Arduino/hardware/libraries/Timer1/
Prescaler set for 16Mhz
Prescale Time per counter tick Max Period
1 0.0625 uS 8.192 mS
8 0.5 uS 65.536 mS
64 4 uS 524.288 mS
256 16 uS 2097.152 mS
1024 64uS 8388.608mS
Max Period = (Prescale)(1/Frequency)(2^17)
Time per Tick = (Prescale)*(1/Frequency)
Instructions available using this library are:
You must call this method first to use any of the other methods. You can optionally specify the timer's period here (in microseconds), by default it is set at 1 second. Note that this breaks analogWrite() for digital pins 9 and 10 on Arduino.
Sets the period in microseconds. The minimum period or highest frequency this library supports is 1 microsecond or 1 MHz. The maximum period is 8388480 microseconds or about 8.3 seconds. Note that setting the period will change the attached interrupt and both pwm outputs' frequencies and duty cycles simultaneously.
pwm(pin, duty, period)
Generates a PWM waveform on the specified pin. Output pins for Timer1 are PORTB pins 1 and 2, so you have to choose between these two, anything else is ignored. On Arduino, these are digital pins 9 and 10, so those aliases also work. Output pins for Timer3 are from PORTE and correspond to 2,3 & 5 on the Arduino Mega. The duty cycle is specified as a 10 bit value, so anything between 0 and 1023. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.
Calls a function at the specified interval in microseconds. Be careful about trying to execute too complicated of an interrupt at too high of a frequency, or the CPU may never enter the main loop and your program will 'lock up'. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.
A fast shortcut for setting the pwm duty for a given pin if you have already set it up by calling pwm() earlier. This avoids the overhead of enabling pwm mode for the pin, setting the data direction register, checking for optional period adjustments etc. that are mandatory when you call pwm().
Disables the attached interrupt.
Turns PWM off for the specified pin so you can use that pin for something else.
Reads the time since last rollover in microseconds.
Example - Sets up PWM output on pin 9 with a 50% duty cycle, and attaches an interrupt that toggles digital pin 10 every half second.
* Timer1 library example
* June 2008 | jesse dot tane at gmail dot com
Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
Timer1.pwm(9, 512); // setup pwm on pin 9, 50% duty cycle
Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
digitalWrite(10, digitalRead(10) ^ 1);
// your program here...