Timer0 & Timer1
One of the first things you should determine is whether your timer is 8-bit or 16-bit. If it is both, then select which one you want. Here's how you derive the equations, based on the following parameters:
- Oscillator Frequency (PIC12F629) = 4 MHz
- Operating Frequency = 1/4 OSC = 1 MHz
- Timer Is Configured As 8-Bit Timer
Now, if we were using a prescaler our operating frequency would be different. For example, a 1:4 prescaler ratio would give me a 250 kHz operating frequency (1 MHz / 4). Now we can derive our equation:
[LATEX]Period_{(s)} = [(256 - Delay)*OpFreq]*2[/LATEX]
Note that I multiply everything by 2, because we have a complete cycle:
Code:
One Cycle
{
Turn ON Output (5V);
Delay;
Turn OFF Output (0V);
Delay;
}
So the timer only gives us the ON and first delay, so we multiply by 2 to get both, or one complete cycle.
To give you an example, let's say we want a frequency output of 10 kHz (1E-4 Seconds).
[LATEX]1E-4 = ((256 - Delay)*1E-6)*2[/LATEX]
[LATEX]Delay = 206[/LATEX]
So you need a delay of 206 entered to give you a 10 kHz output tone (square wave).
Timer0 Code PIC12F629 8-Bit Timer With HI-TECH
Code:
void frq(char pins, unsigned int frqcy, unsigned int timer) // Frequency Function using Timer0 (8-Bit)
{
unsigned int times;
T0IF = 0; // Clear OVF Flag
GPIO = pins; // Initialize GPIO
for(times=timer;times>0;times--) // Duration of playing
{
TMR0 = frqcy & 0xFF; // Load TMR0L byte next
while(!T0IF); // Wait for timer
T0IF = 0; // Clear OVF Flag
GPIO = ~GPIO; // Invert output
}
T0IF = 0; // Clear OVF Flag
}
Timer1 Code PIC12F629 16-Bit Timer With HI-TECH
Code:
void freq(char pins, unsigned int frqcy, unsigned int timer) // Frequency Function using Timer1 (16-Bit)
{
unsigned int times;
TMR1IF = 0; // Clear OVF Flag
GPIO = pins; // Initialize GPIO
for(times=timer;times>0;times--) // Duration of playing
{
TMR1H = (frqcy >> 8) & 0xFF; //Load TMR0H byte first
TMR1L = frqcy & 0xFF; // Load TMR0L byte next
while(!TMR1IF); // Wait for timer
TMR1IF = 0; // Clear OVF Flag
GPIO = ~GPIO; // Invert output
}
TMR1IF = 0; // Clear OVF Flag
}
TImer0 Code PIC18F1320 16-Bit Timer With C18
Code:
void freq(char pins, unsigned int frqcy, unsigned int timer) // Timer0 Frequency Function 16-Bit
{
unsigned int times;
TRISA = ~(pins & 0xFF);
INTCONbits.TMR0IF = 0; // Clear OVF Flag
LATA = pins; // Initialize LATA
T0CON|=0x80;
for(times=timer;times>0;times--) // Duration of playing
{
TMR0H = (frqcy >> 8) & 0xFF; //Load TMR0H byte first
TMR0L = frqcy & 0xFF; // Load TMR0L byte next
while(!INTCONbits.TMR0IF); // Wait for timer
INTCONbits.TMR0IF = 0; // Clear OVF Flag
LATA = ~LATA; // Invert output
}
}
You can enter hex, dec, or bin for the timer input delay. I would recommend dec, since you don't have to convert from hex to dec or something. Also, in my example I had an 8-Bit timer so I used 256 in the equation; if you are using a 16-Bit timer it would be 65536.
Hope this helps you, if you have questions just let me know.