PIC Lab, PIC16, Experiment #3: Timer TMR0

uC: PIC16F628a

Compiler: Hi-TECH PICC

Goal: To make pulses with frequency 5Hz

Timer TMR0 module frequently used in many applications, it has next useful options:

  • 8 bits counter/timer
  • Internal/external oscillator for pulses counting
  • An interrupt is generated after overflow

In that experiment we will make it without using interruptions.

Timer TMR0 module (from datasheet)

The main diagram can be observed in the official datasheet from the microchip site (that’s where I got the one from beginning). All main setup/whistles can be found in OPTION register.

OPTION register

Looks like we have got everything we need. So from the goal we need to achieve 5 Hz pulses, or a duration 200ms. We have XTAL oscillator 4MHz, so the timer is getting 4/4 = 1 MHz or the 1 us pulse. So whole timer is 8 bit or can make 256 “ticks”, which are equal to 256us, while we need to get 200ms. We have two choices – one is to use a prescaler connected to timer TMR0 module, or the second one – to use extra variable in a similar role. When I wrote the original of that post in Russian language, I did that with the use of the variable. At the current moment of time – I don’t like that decision, but, in order to make everything aligned, I will just translate that code here:

#include <htc.h>
#define _XTAL_FREQ 4000000
 
__CONFIG(WDTDIS & UNPROTECT & MCLREN);
 
unsigned char cnt = 0;
unsigned char i = 0;
unsigned char srb = 0;
void main() {
TRISB = 0b01111111;
RB7 = 0;
for (;;) {
 OPTION = 0b11010111; // counting 256 us
 for (i=1;i<4;i++) {                // 192 мus
 TMR0 = 0;
 while (TMR0 < 250)  { cnt++; }
 }
 OPTION = 0b11010100; // now counting 32 us
 TMR0 = 0; cnt = 0;
 while (TMR0 < 250) {cnt++;}  // 8 ms
 srb = !srb;
 RB7 = srb;
}
 
}

Let’s see now what we got in proteus!

scope from proteus simulation

1 square is 25ms, we have 8 of them or 25*8 = 200 ms. Looks like everything works fine.

The source code for that experiment can be found here.

1 thought on “PIC Lab, PIC16, Experiment #3: Timer TMR0

  1. Pingback: Pic Lab, PIC16, Experiment #5: interruptions | diymicro.org

Leave a Reply

Your email address will not be published.