Pic Lab, PIC16, Experiment #8, The timer1 module

The goal: to get 1 Hz pulses.

What do we have: PIC16f628a, a handmade devboard, and proteus

Continuing to learn pic microcontrollers, and the timer1 is the next module in our way. Usually, this is a 16bit timer, so it allows to have a larger time frame.

timer1 block diagram, pic16f628a datasheet

The timer has two main purposes: counter of pulses or timer. I don’t use a counter, but I do use a timer a lot. The main control bits are in the register T1CON:

T1CON register

Let me calculate what the configuration should be for 1Hz pulses, if we have the quartz frequency equal to 32.768KHz:

Fosc  =  32.768 kHz

F0sc/4 = 8192 Hz

Prescaler can make F = 1024 Hz

1 tick = 0.0009765625 seconds

0.5/0.0009765625  = 512 (we are going to change the value at pin at each half of the period, and the duty cycle is 50%)

16 bits give us 65536 “ticks”, but we need only 512, so we need to preset it to: 65536 – 512 = 65024

And the resulting config is:

TMR1H = 0b11111110; TMR1L = 0x00;

And the code:

#include <htc.h>
#define _XTAL_FREQ 32768
 
__CONFIG(WDTDIS & UNPROTECT & MCLREN & LVPDIS);
 
void main() {
__delay_ms(100); 
TRISB = 0x00;
PORTB = 0x00;
T1CKPS1 = 1;
T1CKPS0 = 1; // prescaler to /8
 
T1OSCEN = 0; 
TMR1CS = 0; // Fosc/4
GIE = 1;   // global interrupt
PEIE = 1;  
TMR1IE = 1; // tmr1 interrupt
TMR1ON = 1; // enabling timer
TMR1H = 0b11111110; TMR1L = 0x00;  //init timer value 65024
 
for (;;) {
 //just a cycle
 }
 
}
 
interrupt isr() {
 
if (TMR1IF) {
TMR1H = 0b11111110; TMR1L = 0x00;
RB5 = !RB5;
TMR1IF = 0;  
}
 
}
the result of the code

The source of the code can be found there. Although remember it was done in 2011, now when I’m translating the article to English is 2022 on the Earth, and we have 30+ versions of xc8 which already evolved to something strange, with a complete change of syntax for port bits and interrupts, and who knows what else. So don’t blame me I guess.

Leave a Reply

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