Programming Timer1 on the Atmega328p

Thread Starter

LukeNodag

Joined Oct 24, 2015
1
Hello, I am currently learning how to create clock signals using Timer1 on the 328p and was wondering how to create a 1kHz square wave with a 50% duty cycle using CTC mode. I have been looking for how to manipulate the registers to create it but the resources I've come across have been fairly unhelpful. I'm using the Arduino programming environment. Thank you very much for your time
 

d0ughb0y

Joined Aug 18, 2015
5
First you need to figure how much you want to divide the clock (16Mhz). that is the prescaler.
Once you get the frequency (after dividing with prescale value), get the time (period).
That is the time it takes for the timer counter to increment.

There are several ways to generate a 50% square wave.
If you use CTC, you get an interrupt when the counter matches the output compare register.
In the ISR you can toggle the pin that outputs the square wave.

For 1khz, the period is 1 milliseconds. Which means you need to toggle every 500 us.

If you divide 16mhz by 8, that gives you 2mhz. The period is 0.5 us. timer counter is incremented once every 0.5us.
you need to count up 1000 times for 500 us to elapse (you want to toggle every 500 us).
So you need to set the OCR to 1000. Since this is >255, you need to use the 16 bit timer.

If you divide 16mhz by 64, that gives you 250khz, the period is 4us.
You need to count up 125 times for 500us to elapse. So you need to set OCR to 125. For this you can use 8 bit timer.

From here, you can expand to say create a pwm signal that can vary from 0 to 100% duty cycle. Read the atmega datasheet chapter on timer. Everything you need to know is there.
 
Top