Timer 0, a simple Counter in 8-bit PIC you need to know

Timer 0, a simple Counter in 8-bit PIC you need to know

Instead of creating software to count seconds or pulses, a specific hardware was created to deal with this necessity called ‘timers'. There is a bunch of different kinds of timers and they certainly vary in every microcontroller. For this tutorial, I will cover how to setup the Timer 0 in the 8-bit PIC microcontroller PIC16F628A. It's so simple that in fact, it's always running because you can't turn it off.

Background vector created by iconicbestiary – www.freepik.com

Before reading this, you will need to know how to setup MPLAB IDE and how to connect the PICkit to the PIC microcontroller. If not, check them out first. Check out also another projects for beginners in 8-bit PIC microcontrollers.

Requirements for Timer 0

Components and Devices

In this tutorial, all the components are Through Hole.

  • LED, any color or size: 1 unit.
  • PIC16F628A: 1 unit.
  • Resistors, 1/2 or 1/4W, 5% tolerance:
    • 1KΩ, : 1 unit.

Check out the commercial values of resistors and capacitors here.

PIC microcontroller

For this tutorial, I will use the 8-bit microcontroller PIC16F628A. This one is the very first one that I learned to program. Very practical too. Be sure to select Through Hole or ‘TH' version. Surface Mounted won't fit in the breadboard.

DIP 18 pins Integrated Circuit IC
This is a typical DIP IC with 18 pins

Download the datasheet here. I recommend that you print in reduced A4 all the datasheet because it will serve you as quick reference.

Tools and Machinery

  • Breadboard: 1 unit.
  • AC/DC Power Adapter to 5V DC, with at least 500mA: 1 unit.
  • Jumper or UTP Wires: various.
  • Multimeter: 1 unit.

How is Timer 0 calculated?

Whenever you need to count something and do certain after a certain time, timer do become quite helpful. You just need to configure a few parameters and bits and the timer will begin to run in the background. When the time count has reach the upper limit threshold, an interrupt will emerge and then the microcontroller will attend the situation.

Timer 0 is a 8-bit counter. This means it can count from 0 to 255 (i.e. 2^8). But to make it useful, it counts from a start point that you decide until 255. Therefore, the time to complete this counting will vary.

x -> 255

