Arduino Timers

Some devices require a certain frequency to operate. Arduino has some adjustment capabilities. Use the following codes below to determine which code will achieve what frequency. Note that there are 3 timers in the microcontroller (Timer0, Timer1, Timer2). Timer0 controls the system and track delays and millis so it’s best to leave it alone unless you know what you are doing.

Code Format:

TCCRxB = (TCCRxB & 0xF8) | i;

x = the timer (0,1,2)
i = frequency desired

Timer0 (TCCR0B for pins 5 and 6)
i = 1 62500hz
i = 2 7812hz
i = 3 976hz
i = 4 244hz
i = 5 61hz

Timer1 (TCCR1B for pins 9 and 10)
i = 1 31250hz
i = 2 3906hz
i = 3 488hz
i = 4 122hz
i = 5 30hz

Timer2 (TCCR2B for pins 3 and 11)
i = 1 31250hz
i = 2 3906hz
i = 3 980hz
i = 4 490hz
i = 5 245hz
i = 6 122hz
i = 7 30hz

Example:
TCCR1B = (TCCR1B & 0xF8) | 5;
This code will set the pins 9 and 10 to 30hz

Arduino code:


void setup() {
pinMode(9, OUTPUT); //set pin 9 as an output
TCCR1B = (TCCR1B & 0xF8) | 5; //set timer 1 to “I = 5” which will result in 30hz
}
Void loop(){
analogWrite(9,127); // send pwm of value 127 to pin 9 50% duty cycle
}

Use an oscilloscope to measure the output on pin 9. It should show a square wave at 30hz 50% duty cycle.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.