Friday, May 23, 2008

PIC Clock

Finally I managed to build the initial version of the Desktop clock using PIC16F84. Still its in the vero board as you see in below video.



It shows Time (Hour, Minute) and Seconds alternatively. It has two buttons to advance hours and minutes. An Interrupt routine is used to calculate the base time and to multiplex the four seven segments. The program is written in C and compiled using MikroC compiler. I got lot of ideas from so many people and used code samples from various resources. Specially the MikroC comes with very useful code samples. Here is the program listing. It is not optimized yet. You'll find unused variables here and there. Comments and suggestions are welcome.


#include "Display_utils.h"

char kraj;
unsigned short zz, v, j, countsec,displaysec;
//unsigned int i;
unsigned short por[4];

unsigned char sec, mins, hrs, ticks, correction;
char oldstate_min, oldstate_hr;


void interrupt() {

if(INTCON.T0IF)
{
ticks++;
correction++;
TMR0=101; //96; //102

if (correction==180) // Correction routine
{
ticks--;
correction=0;
}
}



PORTA = ~0;
PORTB = por[v];
PORTA = ~zz; // turn on appropriate 7seg. display
zz <<= 1;
if (zz > 8u)
zz = 1; // prepare mask for digit

v++ ;
if (v > 3u)
v = 0; // turn on 1st, turn off 2nd 7seg.
//Delay_ms(1);
//TMR0 = 0;
INTCON = 0x20;
}//~

void main() {
OPTION_REG = 0x84;
j = 0;
v = 0;
zz = 1;
TMR0 = 101;
INTCON = 0xA0; // Disable PEIE,INTE,RBIE,T0IE
PORTA = ~0;
TRISA = 0;
PORTB = 0;
TRISB = 0;
sec=0;
mins=0;
ticks=0;
correction=0;
hrs=0;
oldstate_min=0;
oldstate_hr=0;


do {

if (ticks==200)
{
sec++;
countsec++;
ticks=0;

//if (PORTB.F7==1)
// {
// PORTB.F7=1;
// }
// else
// {
// PORTB.F7=0;
// }
//}
if (sec>59)
{
mins++;
sec=0;

//}

if (mins>59)
{
hrs++;
mins=0;
//}


if (hrs>23)
{
hrs=0;
}

}
}
}
TRISB=0b00000011;
if (Button(&PORTB, 0, 1, 1))
oldstate_min = 1;
if (oldstate_min && Button(&PORTB, 0, 1, 0)) {
mins++;
if (mins>59)
mins=0;
oldstate_min = 0;
}
if (Button(&PORTB, 1, 1, 1))
oldstate_hr = 1;
if (oldstate_hr && Button(&PORTB, 1, 1, 0)) {
hrs++;
if (hrs>23)
hrs=0;
oldstate_hr = 0;
}

TRISB=0b00000000;



if (countsec==5)
{
countsec=0;
if (displaysec==1)
{
displaysec=0;
}
else
{
displaysec=1;
}
}


if (displaysec==0)
{
por[0]=mask(hrs/10u);
j=(char)(hrs%10u);
por[1]=mask(j);

por[3]=mask(mins/10u);
j=(char)(mins%10u);
por[2]=mask(j);
}
else
{
por[0]=mask(5);
//j=(char)(mins%10u);
por[1]=mask(11);

por[3]=mask(sec/10u);
j=(char)(sec%10u);
por[2]=mask(j);
}


} while(1); // endless loop
}//~




Display_utils.h file


//-------------- Returns mask for common cathode 7-seg. display
unsigned short mask(unsigned short num) {
switch (num) {
case 0 : return 0x3F;
case 1 : return 0x06;
case 2 : return 0x5B;
case 3 : return 0x4F;
case 4 : return 0x66;
case 5 : return 0x6D;
case 6 : return 0x7D;
case 7 : return 0x07;
case 8 : return 0x7F;
case 9 : return 0x6F;
case 11 : return 0x79;
} //case end
}//~