Every time there is a overflow (from 255 to ‘256'), the Timer 0 flag will be set and the task or command will be executed.

Defining the Time required

How is this starting point ‘x' calculated? Let's take a look at a few variables that we need to know.

Firstly, determine the desired time. For example, let's calculate a timer that executes a task or command every 10ms (milliseconds).

Afterwards, 2 variables defines how the desired time can be achieved: the clock frequency and the prescaler. The faster the clock frequency is, the shorter the timer can be. Both parameters has to be adjusted properly to reach close enough to the time designed for the Timer 0. This formula is required:

Timer 0 formula

    \[ TMR0=256-\frac{t_{d}*f}{4*prescaler} \]

where TMR0 is a variable ‘x' mentioned earlier, td is the time desired, f is the clock frequency and the prescaler is a parameter let us reduce the time to count. I highly recommend you to download the calculator of the Timer 0 for 8-bit PIC microcontrollers for free. Use the following form to complete.

Let's use the internal 4Mhz clock frequency, therefore fill 4 in the Frequency prompt and 10 in Time Desired. Now, let's choose from various prescalers to see which one could give us a preciser result. Firstly, I chose prescaler 2 but it was to high (TMR0 results in a negative value). After a few tries, prescaler 64 results in a positive value with only 0,16%; quite good!

Now that the time is defined, let's see how it's configured in this 8-bit PIC microcontroller.

Programming the Timer 0

Configuration Bits

On table 6-1, located in page 47, the registers associated with Timer 0 are displayed. Let's start with the Option Register.

Firstly, in the function config() the registers are configured to match the desired operation. To do so, go to page 23 in the datasheet to read about the ‘Register 4-2: Option Register'. The bit T0CS must be set to 0 in order to count with the internal clock. Next, the bit PSA must be set to 0 for the prescaler to work with the Timer 0. The final bits PS2:PS0 has to correspond to the column ‘TMR0 Rate' in the table. In this case, the prescaler 64 will be 101. Translated that into code would be:

//Timer 0 configuration
T0CS=0;
PSA=0;
PS2=1; PS1=0; PS0=1;

Afterwards, the Timer 0 enable bit must be set and its flag bit reset. Finally, the Global Interrupt Enable must be set.

TMR0IF=0;
TMR0IE=1;

GIE=1; 

Now, it's configured. But what should it do every time that the overflow occurs? Let's deal with the interrupt.

Interrupt Function

If you haven't read about the Interrupt Sources or how to handle Functions in C, check them out first.

Create the function called void __interrupt(void) interruptFunction(). From this place, all the interrupts are handled. Specify the enable bit and flag bit in order to enter the function. In addition, write the Routine_Tmr0() to specify where it should go next if Timer 0 requires the attention.

//Interrupt Sources
  if(TMR0IE && TMR0IF) {
    TMR0IE=0; //Disable Timer 0 interrupt
    Routine_Tmr0();
    TMR0IF=0; //Once attended, erase the interrupt flag from Timer 0
    TMR0IE=1; //Enable Timer 0 interrupt
  }

And now, let's attend the interrupt of Timer 0 caused by the overflow. Let's program a small LED blink, the same way it was done in the previous tutorial.

void Routine_Tmr0(){
 PORTBbits.RB3=1; //LED On
      
 //delay
 int x;
 x=0;
 while(x<100) x++;
      
 PORTBbits.RB3=0; //LED Off
}

Extra Coding

On MPLab, select ‘Production' tab from the main menu and then clic ‘Set Configuration bits'. Select the following options:

 /*-------------------------------------------------------------------
  1. DEFINITION OF BITS, PINS, ALIASES, CONSTANTS
---------------------------------------------------------------------*/
// CONFIG
#pragma config FOSC = INTOSCIO  // Oscillator Selection bits (INTOSC oscillator: I/O function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = OFF      // RA5/MCLR/VPP Pin Function Select bit (RA5/MCLR/VPP pin function is digital input, MCLR internally tied to VDD)
#pragma config BOREN = ON       // Brown-out Detect Enable bit (BOD enabled)
#pragma config LVP = ON         // Low-Voltage Programming Enable bit (RB4/PGM pin has PGM function, low-voltage programming enabled)
#pragma config CPD = OFF        // Data EE Memory Code Protection bit (Data memory code protection off)
#pragma config CP = OFF         // Flash Program Memory Code Protection bit (Code protection off)

// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.

#include <xc.h>

In the config() put the pin configuration (1 for everything except for RB3).

//Pin Configuration
    TRISA = 0b1111111; //RA7 to RA0.
    TRISB = 0b11110111; //RB7 to RB0.
    PORTBbits.RB3=0;

Don't forget to add the While(1) in the Main function to make it run forever!

while(1) {

}

Download the code of Timer 0

If you would like to see and read the whole code through, enter your name and e-mail in the form below to download the project. I promise that I won’t send you spam; just relevant content to the blog. If you don’t see any form below, please click here.

Schematic of Timer 0

For reference, here is the schematic used for the Timer 0.

Blinking LED
Schematic for the Hello World

Picture of Timer 0

This is how the Timer 0 looks like in the breadboard.

Testing Timer 0

After programming the PIC microcontroller (follow this link if you don't know how), the LED seems to be dimmed or not as bright as when it's connected to 5V. This happens because the LED is only turned on for a fraction of a second and then it's turned off again.

This technique is called PWM but there are specific tools and hardware in this microcontroller for the task. I will write another tutorial about the topic.

Did you notice it? The While(1) function is empty. The Blinking LED is working only by interruptions. There is no need to add here extra code.

Conclusion

To summarize, Timer 0 was configured to achieve the execution of certain code every 10ms. The code was programmed into the PIC16F628A successfully and tested. A video and a foto is attached to demonstrate the functioning.

Timer 0 is helpful for refreshing information in a screen or indicator, such as a 7-segment displays. The technique is called Multiplexing and you can read more about it here. Soon I will write how to use it for such purpose.

The next tutorial will be about using the Timer 0 as ‘External Counter', which is interesting as it sounds. Stay tuned for this future post.

Further reading

To read more about the beginner's guide to 8-bit PIC microcontrollers, refer to the following posts:

How to drive 7-Segment Displays with a 8-bit PIC - Learn how to drive 7-segment displays using the PIC16F684 microcontroller. Download the code and watch an example. Click here to…
Multiplexing Traffic Lights easily in a PIC microcontroller - Using the 8-bit PIC16F684, a circuit for multiplexing traffic lights is assembled in a breadboard with simple LEDs. Click here…
Timer 1, how to make a reliable Real Time Clock in 8-bit PIC - In this tutorial, a Real Time Clock RTC is done using Timer 1 and the 32768Hz oscillator in a PIC…
Timer 0 Timer 0 as External Counter in 8-bit PIC microcontroller - Timer 0 can also be set as external counter. This way it can act upon reaching a certain threshold. Click…
Timer 0 Timer 0, a simple Counter in 8-bit PIC you need to know - Timer 0 is a counter that is always working and it's used commonly to refresh information on screens. Click here…
Interrupt sources in 8-bit PIC and how to quickly attend them - Interrupts are the critical way to manage emergent situations in a PIC microcontroller. Click here to read to learn the…
Code Template Code Template, an easy guide for PIC Microcontrollers in C - Writing a program with order is a time saver. Download today the code template for PIC microcontrollers for free. Click…
Blinking LED with a PIC microcontroller, a helpful Indicator - Learn how to continuously turn on and off a simple LED; in other words, to blink a LED. The microcontroller…
Hello World with 8-bit PIC microcontroller - Hello World is the first code in any programming language and now it's applied to a PIC microcontroller. Click here…
PICKIT 4 How to connect any PICkit to a microcontroller - PICkits are the tools for programming PIC microcontrollers. Do you want to learn how to connect a PICkit? Click here…

You have reached this far!

Thank you for reading the blog post. Your comments and suggestions are welcomed. At the bottom of this page, leave a message or just say hi! The whole team of techZorro will appreciate it. Don't forget to share it on social media as well.

techZorro’s Index of Content

Click on the following link to browse likewise content in the blog in techZorro. This index will help you see what you are looking for in a bird’s eye view.

techZorro's Newsletter!

If you enjoyed this blog post, please subscribe to techZorro’s newsletter so you don’t miss any future blog posts!

techZorro's Index of Content

Keep Reading!

3 Comments

Leave a Reply

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